blob: 7e637615580c31a921b1fa2efea881faeaa94e56 [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
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004952 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09004953 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004954 mHandler.sendMessageDelayed(
4955 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4956 PROMPT_UNVALIDATED_DELAY_MS);
4957 }
4958
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004959 @Override
4960 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08004961 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004962 mHandler.post(() -> {
4963 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4964 if (nai == null) return;
4965 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004966 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004967 });
4968 }
4969
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004970 /**
4971 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4972 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004973 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004974 * @param appExtras Bundle to use as intent extras for the captive portal application.
4975 * Must be treated as opaque to avoid preventing the captive portal app to
4976 * update its arguments.
4977 */
4978 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004979 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08004980 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4981 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004982
4983 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4984 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004985 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4986 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004987 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4988
lucaslin75ff7022020-12-17 04:14:35 +08004989 final long token = Binder.clearCallingIdentity();
4990 try {
4991 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4992 } finally {
4993 Binder.restoreCallingIdentity(token);
4994 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004995 }
4996
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004997 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4998 private final Network mNetwork;
4999
5000 private CaptivePortalImpl(Network network) {
5001 mNetwork = network;
5002 }
5003
5004 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005005 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005006 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5007 enforceSettingsPermission();
5008 }
5009
Chiachang Wang938bfba2020-01-09 13:50:55 +08005010 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005011 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005012 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005013 }
5014
5015 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005016 public void appRequest(final int request) {
5017 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5018 if (nm == null) return;
5019
5020 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005021 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005022 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005023 }
5024 }
5025
5026 @Nullable
5027 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5028 // getNetworkAgentInfoForNetwork is thread-safe
5029 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5030 if (nai == null) return null;
5031
5032 // nai.networkMonitor() is thread-safe
5033 return nai.networkMonitor();
5034 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005035 }
5036
Hugo Benichic9048bc2016-09-14 23:23:08 +00005037 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005038 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005039 }
5040
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005041 /**
5042 * Return whether the device should maintain continuous, working connectivity by switching away
5043 * from WiFi networks having no connectivity.
5044 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5045 */
5046 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005047 if (!checkNetworkStackPermission()) {
5048 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5049 }
5050 return avoidBadWifi();
5051 }
5052
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005053 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005054 ensureRunningOnConnectivityServiceThread();
5055 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005056 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005057 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005058 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005059 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5060 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5061 for (final NetworkOfferInfo noi : offersToUpdate) {
5062 updateOfferScore(noi.offer);
5063 }
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005064 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005065 }
5066
Erik Kline95ecfee2016-10-02 18:02:14 +09005067 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005068 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005069 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005070 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005071 if (!configRestrict) {
5072 pw.println("Bad Wi-Fi avoidance: unrestricted");
5073 return;
5074 }
5075
5076 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5077 pw.increaseIndent();
5078 pw.println("Config restrict: " + configRestrict);
5079
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005080 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005081 String description;
5082 // Can't use a switch statement because strings are legal case labels, but null is not.
5083 if ("0".equals(value)) {
5084 description = "get stuck";
5085 } else if (value == null) {
5086 description = "prompt";
5087 } else if ("1".equals(value)) {
5088 description = "avoid";
5089 } else {
5090 description = value + " (?)";
5091 }
5092 pw.println("User setting: " + description);
5093 pw.println("Network overrides:");
5094 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005095 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005096 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005097 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005098 }
5099 }
5100 pw.decreaseIndent();
5101 pw.decreaseIndent();
5102 }
5103
paulhu7746e4e2020-06-09 19:07:03 +08005104 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5105 // unify the method.
5106 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5107 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5108 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5109 return settingsComponent != null
5110 ? settingsComponent.getPackageName() : "com.android.settings";
5111 }
5112
lucaslinb1e8e382019-01-24 15:55:30 +08005113 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005114 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005115 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005116 switch (type) {
5117 case NO_INTERNET:
5118 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005119 // High priority because it is only displayed for explicitly selected networks.
5120 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005121 break;
lucasline117e2e2019-10-22 18:27:33 +08005122 case PRIVATE_DNS_BROKEN:
5123 action = Settings.ACTION_WIRELESS_SETTINGS;
5124 // High priority because we should let user know why there is no internet.
5125 highPriority = true;
5126 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005127 case LOST_INTERNET:
5128 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005129 // High priority because it could help the user avoid unexpected data usage.
5130 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005131 break;
lucaslin2240ef62019-03-12 13:08:03 +08005132 case PARTIAL_CONNECTIVITY:
5133 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005134 // Don't bother the user with a high-priority notification if the network was not
5135 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005136 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005137 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005138 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005139 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005140 return;
5141 }
5142
5143 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005144 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005145 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005146 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005147 // Some OEMs have their own Settings package. Thus, need to get the current using
5148 // Settings package name instead of just use default name "com.android.settings".
5149 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5150 intent.setClassName(settingsPkgName,
5151 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005152 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005153
paulhu2af50222020-10-11 22:52:27 +08005154 PendingIntent pendingIntent = PendingIntent.getActivity(
5155 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005156 0 /* requestCode */,
5157 intent,
paulhu2af50222020-10-11 22:52:27 +08005158 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005159
Serik Beketayevec8ad212020-12-07 22:43:07 -08005160 mNotifier.showNotification(
5161 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005162 }
5163
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005164 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5165 // Don't prompt if the network is validated, and don't prompt on captive portals
5166 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005167 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005168 return false;
5169 }
5170
5171 // If a network has partial connectivity, always prompt unless the user has already accepted
5172 // partial connectivity and selected don't ask again. This ensures that if the device
5173 // automatically connects to a network that has partial Internet access, the user will
5174 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005175 // because we have prompted them.
5176 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005177 return true;
5178 }
5179
5180 // If a network has no Internet access, only prompt if the network was explicitly selected
5181 // and if the user has not already told us to use the network regardless of whether it
5182 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005183 if (nai.networkAgentConfig.explicitlySelected
5184 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005185 return true;
5186 }
5187
5188 return false;
5189 }
5190
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005191 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09005192 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005193 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5194
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005195 if (nai == null || !shouldPromptUnvalidated(nai)) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005196 return;
5197 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005198
5199 // Stop automatically reconnecting to this network in the future. Automatically connecting
5200 // to a network that provides no or limited connectivity is not useful, because the user
5201 // cannot use that network except through the notification shown by this method, and the
5202 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005203 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005204
lucaslin2240ef62019-03-12 13:08:03 +08005205 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
5206 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
5207 // popup the notification immediately when the network is partial connectivity.
Chalard Jean254bd162022-08-25 13:04:51 +09005208 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005209 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005210 } else {
5211 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5212 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005213 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005214
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005215 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5216 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005217 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005218
lucaslin2240ef62019-03-12 13:08:03 +08005219 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5220 return;
5221 }
5222
5223 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005224 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005225 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005226 }
5227
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005228 @Override
5229 public int getMultipathPreference(Network network) {
5230 enforceAccessPermission();
5231
5232 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005233 if (nai != null && nai.networkCapabilities
5234 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005235 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5236 }
5237
Aaron Huang9a57acf2020-12-08 10:03:29 +08005238 final NetworkPolicyManager netPolicyManager =
5239 mContext.getSystemService(NetworkPolicyManager.class);
5240
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005241 final long token = Binder.clearCallingIdentity();
5242 final int networkPreference;
5243 try {
5244 networkPreference = netPolicyManager.getMultipathPreference(network);
5245 } finally {
5246 Binder.restoreCallingIdentity(token);
5247 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005248 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005249 return networkPreference;
5250 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005251 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5252 }
5253
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005254 @Override
5255 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005256 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005257 }
5258
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005259 private class InternalHandler extends Handler {
5260 public InternalHandler(Looper looper) {
5261 super(looper);
5262 }
5263
5264 @Override
5265 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005266 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005267 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005268 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005269 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005270 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005271 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005272 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005273 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005274 break;
5275 }
Jason Monka69f1b02013-10-10 14:02:51 -04005276 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005277 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5278 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005279 break;
5280 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005281 case EVENT_REGISTER_NETWORK_PROVIDER: {
5282 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005283 break;
5284 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005285 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5286 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005287 break;
5288 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005289 case EVENT_REGISTER_NETWORK_OFFER: {
5290 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5291 break;
5292 }
5293 case EVENT_UNREGISTER_NETWORK_OFFER: {
5294 final NetworkOfferInfo offer =
5295 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5296 if (null != offer) {
5297 handleUnregisterNetworkOffer(offer);
5298 }
5299 break;
5300 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005301 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005302 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5303 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5304 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005305 break;
5306 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005307 case EVENT_REGISTER_NETWORK_REQUEST:
5308 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005309 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005310 break;
5311 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005312 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5313 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005314 handleRegisterNetworkRequestWithIntent(msg);
5315 break;
5316 }
Erik Kline155a59a2015-11-25 12:49:38 +09005317 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5318 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5319 handleTimedOutNetworkRequest(nri);
5320 break;
5321 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005322 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5323 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5324 break;
5325 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005326 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005327 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5328 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005329 break;
5330 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005331 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005332 Network network = (Network) msg.obj;
5333 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005334 break;
5335 }
lucaslin2240ef62019-03-12 13:08:03 +08005336 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5337 Network network = (Network) msg.obj;
5338 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5339 toBool(msg.arg2));
5340 break;
5341 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005342 case EVENT_SET_AVOID_UNVALIDATED: {
5343 handleSetAvoidUnvalidated((Network) msg.obj);
5344 break;
5345 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005346 case EVENT_PROMPT_UNVALIDATED: {
5347 handlePromptUnvalidated((Network) msg.obj);
5348 break;
5349 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005350 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5351 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005352 break;
5353 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005354 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005355 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005356 mKeepaliveTracker.handleStartKeepalive(msg);
5357 break;
5358 }
5359 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005360 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005361 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5362 int slot = msg.arg1;
5363 int reason = msg.arg2;
5364 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
5365 break;
5366 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005367 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5368 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5369 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005370 break;
5371 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005372 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5373 handlePrivateDnsSettingsChanged();
5374 break;
dalyk1720e542018-03-05 12:42:22 -05005375 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5376 handlePrivateDnsValidationUpdate(
5377 (PrivateDnsValidationUpdate) msg.obj);
5378 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005379 case EVENT_UID_BLOCKED_REASON_CHANGED:
5380 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005381 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005382 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5383 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5384 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005385 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005386 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5387 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005388 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005389 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005390 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005391 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005392 final Pair<List<ProfileNetworkPreferenceList.Preference>,
5393 IOnCompleteListener> arg =
5394 (Pair<List<ProfileNetworkPreferenceList.Preference>,
5395 IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005396 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005397 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005398 }
lucaslin1193a5d2021-01-21 02:04:15 +08005399 case EVENT_REPORT_NETWORK_ACTIVITY:
5400 mNetworkActivityTracker.handleReportNetworkActivity();
5401 break;
paulhu51f77dc2021-06-07 02:34:20 +00005402 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5403 handleMobileDataPreferredUidsChanged();
5404 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005405 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5406 final long timeMs = ((Long) msg.obj).longValue();
5407 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5408 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01005409 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
5410 handleIngressRateLimitChanged();
5411 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005412 }
5413 }
5414 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005415
Lorenzo Colittid6459092016-07-04 12:55:44 +09005416 @Override
markchien5776f962019-12-16 20:15:20 +08005417 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005418 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08005419 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005420 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5421 Context.TETHERING_SERVICE);
5422 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005423 }
5424
Lorenzo Colittid6459092016-07-04 12:55:44 +09005425 @Override
markchien5776f962019-12-16 20:15:20 +08005426 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005427 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08005428 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005429 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5430 Context.TETHERING_SERVICE);
5431 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005432 }
5433
Lorenzo Colittid6459092016-07-04 12:55:44 +09005434 @Override
markchien5776f962019-12-16 20:15:20 +08005435 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005436 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005437 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005438 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5439 Context.TETHERING_SERVICE);
5440 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005441 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005442
markchien5776f962019-12-16 20:15:20 +08005443
Lorenzo Colittid6459092016-07-04 12:55:44 +09005444 @Override
markchien5776f962019-12-16 20:15:20 +08005445 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005446 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005447 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005448 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5449 Context.TETHERING_SERVICE);
5450
5451 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005452 }
5453
Lorenzo Colittid6459092016-07-04 12:55:44 +09005454 @Override
markchien5776f962019-12-16 20:15:20 +08005455 @Deprecated
5456 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08005457 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005458 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5459 Context.TETHERING_SERVICE);
5460
5461 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005462 }
5463
Udam Saini8f7d6a72017-06-07 12:06:28 -07005464 @Override
markchien5776f962019-12-16 20:15:20 +08005465 @Deprecated
5466 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08005467 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005468 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5469 Context.TETHERING_SERVICE);
5470 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005471 }
5472
Robert Greenwalte0b00512014-07-02 09:59:16 -07005473 // Called when we lose the default network and have no replacement yet.
5474 // This will automatically be cleared after X seconds or a new default network
5475 // becomes CONNECTED, whichever happens first. The timer is started by the
5476 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005477 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005478 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005479 if (mNetTransitionWakeLock.isHeld()) {
5480 return;
5481 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005482 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005483 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5484 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005485 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005486 mWakelockLogs.log("ACQUIRE for " + forWhom);
5487 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005488 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005489 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005490 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005491 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005492
Hugo Benichi471b62a2017-03-30 23:18:10 +09005493 // Called when we gain a new default network to release the network transition wakelock in a
5494 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5495 // message is cancelled.
5496 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005497 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005498 if (!mNetTransitionWakeLock.isHeld()) {
5499 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005500 }
5501 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005502 // Cancel self timeout on wakelock hold.
5503 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5504 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5505 mHandler.sendMessageDelayed(msg, 1000);
5506 }
5507
5508 // Called when either message of ensureNetworkTransitionWakelock or
5509 // scheduleReleaseNetworkTransitionWakelock is processed.
5510 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5511 String event = eventName(eventId);
5512 synchronized (this) {
5513 if (!mNetTransitionWakeLock.isHeld()) {
5514 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005515 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005516 return;
5517 }
5518 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005519 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5520 mTotalWakelockDurationMs += lockDuration;
5521 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5522 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005523 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005524 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005525 }
5526
Robert Greenwalt986c7412010-09-08 15:24:47 -07005527 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005528 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005529 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005530 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005531 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005532 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005533 }
5534
Lorenzo Colittid6459092016-07-04 12:55:44 +09005535 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005536 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005537 enforceAccessPermission();
5538 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005539 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005540 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005541
5542 final NetworkAgentInfo nai;
5543 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005544 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005545 } else {
5546 nai = getNetworkAgentInfoForNetwork(network);
5547 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005548
5549 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005550 mHandler.obtainMessage(
5551 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005552 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005553
Hugo Benichid6b510a2017-04-06 17:22:18 +09005554 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005555 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005556 if (nai == null
5557 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005558 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005559 return;
5560 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005561 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09005562 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005563 mConnectivityDiagnosticsHandler.sendMessage(
5564 mConnectivityDiagnosticsHandler.obtainMessage(
5565 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5566 new ReportedNetworkConnectivityInfo(
5567 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005568 return;
5569 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005570 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005571 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005572 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005573 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005574 // Validating a network that has not yet connected could result in a call to
5575 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09005576 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005577 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005578 }
paulhu7aeba372020-12-30 00:42:19 +08005579 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5580 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005581 return;
5582 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005583
5584 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5585 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5586 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5587 // completed.
5588 mConnectivityDiagnosticsHandler.sendMessage(
5589 mConnectivityDiagnosticsHandler.obtainMessage(
5590 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5591 new ReportedNetworkConnectivityInfo(
5592 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005593 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005594 }
5595
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005596 // TODO: call into netd.
5597 private boolean queryUserAccess(int uid, Network network) {
5598 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5599 if (nai == null) return false;
5600
5601 // Any UID can use its default network.
5602 if (nai == getDefaultNetworkForUid(uid)) return true;
5603
5604 // Privileged apps can use any network.
5605 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5606 return true;
5607 }
5608
5609 // An unprivileged UID can use a VPN iff the VPN applies to it.
5610 if (nai.isVPN()) {
5611 return nai.networkCapabilities.appliesToUid(uid);
5612 }
5613
5614 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5615 // sockets, i.e., if it is the owner.
5616 final NetworkAgentInfo vpn = getVpnForUid(uid);
5617 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5618 && uid != vpn.networkCapabilities.getOwnerUid()) {
5619 return false;
5620 }
5621
5622 // The UID's permission must be at least sufficient for the network. Since the restricted
5623 // permission was already checked above, that just leaves background networks.
5624 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5625 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5626 }
5627
5628 // Unrestricted network. Anyone gets to use it.
5629 return true;
5630 }
5631
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005632 /**
5633 * Returns information about the proxy a certain network is using. If given a null network, it
5634 * it will return the proxy for the bound network for the caller app or the default proxy if
5635 * none.
5636 *
5637 * @param network the network we want to get the proxy information for.
5638 * @return Proxy information if a network has a proxy configured, or otherwise null.
5639 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005640 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005641 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005642 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005643 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005644 if (network == null) {
5645 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005646 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005647 true);
5648 if (activeNetwork == null) {
5649 return null;
5650 }
5651 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005652 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005653 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5654 // caller may not have.
5655 return getLinkPropertiesProxyInfo(network);
5656 }
5657 // No proxy info available if the calling UID does not have network access.
5658 return null;
5659 }
5660
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005661
5662 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005663 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5664 if (nai == null) return null;
5665 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005666 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5667 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005668 }
5669 }
5670
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005671 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005672 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08005673 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005674 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005675 }
5676
Chalard Jean777e2e52018-06-07 18:02:37 +09005677 @Override
5678 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005679 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005680 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005681 }
5682
Jason Monk4d5e20f2014-04-25 15:00:09 -04005683 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005684 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005685 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005686 proxy = null;
5687 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005688 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005689 }
5690
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005691 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5692 // when any network changes proxy.
5693 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5694 // multi-network world where an app might be bound to a non-default network.
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005695 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensenc0618a62014-12-10 15:12:18 -05005696 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5697 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5698
Chalard Jean7d97afc2018-06-07 17:41:29 +09005699 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005700 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005701 }
5702 }
5703
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005704 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005705 final private HashMap<Uri, Integer> mUriEventMap;
5706 final private Context mContext;
5707 final private Handler mHandler;
5708
5709 SettingsObserver(Context context, Handler handler) {
5710 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005711 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005712 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005713 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005714 }
5715
Erik Kline05f2b402015-04-30 12:58:40 +09005716 void observe(Uri uri, int what) {
5717 mUriEventMap.put(uri, what);
5718 final ContentResolver resolver = mContext.getContentResolver();
5719 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005720 }
5721
5722 @Override
5723 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005724 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005725 }
5726
5727 @Override
5728 public void onChange(boolean selfChange, Uri uri) {
5729 final Integer what = mUriEventMap.get(uri);
5730 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005731 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005732 } else {
5733 loge("No matching event to send for URI=" + uri);
5734 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005735 }
5736 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005737
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005738 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005739 Log.d(TAG, s);
5740 }
5741
5742 private static void logw(String s) {
5743 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005744 }
5745
Daniel Brightf9e945b2020-06-15 16:10:01 -07005746 private static void logwtf(String s) {
5747 Log.wtf(TAG, s);
5748 }
5749
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005750 private static void logwtf(String s, Throwable t) {
5751 Log.wtf(TAG, s, t);
5752 }
5753
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005754 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005755 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005756 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005757
Hugo Benichi39621362017-02-11 17:04:43 +09005758 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005759 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005760 }
5761
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005762 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005763 * Return the information of all ongoing VPNs.
5764 *
5765 * <p>This method is used to update NetworkStatsService.
5766 *
5767 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08005768 */
junyulai2050bed2021-01-23 09:46:34 +08005769 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005770 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09005771 if (mLockdownEnabled) {
5772 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08005773 }
junyulai2050bed2021-01-23 09:46:34 +08005774 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005775 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08005776 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005777 if (info != null) {
5778 infoList.add(info);
5779 }
5780 }
junyulai2050bed2021-01-23 09:46:34 +08005781 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08005782 }
5783
5784 /**
5785 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00005786 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08005787 */
junyulai2050bed2021-01-23 09:46:34 +08005788 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005789 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08005790 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5791 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09005792 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5793 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5794 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08005795 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5796 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00005797 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00005798 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08005799 }
5800 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005801
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005802 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005803
5804 List<String> interfaces = new ArrayList<>();
5805 for (Network network : underlyingNetworks) {
5806 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5807 if (underlyingNai == null) continue;
5808 LinkProperties lp = underlyingNai.linkProperties;
5809 for (String iface : lp.getAllInterfaceNames()) {
5810 if (!TextUtils.isEmpty(iface)) {
5811 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00005812 }
5813 }
Benedict Wong34857f82019-06-12 17:46:15 +00005814 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005815
5816 if (interfaces.isEmpty()) return null;
5817
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005818 // Must be non-null or NetworkStatsService will crash.
5819 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5820 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08005821 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08005822 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005823
junyulai2050bed2021-01-23 09:46:34 +08005824 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5825 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08005826 }
5827
James Mattisd31bdfa2020-12-23 16:37:26 -08005828 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08005829 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5830 Network[] underlyingNetworks) {
5831 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005832 if (underlyingNetworks == null && defaultNetwork != null) {
5833 // null underlying networks means to track the default.
5834 underlyingNetworks = new Network[] { defaultNetwork };
5835 }
5836 return underlyingNetworks;
5837 }
5838
5839 // Returns true iff |network| is an underlying network of |nai|.
5840 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5841 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5842 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09005843 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08005844 final Network[] underlying = underlyingNetworksOrDefault(
5845 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005846 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005847 }
5848
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005849 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005850 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005851 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005852 * When underlying networks change, such networks may have to update capabilities to reflect
5853 * things like the metered bit, their transports, and so on. The capabilities are calculated
5854 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005855 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005856 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005857 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005858 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005859 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005860 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005861 }
5862 }
5863 }
5864
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005865 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5866 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5867 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5868 // a VPN is not up.
5869 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5870 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5871 for (UidRange range : blockedUidRanges) {
5872 if (range.contains(uid)) return true;
5873 }
5874 return false;
5875 }
5876
5877 @Override
5878 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08005879 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005880 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5881 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5882 }
5883
5884 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5885 if (DBG) {
5886 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5887 + Arrays.toString(ranges));
5888 }
5889 // Cannot use a Set since the list of UID ranges might contain duplicates.
5890 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5891 for (int i = 0; i < ranges.length; i++) {
5892 if (requireVpn) {
5893 newVpnBlockedUidRanges.add(ranges[i]);
5894 } else {
5895 newVpnBlockedUidRanges.remove(ranges[i]);
5896 }
5897 }
5898
5899 try {
5900 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5901 } catch (RemoteException | ServiceSpecificException e) {
5902 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5903 + Arrays.toString(ranges) + "): netd command failed: " + e);
5904 }
5905
Motomu Utsumib08654c2022-05-11 05:56:26 +00005906 if (SdkLevel.isAtLeastT()) {
5907 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
5908 }
5909
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005910 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5911 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00005912 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5913 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005914 }
5915
5916 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5917 }
5918
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07005919 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005920 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08005921 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005922 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01005923 }
5924
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005925 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5926 return mLockdownEnabled
5927 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5928 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00005929 }
5930
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005931 private NetworkAgentInfo getLegacyLockdownNai() {
5932 if (!mLockdownEnabled) {
5933 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005934 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005935 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005936 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5937 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005938
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005939 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005940 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5941 // a local variable. There is no need to make a copy because its contents cannot change.
5942 final Network[] underlying = nai.declaredUnderlyingNetworks;
5943 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005944 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005945 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005946
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005947 // The legacy lockdown VPN always uses the default network.
5948 // If the VPN's underlying network is no longer the current default network, it means that
5949 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005950 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5951 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005952 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005953 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005954 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005955 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005956
5957 return nai;
5958 };
5959
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005960 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5961 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5962 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005963 private DetailedState getLegacyLockdownState(DetailedState origState) {
5964 if (origState != DetailedState.CONNECTED) {
5965 return origState;
5966 }
5967 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5968 ? DetailedState.CONNECTING
5969 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005970 }
5971
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005972 private void filterForLegacyLockdown(NetworkInfo ni) {
5973 if (!mLockdownEnabled || !ni.isConnected()) return;
5974 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5975 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5976 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5977 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5978 // network, this time with a state of CONNECTED.
5979 //
5980 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5981 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5982 // is not too far off the truth, since an always-on VPN, when not connected, is always
5983 // trying to reconnect.
5984 if (getLegacyLockdownNai() == null) {
5985 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5986 }
5987 }
5988
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005989 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005990 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04005991 String action) {
paulhu8e96a752019-08-12 16:25:11 +08005992 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09005993 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5994 return;
5995 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04005996 final long ident = Binder.clearCallingIdentity();
5997 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09005998 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09005999 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006000 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006001 } finally {
6002 Binder.restoreCallingIdentity(ident);
6003 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006004 }
Wink Savillecb117d32013-08-29 14:57:08 -07006005
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006006 @Override
6007 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006008 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006009 final long ident = Binder.clearCallingIdentity();
6010 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006011 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006012 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006013 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6014 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006015 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006016 } finally {
6017 Binder.restoreCallingIdentity(ident);
6018 }
6019 }
6020
James Mattis02220e22021-03-13 19:27:21 -08006021 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006022 mPermissionMonitor.onUserAdded(user);
James Mattisae9aeb02021-03-01 17:09:11 -08006023 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6024 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6025 }
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006026 }
6027
James Mattis02220e22021-03-13 19:27:21 -08006028 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006029 mPermissionMonitor.onUserRemoved(user);
Chalard Jean0f57a492021-03-09 21:09:20 +09006030 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006031 handleSetProfileNetworkPreference(
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08006032 List.of(new ProfileNetworkPreferenceList.Preference(user, null, true)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006033 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006034 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6035 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6036 }
junyulaid91e7052020-08-28 13:44:33 +08006037 }
6038
James Mattis02220e22021-03-13 19:27:21 -08006039 private void onPackageChanged(@NonNull final String packageName) {
6040 // This is necessary in case a package is added or removed, but also when it's replaced to
6041 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6042 // as one in the preferences, then it should follow the same routing as that other package,
6043 // which means updating the rules is never to be needed in this case (whether it joins or
6044 // leaves a UID with a preference).
6045 if (isMappedInOemNetworkPreference(packageName)) {
6046 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6047 }
6048 }
6049
6050 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006051 @Override
6052 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006053 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006054 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006055 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006056
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006057 // User should be filled for below intents, check the existence.
6058 if (user == null) {
6059 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6060 return;
6061 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006062
Lorenzo Colitticd675292021-02-04 17:32:07 +09006063 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006064 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006065 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006066 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006067 } else {
junyulaid91e7052020-08-28 13:44:33 +08006068 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006069 }
6070 }
6071 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006072
James Mattis02220e22021-03-13 19:27:21 -08006073 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6074 @Override
6075 public void onReceive(Context context, Intent intent) {
6076 ensureRunningOnConnectivityServiceThread();
6077 switch (intent.getAction()) {
6078 case Intent.ACTION_PACKAGE_ADDED:
6079 case Intent.ACTION_PACKAGE_REMOVED:
6080 case Intent.ACTION_PACKAGE_REPLACED:
6081 onPackageChanged(intent.getData().getSchemeSpecificPart());
6082 break;
6083 default:
6084 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6085 }
6086 }
6087 };
6088
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006089 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006090 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006091
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006092 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006093 public final String name;
6094 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006095 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006096 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006097
lifraf3a3492021-03-10 13:58:14 +08006098 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6099 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006100 this.name = name;
6101 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006102 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006103 mDeathRecipient = deathRecipient;
6104
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006105 if (mDeathRecipient == null) {
6106 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006107 }
6108 }
6109
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006110 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006111 try {
6112 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6113 } catch (RemoteException e) {
6114 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006115 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006116 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006117 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006118
James Mattis4fce5d12020-11-12 15:53:42 -08006119 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6120 for (int i = 0; i < requests.size(); i++) {
6121 ensureNetworkRequestHasType(requests.get(i));
6122 }
6123 }
6124
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006125 private void ensureNetworkRequestHasType(NetworkRequest request) {
6126 if (request.type == NetworkRequest.Type.NONE) {
6127 throw new IllegalArgumentException(
6128 "All NetworkRequests in ConnectivityService must have a type");
6129 }
6130 }
6131
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006132 /**
6133 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006134 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006135 */
James Mattis258ea3c2020-11-15 15:04:40 -08006136 @VisibleForTesting
6137 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006138 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6139 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006140 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006141
James Mattisa076c532020-12-02 14:12:41 -08006142 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6143 void setSatisfier(
6144 @Nullable final NetworkAgentInfo satisfier,
6145 @Nullable final NetworkRequest activeRequest) {
6146 mSatisfier = satisfier;
6147 mActiveRequest = activeRequest;
6148 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006149
James Mattisd31bdfa2020-12-23 16:37:26 -08006150 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006151 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006152 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006153 private NetworkAgentInfo mSatisfier;
6154 NetworkAgentInfo getSatisfier() {
6155 return mSatisfier;
6156 }
6157
6158 // The request in mRequests assigned to a network agent. This is null if none of the
6159 // requests in mRequests can be satisfied. This member has the constraint of only being
6160 // accessible on the handler thread.
6161 @Nullable
6162 private NetworkRequest mActiveRequest;
6163 NetworkRequest getActiveRequest() {
6164 return mActiveRequest;
6165 }
6166
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006167 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006168 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006169 @Nullable
6170 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006171
6172 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006173 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006174 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006175 final int mPid;
6176 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006177 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006178 @Nullable
6179 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006180
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006181 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006182 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006183
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006184 // Effective UID of this request. This is different from mUid when a privileged process
6185 // files a request on behalf of another UID. This UID is used to determine blocked status,
6186 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6187 // maximum limit of registered callbacks per UID.
6188 final int mAsUid;
6189
paulhu48291862021-07-14 14:53:57 +08006190 // Preference order of this request.
6191 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006192
James Mattis3ce3d3c2021-02-09 18:18:28 -08006193 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6194 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6195 // maintained for keying off of. This is only a concern when the original nri
6196 // mNetworkRequests changes which happens currently for apps that register callbacks to
6197 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6198 // that match the per-app default nri that currently tracks the calling app's uid so that
6199 // callbacks are fired at the appropriate time. When the callbacks fire,
6200 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6201 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6202 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6203 @NonNull
6204 private final NetworkRequest mNetworkRequestForCallback;
6205 NetworkRequest getNetworkRequestForCallback() {
6206 return mNetworkRequestForCallback;
6207 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006208
James Mattisd31bdfa2020-12-23 16:37:26 -08006209 /**
6210 * Get the list of UIDs this nri applies to.
6211 */
6212 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006213 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006214 // networkCapabilities.getUids() returns a defensive copy.
6215 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006216 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6217 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006218 }
6219
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006220 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6221 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006222 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006223 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006224 }
6225
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006226 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006227 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006228 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006229 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006230 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006231 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006232 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006233 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006234 mBinder = null;
6235 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006236 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006237 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006238 mPerUidCounter = getRequestCounter(this);
6239 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006240 /**
6241 * Location sensitive data not included in pending intent. Only included in
6242 * {@link NetworkCallback}.
6243 */
6244 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006245 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006246 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006247 }
6248
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006249 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006250 @Nullable final IBinder binder,
6251 @NetworkCallback.Flag int callbackFlags,
6252 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006253 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
6254 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08006255 }
6256
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006257 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006258 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006259 @Nullable final IBinder binder,
6260 @NetworkCallback.Flag int callbackFlags,
6261 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006262 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006263 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006264 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006265 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006266 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006267 mBinder = binder;
6268 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006269 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006270 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006271 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006272 mPerUidCounter = getRequestCounter(this);
6273 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006274 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006275 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006276 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006277 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006278 }
6279
James Mattis3ce3d3c2021-02-09 18:18:28 -08006280 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6281 @NonNull final List<NetworkRequest> r) {
6282 super();
6283 ensureAllNetworkRequestsHaveType(r);
6284 mRequests = initializeRequests(r);
6285 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006286 final NetworkAgentInfo satisfier = nri.getSatisfier();
6287 if (null != satisfier) {
6288 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6289 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09006290 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006291 // As this code creates a new NRI with a new set of requests, figure out which of
6292 // the list of requests should be the active request. It is always the first
6293 // request of the list that can be satisfied by the satisfier since the order of
6294 // requests is a priority order.
6295 // Note even in the presence of a satisfier there may not be an active request,
6296 // when the satisfier is the no-service network.
6297 NetworkRequest activeRequest = null;
6298 for (final NetworkRequest candidate : r) {
6299 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6300 activeRequest = candidate;
6301 break;
6302 }
6303 }
6304 setSatisfier(satisfier, activeRequest);
6305 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006306 mMessenger = nri.mMessenger;
6307 mBinder = nri.mBinder;
6308 mPid = nri.mPid;
6309 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006310 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006311 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006312 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006313 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006314 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006315 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006316 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006317 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006318 }
6319
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006320 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006321 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006322 }
6323
paulhue9913722021-05-26 15:19:20 +08006324 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006325 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006326 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006327 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006328 }
6329
James Mattis2516da32021-01-31 17:06:19 -08006330 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6331 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6332 // false.
6333 boolean isBeingSatisfied() {
6334 return (null != mSatisfier && null != mActiveRequest);
6335 }
6336
James Mattis3d229892020-11-16 16:46:28 -08006337 boolean isMultilayerRequest() {
6338 return mRequests.size() > 1;
6339 }
6340
James Mattis45d81842021-01-10 14:24:24 -08006341 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6342 // Creating a defensive copy to prevent the sender from modifying the list being
6343 // reflected in the return value of this method.
6344 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006345 return Collections.unmodifiableList(tempRequests);
6346 }
6347
James Mattisb1392002021-03-31 13:57:52 -07006348 void linkDeathRecipient() {
6349 if (null != mBinder) {
6350 try {
6351 mBinder.linkToDeath(this, 0);
6352 } catch (RemoteException e) {
6353 binderDied();
6354 }
6355 }
6356 }
6357
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006358 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006359 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006360 try {
6361 mBinder.unlinkToDeath(this, 0);
6362 } catch (NoSuchElementException e) {
6363 // Temporary workaround for b/194394697 pending analysis of additional logs
6364 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6365 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006366 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006367 }
6368
paulhu48291862021-07-14 14:53:57 +08006369 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6370 // Compare two preference orders.
6371 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006372 }
6373
paulhu48291862021-07-14 14:53:57 +08006374 int getPreferenceOrderForNetd() {
6375 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6376 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6377 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006378 }
paulhu48291862021-07-14 14:53:57 +08006379 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006380 }
6381
James Mattis4fce5d12020-11-12 15:53:42 -08006382 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006383 public void binderDied() {
6384 log("ConnectivityService NetworkRequestInfo binderDied(" +
Chalard Jean524f0b12021-10-25 21:11:56 +09006385 "uid/pid:" + mUid + "/" + mPid + ", " + mRequests + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09006386 // As an immutable collection, mRequests cannot change by the time the
6387 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6388 // is acceptable. Use handleReleaseNetworkRequest and not directly
6389 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6390 // the app already unregistered the request.
6391 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6392 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006393 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006394
James Mattis4fce5d12020-11-12 15:53:42 -08006395 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006396 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006397 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6398 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006399 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006400 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006401 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006402 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006403 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006404 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006405 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006406 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006407 }
6408
Junyu Lai00d92df2022-07-05 11:01:52 +08006409 // Keep backward compatibility since the ServiceSpecificException is used by
6410 // the API surface, see {@link ConnectivityManager#convertServiceException}.
6411 public static class RequestInfoPerUidCounter extends PerUidCounter {
6412 RequestInfoPerUidCounter(int maxCountPerUid) {
6413 super(maxCountPerUid);
6414 }
6415
6416 @Override
6417 public synchronized void incrementCountOrThrow(int uid) {
6418 try {
6419 super.incrementCountOrThrow(uid);
6420 } catch (IllegalStateException e) {
6421 throw new ServiceSpecificException(
6422 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
6423 "Uid " + uid + " exceeded its allotted requests limit");
6424 }
6425 }
6426
6427 @Override
6428 public synchronized void decrementCountOrThrow(int uid) {
6429 throw new UnsupportedOperationException("Use decrementCount instead.");
6430 }
6431
6432 public synchronized void decrementCount(int uid) {
6433 try {
6434 super.decrementCountOrThrow(uid);
6435 } catch (IllegalStateException e) {
6436 logwtf("Exception when decrement per uid request count: ", e);
6437 }
6438 }
6439 }
6440
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006441 // This checks that the passed capabilities either do not request a
6442 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006443 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006444 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006445 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006446 throw new SecurityException("Insufficient permissions to request a specific SSID");
6447 }
paulhu1a407652019-03-22 16:35:06 +08006448
6449 if (nc.hasSignalStrength()
6450 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6451 throw new SecurityException(
6452 "Insufficient permissions to request a specific signal strength");
6453 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006454 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006455
junyulai2217bec2021-04-14 23:33:31 +08006456 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006457 enforceNetworkFactoryPermission();
6458 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006459 }
6460
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006461 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006462 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006463 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006464 // mNetworkRequests may contain the same value multiple times in case of
6465 // multilayer requests. It won't matter in this case because the thresholds
6466 // will then be the same and be deduplicated as they enter the `thresholds` set.
6467 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006468 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6469 for (final NetworkRequest req : nri.mRequests) {
6470 if (req.networkCapabilities.hasSignalStrength()
6471 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6472 thresholds.add(req.networkCapabilities.getSignalStrength());
6473 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006474 }
6475 }
6476 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006477 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006478 }
6479
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006480 private void updateSignalStrengthThresholds(
6481 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006482 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006483
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006484 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006485 String detail;
6486 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6487 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6488 } else {
6489 detail = reason;
6490 }
6491 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006492 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006493 }
6494
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006495 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006496 }
6497
Chalard Jeandd421992021-12-16 23:16:02 +09006498 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07006499 if (nc == null) {
6500 return;
6501 }
6502 NetworkSpecifier ns = nc.getNetworkSpecifier();
6503 if (ns == null) {
6504 return;
6505 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006506 if (ns instanceof MatchAllNetworkSpecifier) {
6507 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6508 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006509 }
6510
Chalard Jeandd421992021-12-16 23:16:02 +09006511 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08006512 ensureValidNetworkSpecifier(nc);
6513 if (nc.isPrivateDnsBroken()) {
6514 throw new IllegalArgumentException("Can't request broken private DNS");
6515 }
Chalard Jeande665262022-02-25 16:12:12 +09006516 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09006517 throw new IllegalArgumentException("Can't request access UIDs");
6518 }
lucasline117e2e2019-10-22 18:27:33 +08006519 }
6520
Chalard Jeandd421992021-12-16 23:16:02 +09006521 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
6522 ensureListenableCapabilities(nc);
6523 final String badCapability = nc.describeFirstNonRequestableCapability();
6524 if (badCapability != null) {
6525 throw new IllegalArgumentException("Cannot request network with " + badCapability);
6526 }
6527 }
6528
Chiachang Wang3bc52762021-11-25 14:17:57 +08006529 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6530 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006531 private boolean isTargetSdkAtleast(int version, int callingUid,
6532 @NonNull String callingPackageName) {
6533 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006534 final PackageManager pm =
6535 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006536 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006537 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006538 if (callingVersion < version) return false;
6539 } catch (PackageManager.NameNotFoundException e) { }
6540 return true;
6541 }
6542
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006543 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006544 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006545 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006546 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006547 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006548 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006549 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6550 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006551 throw new SecurityException("Insufficient permissions to specify legacy type");
6552 }
markchienfac84a22020-03-18 21:16:15 +08006553 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006554 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006555 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006556 // Privileged callers can track the default network of another UID by passing in a UID.
6557 if (asUid != Process.INVALID_UID) {
6558 enforceSettingsPermission();
6559 } else {
6560 asUid = callingUid;
6561 }
junyulaiad010792021-01-11 16:53:38 +08006562 final NetworkRequest.Type reqType;
6563 try {
6564 reqType = NetworkRequest.Type.values()[reqTypeInt];
6565 } catch (ArrayIndexOutOfBoundsException e) {
6566 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6567 }
6568 switch (reqType) {
6569 case TRACK_DEFAULT:
6570 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006571 // is unused and will be replaced by ones appropriate for the UID (usually, the
6572 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006573 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006574 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006575 enforceAccessPermission();
6576 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006577 case TRACK_SYSTEM_DEFAULT:
6578 enforceSettingsPermission();
6579 networkCapabilities = new NetworkCapabilities(defaultNc);
6580 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006581 case BACKGROUND_REQUEST:
6582 enforceNetworkStackOrSettingsPermission();
6583 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006584 case REQUEST:
6585 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6586 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006587 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08006588 // TODO: this is incorrect. We mark the request as metered or not depending on
6589 // the state of the app when the request is filed, but we never change the
6590 // request if the app changes network state. http://b/29964605
6591 enforceMeteredApnPolicy(networkCapabilities);
6592 break;
junyulai1b1c8742021-03-12 20:05:08 +08006593 case LISTEN_FOR_BEST:
6594 enforceAccessPermission();
6595 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6596 break;
junyulaiad010792021-01-11 16:53:38 +08006597 default:
6598 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006599 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006600 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006601 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006602 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006603
junyulai1b1c8742021-03-12 20:05:08 +08006604 // Enforce FOREGROUND if the caller does not have permission to use background network.
6605 if (reqType == LISTEN_FOR_BEST) {
6606 restrictBackgroundRequestForCaller(networkCapabilities);
6607 }
6608
6609 // Set the UID range for this request to the single UID of the requester, unless the
6610 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006611 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6612 // are no visible methods to set the UIDs, an app could use reflection to try and get
6613 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006614 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006615 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6616 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006617
Etan Cohen85000162017-02-05 10:42:27 -08006618 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006619 throw new IllegalArgumentException("Bad timeout specified");
6620 }
Etan Cohen9786d922015-11-18 10:56:15 -08006621
James Mattis3ce3d3c2021-02-09 18:18:28 -08006622 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006623 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006624 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006625 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006626 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006627 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006628
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006629 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6630 // copied from the default request above. (This is necessary to ensure, for example, that
6631 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6632 // changes don't alter request matching.
6633 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6634 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006635 throw new IllegalStateException(
6636 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006637 + networkCapabilities + " vs. " + defaultNc);
6638 }
6639
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006640 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006641 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006642 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006643 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006644 }
6645 return networkRequest;
6646 }
6647
James Mattis3ce3d3c2021-02-09 18:18:28 -08006648 /**
6649 * Return the nri to be used when registering a network request. Specifically, this is used with
6650 * requests registered to track the default request. If there is currently a per-app default
6651 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6652 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006653 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6654 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006655 * @param nr the network request for the nri.
6656 * @param msgr the messenger for the nri.
6657 * @param binder the binder for the nri.
6658 * @param callingAttributionTag the calling attribution tag for the nri.
6659 * @return the nri to register.
6660 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006661 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006662 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006663 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006664 @Nullable String callingAttributionTag) {
6665 final List<NetworkRequest> requests;
6666 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6667 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006668 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006669 } else {
6670 requests = Collections.singletonList(nr);
6671 }
Roshan Pius951c0032020-12-22 15:10:42 -08006672 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006673 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006674 }
6675
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006676 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08006677 String callingPackageName, String callingAttributionTag, final int callingUid) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006678 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08006679 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
6680 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
6681 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
6682 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006683 }
junyulai96bd9fe2022-03-08 17:36:42 +08006684 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006685 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006686 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006687 }
6688 }
6689
fenglu3f357402015-03-20 11:29:56 -07006690 @Override
fenglub00f4882015-04-21 17:12:05 -07006691 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006692 enforceAccessPermission();
6693 NetworkAgentInfo nai = null;
6694 if (network == null) {
6695 return false;
6696 }
6697 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006698 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006699 }
6700 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006701 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006702 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006703 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006704 Integer uidReqs = mBandwidthRequests.get(uid);
6705 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006706 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006707 }
6708 mBandwidthRequests.put(uid, ++uidReqs);
6709 }
fenglu3f357402015-03-20 11:29:56 -07006710 return true;
6711 }
6712 return false;
6713 }
6714
Felipe Leme0a5ae422016-06-20 16:36:29 -07006715 private boolean isSystem(int uid) {
6716 return uid < Process.FIRST_APPLICATION_UID;
6717 }
fenglu3f357402015-03-20 11:29:56 -07006718
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006719 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006720 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006721 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006722 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006723 return;
6724 }
Hugo Benichi39621362017-02-11 17:04:43 +09006725 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6726 // Policy already enforced.
6727 return;
6728 }
paulhuaf50d7d2020-12-24 19:47:34 +08006729 final long ident = Binder.clearCallingIdentity();
6730 try {
6731 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6732 // If UID is restricted, don't allow them to bring up metered APNs.
6733 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6734 }
6735 } finally {
6736 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006737 }
6738 }
6739
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006740 @Override
6741 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006742 PendingIntent operation, @NonNull String callingPackageName,
6743 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006744 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006745 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006746 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006747 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006748 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006749 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006750 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006751 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006752 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006753 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6754 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09006755
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006756 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006757 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006758 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6759 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006760 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006761 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6762 nri));
6763 return networkRequest;
6764 }
6765
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006766 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6767 mHandler.sendMessageDelayed(
6768 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006769 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006770 }
6771
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006772 @Override
6773 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006774 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006775 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006776 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006777 }
6778
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006779 // In order to implement the compatibility measure for pre-M apps that call
6780 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6781 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6782 // This ensures it has permission to do so.
6783 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6784 if (nc == null) {
6785 return false;
6786 }
6787 int[] transportTypes = nc.getTransportTypes();
6788 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6789 return false;
6790 }
6791 try {
6792 mContext.enforceCallingOrSelfPermission(
6793 android.Manifest.permission.ACCESS_WIFI_STATE,
6794 "ConnectivityService");
6795 } catch (SecurityException e) {
6796 return false;
6797 }
6798 return true;
6799 }
6800
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006801 @Override
6802 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08006803 Messenger messenger, IBinder binder,
6804 @NetworkCallback.Flag int callbackFlags,
6805 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006806 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006807 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6808 enforceAccessPermission();
6809 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006810
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006811 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006812 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006813 Binder.getCallingPid(), callingUid, callingPackageName);
6814 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09006815 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6816 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6817 // onLost and onAvailable callbacks when networks move in and out of the background.
6818 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6819 // can't request networks.
6820 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09006821 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07006822
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006823 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006824 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08006825 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006826 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08006827 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006828 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006829
6830 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6831 return networkRequest;
6832 }
6833
6834 @Override
6835 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08006836 PendingIntent operation, @NonNull String callingPackageName,
6837 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006838 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006839 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04006840 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6841 enforceAccessPermission();
6842 }
Chalard Jeandd421992021-12-16 23:16:02 +09006843 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006844 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006845 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006846 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006847 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006848
6849 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006850 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006851 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6852 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006853 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04006854
WeiZhang1cc3f172021-06-03 19:02:04 -05006855 mHandler.sendMessage(mHandler.obtainMessage(
6856 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006857 }
6858
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006859 /** Returns the next Network provider ID. */
6860 public final int nextNetworkProviderId() {
6861 return mNextNetworkProviderId.getAndIncrement();
6862 }
6863
Erik Kline0c04b742016-07-07 16:50:58 +09006864 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006865 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006866 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09006867 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006868 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006869 }
6870
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006871 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6872 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006873 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6874 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6875 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08006876 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006877 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006878 return;
6879 }
6880
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006881 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6882 mNetworkProviderInfos.put(npi.messenger, npi);
6883 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006884 }
6885
6886 @Override
6887 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006888 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08006889 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006890 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08006891 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006892 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6893 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006894 }
6895
6896 @Override
6897 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006898 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006899 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006900 }
6901
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006902 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09006903 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006904 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6905 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09006906 Objects.requireNonNull(score);
6907 Objects.requireNonNull(caps);
6908 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09006909 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006910 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09006911 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
6912 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006913 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6914 }
6915
Chalard Jeanbb902a52021-08-18 01:35:19 +09006916 private void updateOfferScore(final NetworkOffer offer) {
6917 final boolean yieldToBadWiFi =
6918 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
6919 final NetworkOffer newOffer = new NetworkOffer(
6920 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
6921 offer.caps, offer.callback, offer.providerId);
6922 if (offer.equals(newOffer)) return;
6923 handleRegisterNetworkOffer(newOffer);
6924 }
6925
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006926 @Override
6927 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08006928 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006929 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6930 }
6931
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006932 private void handleUnregisterNetworkProvider(Messenger messenger) {
6933 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6934 if (npi == null) {
6935 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006936 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006937 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006938 // Unregister all the offers from this provider
6939 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6940 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09006941 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006942 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6943 toRemove.add(noi);
6944 }
6945 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09006946 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006947 handleUnregisterNetworkOffer(noi);
6948 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006949 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006950 }
6951
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006952 @Override
James Mattisf7027322020-12-13 16:28:14 -08006953 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006954 if (request.hasTransport(TRANSPORT_TEST)) {
6955 enforceNetworkFactoryOrTestNetworksPermission();
6956 } else {
6957 enforceNetworkFactoryPermission();
6958 }
James Mattisf7027322020-12-13 16:28:14 -08006959 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6960 if (nri != null) {
6961 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6962 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6963 mHandler.post(() -> handleReleaseNetworkRequest(
6964 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6965 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006966 }
6967
Paul Jensen1f567382015-02-13 14:18:39 -05006968 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6969 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006970 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05006971 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006972 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05006973 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006974 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006975
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09006976 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05006977 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006978 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006979
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006980 // UID ranges for users that are currently blocked by VPNs.
6981 // This array is accessed and iterated on multiple threads without holding locks, so its
6982 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6983 // (on the handler thread).
6984 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6985
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006986 // Must only be accessed on the handler thread
6987 @NonNull
6988 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6989
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006990 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006991 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006992
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006993 // Current OEM network preferences. This object must only be written to on the handler thread.
6994 // Since it is immutable and always non-null, other threads may read it if they only care
6995 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08006996 @NonNull
6997 private OemNetworkPreferences mOemNetworkPreferences =
6998 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006999 // Current per-profile network preferences. This object follows the same threading rules as
7000 // the OEM network preferences above.
7001 @NonNull
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08007002 private ProfileNetworkPreferenceList mProfileNetworkPreferences =
7003 new ProfileNetworkPreferenceList();
James Mattis45d81842021-01-10 14:24:24 -08007004
paulhu51f77dc2021-06-07 02:34:20 +00007005 // A set of UIDs that should use mobile data preferentially if available. This object follows
7006 // the same threading rules as the OEM network preferences above.
7007 @NonNull
7008 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7009
James Mattiscb1e0362021-04-06 17:07:42 -07007010 // OemNetworkPreferences activity String log entries.
7011 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7012 @NonNull
7013 private final LocalLog mOemNetworkPreferencesLogs =
7014 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7015
James Mattis02220e22021-03-13 19:27:21 -08007016 /**
7017 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7018 * @param packageName the package name to check existence of a mapping for.
7019 * @return true if a mapping exists, false otherwise
7020 */
7021 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7022 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7023 }
7024
James Mattise3ef1912020-12-20 11:09:58 -08007025 // The always-on request for an Internet-capable network that apps without a specific default
7026 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007027 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007028 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007029 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007030 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007031 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007032 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007033 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007034
James Mattisd31bdfa2020-12-23 16:37:26 -08007035 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7036 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7037 }
7038
7039 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007040 * Return the default network request currently tracking the given uid.
7041 * @param uid the uid to check.
7042 * @return the NetworkRequestInfo tracking the given uid.
7043 */
7044 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007045 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007046 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007047 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007048 // Checking the first request is sufficient as only multilayer requests will have more
7049 // than one request and for multilayer, all requests will track the same uids.
7050 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007051 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007052 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007053 highestPriorityNri = nri;
7054 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007055 }
7056 }
paulhuaa0743d2021-05-26 21:56:03 +08007057 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007058 }
7059
7060 /**
7061 * Get a copy of the network requests of the default request that is currently tracking the
7062 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007063 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7064 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007065 * @param requestorUid the uid to check the default for.
7066 * @param requestorPackageName the requestor's package name.
7067 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7068 */
7069 @NonNull
7070 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007071 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007072 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007073 getDefaultRequestTrackingUid(asUid).mRequests,
7074 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007075 }
7076
7077 /**
7078 * Copy the given nri's NetworkRequest collection.
7079 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007080 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7081 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007082 * @param requestorUid the uid to set on the copied collection.
7083 * @param requestorPackageName the package name to set on the copied collection.
7084 * @return the copied NetworkRequest collection.
7085 */
7086 @NonNull
7087 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007088 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7089 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007090 final List<NetworkRequest> requests = new ArrayList<>();
7091 for (final NetworkRequest nr : requestsToCopy) {
7092 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007093 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007094 nr.legacyType, nextNetworkRequestId(), nr.type));
7095 }
7096 return requests;
7097 }
7098
7099 @NonNull
7100 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007101 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7102 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007103 // These capabilities are for a TRACK_DEFAULT callback, so:
7104 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7105 // mDefaultRequest and a per-UID default request.
7106 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007107 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007108 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007109 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7110 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007111 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007112 restrictRequestUidsForCallerAndSetRequestorInfo(
7113 netCap, requestorUid, requestorPackageName);
7114 return netCap;
7115 }
7116
7117 /**
7118 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7119 * @param nr the network request to check for equality against.
7120 * @return the nri if one exists, null otherwise.
7121 */
7122 @Nullable
7123 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7124 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7125 if (nri.getNetworkRequestForCallback().equals(nr)) {
7126 return nri;
7127 }
7128 }
7129 return null;
7130 }
7131
7132 /**
7133 * Check if an nri is currently being managed by per-app default networking.
7134 * @param nri the nri to check.
7135 * @return true if this nri is currently being managed by per-app default networking.
7136 */
7137 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7138 // nri.mRequests.get(0) is only different from the original request filed in
7139 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7140 // functionality therefore if these two don't match, it means this particular nri is
7141 // currently being managed by a per-app default.
7142 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7143 }
7144
7145 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007146 * Determine if an nri is a managed default request that disallows default networking.
7147 * @param nri the request to evaluate
7148 * @return true if device-default networking is disallowed
7149 */
7150 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7151 // Check if this nri is a managed default that supports the default network at its
7152 // lowest priority request.
7153 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7154 final NetworkCapabilities lowestPriorityNetCap =
7155 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7156 return isPerAppDefaultRequest(nri)
7157 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7158 lowestPriorityNetCap));
7159 }
7160
Erik Kline05f2b402015-04-30 12:58:40 +09007161 // Request used to optionally keep mobile data active even when higher
7162 // priority networks like Wi-Fi are active.
7163 private final NetworkRequest mDefaultMobileDataRequest;
7164
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007165 // Request used to optionally keep wifi data active even when higher
7166 // priority networks like ethernet are active.
7167 private final NetworkRequest mDefaultWifiRequest;
7168
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007169 // Request used to optionally keep vehicle internal network always active
7170 private final NetworkRequest mDefaultVehicleRequest;
7171
James Mattisd31bdfa2020-12-23 16:37:26 -08007172 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7173 // network with no service. This NAI should never be matched against, nor should any public API
7174 // ever return the associated network. For this reason, this NAI is not in the list of available
7175 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7176 // default requests that don't support using the device default network which will ultimately
7177 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7178 @VisibleForTesting
7179 final NetworkAgentInfo mNoServiceNetwork;
7180
Chalard Jean5b409c72021-02-04 13:12:59 +09007181 // The NetworkAgentInfo currently satisfying the default request, if any.
7182 private NetworkAgentInfo getDefaultNetwork() {
7183 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09007184 }
7185
James Mattis2516da32021-01-31 17:06:19 -08007186 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007187 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08007188 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7189 // Currently, all network requests will have the same uids therefore checking the first
7190 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007191 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08007192 if (null == uids) {
7193 continue;
7194 }
7195 for (final UidRange range : uids) {
7196 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08007197 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007198 highestPriorityNri = nri;
7199 }
James Mattis2516da32021-01-31 17:06:19 -08007200 }
7201 }
7202 }
paulhuaa0743d2021-05-26 21:56:03 +08007203 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08007204 }
7205
Varun Ananddf569952019-02-06 10:13:38 -08007206 @Nullable
7207 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
7208 return nai != null ? nai.network : null;
7209 }
7210
7211 private void ensureRunningOnConnectivityServiceThread() {
7212 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
7213 throw new IllegalStateException(
7214 "Not running on ConnectivityService thread: "
7215 + Thread.currentThread().getName());
7216 }
7217 }
7218
Chalard Jean3a3f5f22019-04-10 23:07:55 +09007219 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09007220 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
7221 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007222 }
7223
Chalard Jean29d06db2018-05-02 21:14:54 +09007224 /**
7225 * Register a new agent with ConnectivityService to handle a network.
7226 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007227 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09007228 * @param networkInfo the initial info associated with this network. It can be updated later :
7229 * see {@link #updateNetworkInfo}.
7230 * @param linkProperties the initial link properties of this network. They can be updated
7231 * later : see {@link #updateLinkProperties}.
7232 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007233 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007234 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007235 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007236 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007237 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007238 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007239 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007240 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007241 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7242 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007243 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7244 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7245 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007246 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007247 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007248 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08007249 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007250 } else {
7251 enforceNetworkFactoryPermission();
7252 }
7253
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007254 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007255 final long token = Binder.clearCallingIdentity();
7256 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007257 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007258 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007259 } finally {
7260 Binder.restoreCallingIdentity(token);
7261 }
7262 }
7263
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007264 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007265 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007266 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7267 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007268
Chalard Jeandbc46952022-02-02 00:14:18 +09007269 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
7270 // and mutate them at any time.
7271 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
7272 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
7273 final LinkProperties lpCopy = new LinkProperties(linkProperties);
7274
Chalard Jean366c5252022-01-25 18:27:53 +09007275 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09007276 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09007277 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7278 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007279 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09007280 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007281 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007282 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7283 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007284
Chalard Jeandbc46952022-02-02 00:14:18 +09007285 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09007286 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007287 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007288 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007289 mDeps.getNetworkStack().makeNetworkMonitor(
7290 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007291 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7292 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007293 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007294 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007295 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007296 }
7297
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007298 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007299 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007300 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09007301 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007302 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09007303 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
7304 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
7305 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09007306
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007307 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007308
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007309 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007310 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007311 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007312 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007313
7314 try {
7315 networkMonitor.start();
7316 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007317 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007318 }
Chalard Jean366c5252022-01-25 18:27:53 +09007319
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007320 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007321 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007322 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007323 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007324 }
7325
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007326 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7327 @NonNull public final NetworkOffer offer;
7328
7329 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7330 this.offer = offer;
7331 }
7332
7333 @Override
7334 public void binderDied() {
7335 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7336 }
7337 }
7338
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007339 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7340 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7341 if (npi.providerId == providerId) return true;
7342 }
7343 return false;
7344 }
7345
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007346 /**
7347 * Register or update a network offer.
7348 * @param newOffer The new offer. If the callback member is the same as an existing
7349 * offer, it is an update of that offer.
7350 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007351 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007352 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7353 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007354 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007355 // This may actually happen if a provider updates its score or registers and then
7356 // immediately unregisters. The offer would still be in the handler queue, but the
7357 // provider would have been removed.
7358 if (DBG) log("Received offer from an unregistered provider");
7359 return;
7360 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007361 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7362 if (null != existingOffer) {
7363 handleUnregisterNetworkOffer(existingOffer);
7364 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007365 if (DBG) {
7366 // handleUnregisterNetworkOffer has already logged the old offer
7367 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7368 }
7369 } else {
7370 if (DBG) {
7371 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7372 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007373 }
7374 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7375 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007376 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007377 } catch (RemoteException e) {
7378 noi.binderDied();
7379 return;
7380 }
7381 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007382 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007383 }
7384
7385 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7386 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007387 if (DBG) {
7388 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7389 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007390
7391 // If the provider removes the offer and dies immediately afterwards this
7392 // function may be called twice in a row, but the array will no longer contain
7393 // the offer.
7394 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007395 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007396 }
7397
7398 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7399 @NonNull final INetworkOfferCallback callback) {
7400 ensureRunningOnConnectivityServiceThread();
7401 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007402 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007403 }
7404 return null;
7405 }
7406
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007407 /**
7408 * Called when receiving LinkProperties directly from a NetworkAgent.
7409 * Stores into |nai| any data coming from the agent that might also be written to the network's
7410 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7411 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007412 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007413 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007414 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7415 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007416 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007417 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007418 }
7419
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007420 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007421 @NonNull LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007422 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007423
Lorenzo Colittid523d142020-04-01 20:16:30 +09007424 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7425 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7426 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007427 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007428
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007429 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007430
7431 // update filtering rules, need to happen after the interface update so netd knows about the
7432 // new interface (the interface name -> index map becomes initialized)
7433 updateVpnFiltering(newLp, oldLp, networkAgent);
7434
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007435 updateMtu(newLp, oldLp);
7436 // TODO - figure out what to do for clat
7437// for (LinkProperties lp : newLp.getStackedLinks()) {
7438// updateMtu(lp, null);
7439// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007440 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007441 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7442 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007443
Erik Klineb9888902016-04-05 13:30:49 +09007444 updateRoutes(newLp, oldLp, netId);
7445 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007446 // Make sure LinkProperties represents the latest private DNS status.
7447 // This does not need to be done before updateDnses because the
7448 // LinkProperties are not the source of the private DNS configuration.
7449 // updateDnses will fetch the private DNS configuration from DnsManager.
7450 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007451
Chalard Jean5b409c72021-02-04 13:12:59 +09007452 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007453 handleApplyDefaultProxy(newLp.getHttpProxy());
7454 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007455 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007456 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007457
7458 updateWakeOnLan(newLp);
7459
Hai Shalome58bdc62021-01-11 18:45:34 -08007460 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7461 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7462 // does, it needs to be merged here.
7463 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7464 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007465
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007466 // TODO - move this check to cover the whole function
7467 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007468 synchronized (networkAgent) {
7469 networkAgent.linkProperties = newLp;
7470 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007471 // Start or stop DNS64 detection and 464xlat according to network state.
7472 networkAgent.clatd.update();
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08007473 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007474 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7475 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09007476 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007477 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007478
7479 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007480 }
7481
Hai Shalome58bdc62021-01-11 18:45:34 -08007482 /**
7483 * @param naData captive portal data from NetworkAgent
7484 * @param apiData captive portal data from capport API
7485 */
7486 @Nullable
7487 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7488 CaptivePortalData apiData) {
7489 if (naData == null || apiData == null) {
7490 return naData == null ? apiData : naData;
7491 }
7492 final CaptivePortalData.Builder captivePortalBuilder =
7493 new CaptivePortalData.Builder(naData);
7494
7495 if (apiData.isCaptive()) {
7496 captivePortalBuilder.setCaptive(true);
7497 }
7498 if (apiData.isSessionExtendable()) {
7499 captivePortalBuilder.setSessionExtendable(true);
7500 }
7501 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7502 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7503 // otherwise data would be inconsistent. Prefer the capport API info if present,
7504 // as it can generally be refreshed more often.
7505 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7506 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7507 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7508 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7509 // No source has time / bytes remaining information: surface the newest refresh time
7510 // for other fields
7511 captivePortalBuilder.setRefreshTime(
7512 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7513 }
7514
Hai Shalom7c6ab402021-02-04 19:34:06 -08007515 // Prioritize the user portal URL from the network agent if the source is authenticated.
7516 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7517 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7518 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7519 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007520 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007521 // Prioritize the venue information URL from the network agent if the source is
7522 // authenticated.
7523 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7524 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7525 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7526 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007527 }
7528 return captivePortalBuilder.build();
7529 }
7530
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007531 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007532 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007533 // marks on unsupported interfaces is harmless.
7534 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7535 return;
7536 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007537
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007538 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7539 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7540
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007541 // Mask/mark of zero will not detect anything interesting.
7542 // Don't install rules unless both values are nonzero.
7543 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007544 return;
7545 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007546
7547 final String prefix = "iface:" + iface;
7548 try {
7549 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007550 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007551 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007552 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007553 }
7554 } catch (Exception e) {
7555 loge("Exception modifying wakeup packet monitoring: " + e);
7556 }
7557
Joel Scherpelza235a812017-05-22 13:47:41 +09007558 }
7559
Chalard Jean9589e722019-11-19 19:03:53 +09007560 private void updateInterfaces(final @Nullable LinkProperties newLp,
7561 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007562 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09007563 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fa7d9e2017-08-22 16:35:52 +01007564 oldLp != null ? oldLp.getAllInterfaceNames() : null,
7565 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jean9589e722019-11-19 19:03:53 +09007566 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007567 for (final String iface : interfaceDiff.added) {
7568 try {
7569 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007570 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09007571 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007572 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7573 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007574 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007575 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007576 }
Paul Jensenbff73492014-04-28 10:33:11 -04007577 }
7578 }
Chalard Jean9589e722019-11-19 19:03:53 +09007579 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007580 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007581 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007582 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007583 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007584 } catch (Exception e) {
7585 loge("Exception removing interface: " + e);
7586 }
7587 }
7588 }
7589
Tyler Weare4314862019-12-05 14:55:30 -08007590 // TODO: move to frameworks/libs/net.
7591 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7592 final String nextHop;
7593
7594 switch (route.getType()) {
7595 case RouteInfo.RTN_UNICAST:
7596 if (route.hasGateway()) {
7597 nextHop = route.getGateway().getHostAddress();
7598 } else {
7599 nextHop = INetd.NEXTHOP_NONE;
7600 }
7601 break;
7602 case RouteInfo.RTN_UNREACHABLE:
7603 nextHop = INetd.NEXTHOP_UNREACHABLE;
7604 break;
7605 case RouteInfo.RTN_THROW:
7606 nextHop = INetd.NEXTHOP_THROW;
7607 break;
7608 default:
7609 nextHop = INetd.NEXTHOP_NONE;
7610 break;
7611 }
7612
7613 final RouteInfoParcel rip = new RouteInfoParcel();
7614 rip.ifName = route.getInterface();
7615 rip.destination = route.getDestination().toString();
7616 rip.nextHop = nextHop;
7617 rip.mtu = route.getMtu();
7618
7619 return rip;
7620 }
7621
Paul Jensene0fd4a82014-08-06 15:51:33 -04007622 /**
7623 * Have netd update routes from oldLp to newLp.
7624 * @return true if routes changed between oldLp and newLp
7625 */
7626 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007627 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007628 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7629 new CompareOrUpdateResult<>(
7630 oldLp != null ? oldLp.getAllRoutes() : null,
7631 newLp != null ? newLp.getAllRoutes() : null,
7632 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007633
7634 // add routes before removing old in case it helps with continuous connectivity
7635
Chalard Jean9dd11612018-06-04 16:52:49 +09007636 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007637 for (RouteInfo route : routeDiff.added) {
7638 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007639 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007640 try {
Tyler Weare4314862019-12-05 14:55:30 -08007641 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007642 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007643 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007644 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007645 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007646 }
7647 }
7648 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007649 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007650 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007651 try {
Tyler Weare4314862019-12-05 14:55:30 -08007652 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007653 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007654 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007655 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007656 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007657 }
7658 }
7659
7660 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007661 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007662 try {
Tyler Weare4314862019-12-05 14:55:30 -08007663 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007664 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007665 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007666 }
7667 }
Tyler Weare4314862019-12-05 14:55:30 -08007668
7669 for (RouteInfo route : routeDiff.updated) {
7670 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7671 try {
7672 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7673 } catch (Exception e) {
7674 loge("Exception in networkUpdateRouteParcel: " + e);
7675 }
7676 }
7677 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7678 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007679 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007680
Erik Klineb9888902016-04-05 13:30:49 +09007681 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7682 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7683 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007684 }
Erik Klineb9888902016-04-05 13:30:49 +09007685
Erik Kline31b4a9e2018-01-11 21:07:29 +09007686 if (DBG) {
7687 final Collection<InetAddress> dnses = newLp.getDnsServers();
7688 log("Setting DNS servers for network " + netId + " to " + dnses);
7689 }
Erik Klineb9888902016-04-05 13:30:49 +09007690 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007691 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007692 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007693 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007694 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007695 }
Erik Kline54e35c02017-04-07 15:29:29 +09007696 }
7697
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007698 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7699 NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00007700 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
7701 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00007702 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
7703 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007704
7705 if (!wasFiltering && !needsFiltering) {
7706 // Nothing to do.
7707 return;
7708 }
7709
7710 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7711 // Nothing changed.
7712 return;
7713 }
7714
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007715 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00007716 if (ranges == null || ranges.isEmpty()) {
7717 return;
7718 }
7719
Qingxi Libb8da982020-01-17 17:54:27 -08007720 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007721 // TODO: this create a window of opportunity for apps to receive traffic between the time
7722 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007723 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007724 // old rules are being removed.
7725 if (wasFiltering) {
7726 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7727 }
7728 if (needsFiltering) {
7729 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7730 }
7731 }
7732
Valentin Iftime9fa35092019-09-24 13:32:13 +02007733 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007734 if (mWolSupportedInterfaces == null) {
7735 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007736 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007737 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007738 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7739 }
7740
Luke Huangb913c812018-08-24 20:33:16 +08007741 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007742 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007743 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007744 }
7745 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007746 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007747 }
Luke Huangb913c812018-08-24 20:33:16 +08007748 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007749 }
7750
Chalard Jean62edfd82019-12-02 18:39:29 +09007751 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7752 @NonNull final NetworkCapabilities newNc) {
7753 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7754 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09007755 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09007756 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007757 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08007758 } catch (RemoteException | ServiceSpecificException e) {
7759 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09007760 }
7761 }
7762 }
7763
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007764 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007765 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09007766 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007767 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08007768 underlyingNetworks = underlyingNetworksOrDefault(
7769 agentCaps.getOwnerUid(), underlyingNetworks);
lifrade6c2a2021-03-04 14:08:08 +08007770 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007771 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7772 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007773 // metered if any underlying is metered, or originally declared metered by the agent.
7774 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007775 boolean roaming = false; // roaming if any underlying is roaming
7776 boolean congested = false; // congested if any underlying is congested
7777 boolean suspended = true; // suspended if all underlying are suspended
7778
7779 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08007780 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007781 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08007782 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007783 for (Network underlyingNetwork : underlyingNetworks) {
7784 final NetworkAgentInfo underlying =
7785 getNetworkAgentInfoForNetwork(underlyingNetwork);
7786 if (underlying == null) continue;
7787
7788 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7789 hadUnderlyingNetworks = true;
7790 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007791 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007792 }
7793
7794 // Merge capabilities of this underlying network. For bandwidth, assume the
7795 // worst case.
7796 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7797 underlyingCaps.getLinkDownstreamBandwidthKbps());
7798 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7799 underlyingCaps.getLinkUpstreamBandwidthKbps());
7800 // If this underlying network is metered, the VPN is metered (it may cost money
7801 // to send packets on this network).
7802 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7803 // If this underlying network is roaming, the VPN is roaming (the billing structure
7804 // is different than the usual, local one).
7805 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7806 // If this underlying network is congested, the VPN is congested (the current
7807 // condition of the network affects the performance of this network).
7808 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7809 // If this network is not suspended, the VPN is not suspended (the VPN
7810 // is able to transfer some data).
7811 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08007812 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007813 }
7814 }
7815 if (!hadUnderlyingNetworks) {
7816 // No idea what the underlying networks are; assume reasonable defaults
7817 metered = true;
7818 roaming = false;
7819 congested = false;
7820 suspended = false;
7821 }
7822
lifrade6c2a2021-03-04 14:08:08 +08007823 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007824 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7825 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7826 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7827 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7828 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7829 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08007830 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007831 }
7832
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007833 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007834 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7835 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7836 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04007837 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007838 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007839 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09007840 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007841 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7842 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007843 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007844 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09007845 if (nai.everConnected()
7846 && !nai.isVPN()
7847 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007848 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09007849 // does not cause any request (that is not a listen) currently matching that agent to
7850 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007851 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09007852 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007853 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09007854 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007855 }
7856
Paul Jensen53f08952015-06-16 14:27:36 -04007857 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007858 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09007859 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007860 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007861 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007862 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007863 }
Chalard Jean254bd162022-08-25 13:04:51 +09007864 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007865 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007866 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007867 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007868 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007869 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007870 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007871 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007872 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007873 }
Chalard Jean254bd162022-08-25 13:04:51 +09007874 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08007875 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7876 } else {
7877 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7878 }
lucasline117e2e2019-10-22 18:27:33 +08007879 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007880
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007881 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09007882 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7883 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007884 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09007885 }
7886
Lorenzo Colittibd079452021-07-02 11:47:57 +09007887 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09007888 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09007889 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007890 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007891 }
7892
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007893 return newNc;
7894 }
7895
Lorenzo Colitti44840702021-01-11 22:27:57 +09007896 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7897 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7898 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7899 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7900 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7901 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7902 if (prevSuspended != suspended) {
7903 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7904 // onResumed have been removed.
7905 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7906 : ConnectivityManager.CALLBACK_RESUMED);
7907 }
7908 if (prevSuspended != suspended || prevRoaming != roaming) {
7909 // updateNetworkInfo will mix in the suspended info from the capabilities and
7910 // take appropriate action for the network having possibly changed state.
7911 updateNetworkInfo(nai, nai.networkInfo);
7912 }
7913 }
7914
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007915 /**
7916 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7917 *
7918 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7919 * capabilities we manage and store in {@code nai}, such as validated status and captive
7920 * portal status)
7921 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7922 * potentially triggers rematches.
7923 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7924 * change.)
7925 *
7926 * @param oldScore score of the network before any of the changes that prompted us
7927 * to call this function.
7928 * @param nai the network having its capabilities updated.
7929 * @param nc the new network capabilities.
7930 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007931 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09007932 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007933 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007934 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean62edfd82019-12-02 18:39:29 +09007935 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09007936 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007937
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007938 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09007939 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09007940 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007941
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007942 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007943 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7944 // the change we're processing can't affect any requests, it can only affect the listens
7945 // on this network. We might have been called by rematchNetworkAndRequests when a
7946 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09007947 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007948 } else {
7949 // If the requestable capabilities have changed or the score changed, we can't have been
7950 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09007951 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04007952 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07007953 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09007954 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007955
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007956 final boolean oldMetered = prevNc.isMetered();
7957 final boolean newMetered = newNc.isMetered();
7958 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08007959
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007960 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00007961 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7962 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007963 }
junyulaif2c67e42018-08-07 19:50:45 +08007964
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007965 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7966 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08007967
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007968 // Report changes that are interesting for network statistics tracking.
7969 if (meteredChanged || roamingChanged) {
7970 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06007971 }
7972
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007973 // This network might have been underlying another network. Propagate its capabilities.
7974 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08007975
7976 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007977 mDnsManager.updateTransportsForNetwork(
7978 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08007979 }
lucaslin53e8a262021-06-08 01:43:59 +08007980
7981 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007982 }
7983
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007984 /** Convenience method to update the capabilities for a given network. */
7985 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007986 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007987 }
7988
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007989 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00007990 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007991 *
7992 * Ingress interface filtering enforces that all apps under the given network can only receive
7993 * packets from the network's interface (and loopback). This is important for VPNs because
7994 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7995 * non-VPN interfaces.
7996 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00007997 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007998 * 1. the network is an app VPN (not legacy VPN)
7999 * 2. the VPN does not allow bypass
8000 * 3. the VPN is fully-routed
8001 * 4. the VPN interface is non-null
8002 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008003 * @see INetd#firewallAddUidInterfaceRules
8004 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008005 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008006 @Nullable
8007 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008008 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008009 if (nc == null || lp == null) return null;
8010 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008011 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008012 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008013 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008014 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008015 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008016 && !lp.hasExcludeRoute()) {
8017 return lp.getInterfaceName();
8018 }
8019 return null;
8020 }
8021
8022 /**
8023 * Returns whether we need to set interface filtering rule or not
8024 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008025 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008026 String isolationIface) {
8027 // Allow rules are always needed if VPN isolation is enabled.
8028 if (isolationIface != null) return true;
8029
8030 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8031 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8032 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
8033 return SdkLevel.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008034 }
8035
Chiachang Wang28afaff2020-12-10 22:24:47 +08008036 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8037 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8038 int index = 0;
8039 for (UidRange range : ranges) {
8040 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8041 index++;
8042 }
8043 return stableRanges;
8044 }
8045
Chalard Jeane6c95272022-01-25 21:04:21 +09008046 private static UidRangeParcel[] intsToUidRangeStableParcels(
8047 final @NonNull ArraySet<Integer> uids) {
8048 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8049 int index = 0;
8050 for (int uid : uids) {
8051 stableRanges[index] = new UidRangeParcel(uid, uid);
8052 index++;
8053 }
8054 return stableRanges;
8055 }
8056
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008057 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8058 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8059 for (int i = 0; i < ranges.length; i++) {
8060 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8061 }
8062 return stableRanges;
8063 }
8064
Ken Chen5e65a852020-12-24 12:59:10 +08008065 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
8066 int[] exemptUids) {
8067 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8068 try {
8069 mNetd.socketDestroy(ranges, exemptUids);
8070 } catch (Exception e) {
8071 loge("Exception in socket destroy: ", e);
8072 }
8073 }
8074 }
8075
paulhuaa0743d2021-05-26 21:56:03 +08008076 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08008077 int[] exemptUids = new int[2];
8078 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8079 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8080 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
8081 exemptUids[0] = VPN_UID;
8082 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
8083 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8084
8085 maybeCloseSockets(nai, ranges, exemptUids);
8086 try {
8087 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008088 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008089 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008090 } else {
paulhu0e79d952021-06-09 16:11:35 +08008091 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008092 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008093 }
8094 } catch (Exception e) {
8095 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8096 " on netId " + nai.network.netId + ". " + e);
8097 }
8098 maybeCloseSockets(nai, ranges, exemptUids);
8099 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008100
lucaslin53e8a262021-06-08 01:43:59 +08008101 private boolean isProxySetOnAnyDefaultNetwork() {
8102 ensureRunningOnConnectivityServiceThread();
8103 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8104 final NetworkAgentInfo nai = nri.getSatisfier();
8105 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8106 return true;
8107 }
8108 }
8109 return false;
8110 }
8111
8112 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8113 NetworkCapabilities newNc) {
8114 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8115 // the proxy might be changed since the default network satisfied by the apps might also
8116 // changed.
8117 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
8118 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09008119 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
8120 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09008121 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08008122 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
8123 mProxyTracker.sendProxyBroadcast();
8124 }
8125 }
8126
Chalard Jeane6c95272022-01-25 21:04:21 +09008127 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
8128 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008129 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
8130 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008131 if (null == prevRanges) prevRanges = new ArraySet<>();
8132 if (null == newRanges) newRanges = new ArraySet<>();
8133 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
8134
8135 prevRanges.removeAll(newRanges);
8136 newRanges.removeAll(prevRangesCopy);
8137
8138 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008139 // When updating the VPN uid routing rules, add the new range first then remove the old
8140 // range. If old range were removed first, there would be a window between the old
8141 // range being removed and the new range being added, during which UIDs contained
8142 // in both ranges are not subject to any VPN routing rules. Adding new range before
8143 // removing old range works because, unlike the filtering rules below, it's possible to
8144 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08008145 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
8146 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
8147 // [1-5] & [1-2],[4-5] == [3]
8148 // Then we can do:
8149 // maybeCloseSockets([3])
8150 // mNetd.networkAddUidRanges([1-2],[4-5])
8151 // mNetd.networkRemoveUidRanges([1-5])
8152 // maybeCloseSockets([3])
8153 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
8154 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09008155 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008156 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008157 }
8158 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008159 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008160 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00008161 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
8162 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008163 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
8164 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008165 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09008166 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008167 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
8168 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
8169 // were added first and then newRanges got removed later, there would be only one uid
8170 // 10013 left. A consequence of removing old ranges before adding new ranges is that
8171 // there is now a window of opportunity when the UIDs are not subject to any filtering.
8172 // Note that this is in contrast with the (more robust) update of VPN routing rules
8173 // above, where the addition of new ranges happens before the removal of old ranges.
8174 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
8175 // to be removed will never overlap with the new range to be added.
8176 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008177 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
8178 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008179 }
8180 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008181 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008182 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09008183 } catch (Exception e) {
8184 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008185 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008186 }
8187 }
8188
Chalard Jeande665262022-02-25 16:12:12 +09008189 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09008190 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
8191 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09008192 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
8193 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09008194 if (prevEmpty && newEmpty) return;
8195
8196 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09008197 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008198 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09008199 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008200
8201 if (prevUids.equals(newUids)) return;
8202
8203 // This implementation is very simple and vastly faster for sets of Integers than
8204 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
8205 // a key computed from the value and has storage for that.
8206 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
8207 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
8208 toRemove.removeAll(newUids);
8209 toAdd.removeAll(prevUids);
8210
8211 try {
8212 if (!toAdd.isEmpty()) {
8213 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
8214 nai.network.netId,
8215 intsToUidRangeStableParcels(toAdd),
8216 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8217 }
8218 if (!toRemove.isEmpty()) {
8219 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
8220 nai.network.netId,
8221 intsToUidRangeStableParcels(toRemove),
8222 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8223 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008224 } catch (ServiceSpecificException e) {
8225 // Has the interface disappeared since the network was built ?
8226 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09008227 } catch (RemoteException e) {
8228 // Netd died. This usually causes a runtime restart anyway.
8229 }
8230 }
8231
Hugo Benichi9d35b752017-09-01 01:23:32 +00008232 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008233 ensureRunningOnConnectivityServiceThread();
8234
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008235 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008236 // Ignore updates for disconnected networks
8237 return;
8238 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008239 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008240 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09008241 + "; created=" + nai.getCreatedTime()
8242 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00008243 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008244 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8245 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008246 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008247 }
8248
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008249 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8250 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008251 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008252 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008253 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008254 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8255 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8256 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008257 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8258 // need to be sent as a separate extra.
8259 final NetworkRequest req = nri.isMultilayerRequest()
8260 ? nri.getActiveRequest()
8261 // Non-multilayer listen requests do not have an active request
8262 : nri.mRequests.get(0);
8263 if (req == null) {
8264 Log.wtf(TAG, "No request in NRI " + nri);
8265 }
8266 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008267 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008268 sendIntent(nri.mPendingIntent, intent);
8269 }
8270 // else not handled
8271 }
8272
8273 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8274 mPendingIntentWakeLock.acquire();
8275 try {
8276 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00008277 final BroadcastOptions options = BroadcastOptions.makeBasic();
8278 if (SdkLevel.isAtLeastT()) {
8279 // Explicitly disallow the receiver from starting activities, to prevent apps from
8280 // utilizing the PendingIntent as a backdoor to do this.
8281 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
8282 }
8283 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
8284 null /* requiredPermission */,
8285 SdkLevel.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008286 } catch (PendingIntent.CanceledException e) {
8287 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8288 mPendingIntentWakeLock.release();
8289 releasePendingNetworkRequest(pendingIntent);
8290 }
8291 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8292 }
8293
8294 @Override
8295 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8296 String resultData, Bundle resultExtras) {
8297 if (DBG) log("Finished sending " + pendingIntent);
8298 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008299 // Release with a delay so the receiving client has an opportunity to put in its
8300 // own request.
8301 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008302 }
8303
Chalard Jean46bfbf02022-02-02 00:56:25 +09008304 // networkAgent is only allowed to be null if notificationType is
8305 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
8306 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08008307 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09008308 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08008309 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008310 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008311 // Default request has no msgr. Also prevents callbacks from being invoked for
8312 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8313 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8314 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008315 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008316 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008317 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008318 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008319 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008320 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008321 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008322 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8323 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008324 }
Roshan Pius951c0032020-12-22 15:10:42 -08008325 final boolean includeLocationSensitiveInfo =
8326 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008327 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008328 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008329 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08008330 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09008331 networkCapabilitiesRestrictedForCallerPermissions(
8332 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
8333 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008334 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09008335 nri.mCallingAttributionTag);
8336 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008337 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8338 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008339 // For this notification, arg1 contains the blocked status.
8340 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008341 break;
8342 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008343 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008344 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008345 break;
8346 }
8347 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008348 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008349 final NetworkCapabilities netCap =
8350 networkCapabilitiesRestrictedForCallerPermissions(
8351 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8352 putParcelable(
8353 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008354 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008355 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008356 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008357 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008358 break;
8359 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008360 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008361 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8362 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008363 break;
8364 }
junyulaif2c67e42018-08-07 19:50:45 +08008365 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008366 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008367 msg.arg1 = arg1;
8368 break;
8369 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008370 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008371 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008372 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008373 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008374 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008375 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008376 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008377 }
James Mattis45d81842021-01-10 14:24:24 -08008378 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008379 } catch (RemoteException e) {
8380 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008381 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008382 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008383 }
8384
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008385 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8386 bundle.putParcelable(t.getClass().getSimpleName(), t);
8387 }
8388
Chalard Jean0702f982021-09-16 21:50:07 +09008389 /**
8390 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8391 *
8392 * When a request should be assigned to a new network, it is normally lingered to give
8393 * time for apps to gracefully migrate their connections. When both networks are on the same
8394 * radio, but that radio can't do time-sharing efficiently, this may end up being
8395 * counter-productive because any traffic on the old network may drastically reduce the
8396 * performance of the new network.
8397 * The stack supports a configuration to let modem vendors state that their radio can't
8398 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8399 * from one cell network to another can't be done gracefully.
8400 *
8401 * @param oldNai the old network serving the request
8402 * @param newNai the new network serving the request
8403 * @return whether the switch can be graceful
8404 */
8405 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8406 @NonNull final NetworkAgentInfo newSatisfier) {
8407 if (mCellularRadioTimesharingCapable) return true;
8408 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8409 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8410 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8411 }
8412
Paul Jensenaf94b982014-09-30 15:37:41 -04008413 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008414 if (nai.numRequestNetworkRequests() != 0) {
8415 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8416 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008417 // Ignore listening and track default requests.
8418 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008419 loge("Dead network still had at least " + nr);
8420 break;
8421 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008422 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008423 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008424 }
8425
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008426 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8427 if (oldNetwork == null) {
8428 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8429 return;
8430 }
Chalard Jean49707572019-12-10 21:07:02 +09008431 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008432
8433 // If we get here it means that the last linger timeout for this network expired. So there
8434 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008435 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008436
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008437 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008438 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008439 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008440 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008441 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008442 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008443 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008444 }
8445
James Mattise3ef1912020-12-20 11:09:58 -08008446 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8447 boolean isDefaultChanged = false;
8448 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8449 final NetworkReassignment.RequestReassignment reassignment =
8450 changes.getReassignment(defaultRequestInfo);
8451 if (null == reassignment) {
8452 continue;
8453 }
8454 // reassignment only contains those instances where the satisfying network changed.
8455 isDefaultChanged = true;
8456 // Notify system services of the new default.
8457 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8458 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008459
James Mattise3ef1912020-12-20 11:09:58 -08008460 if (isDefaultChanged) {
8461 // Hold a wakelock for a short time to help apps in migrating to a new default.
8462 scheduleReleaseNetworkTransitionWakelock();
8463 }
8464 }
8465
8466 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8467 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8468 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8469 if (DBG) {
8470 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8471 }
Chalard Jean8e382112019-12-03 20:45:30 +09008472
James Mattisd31bdfa2020-12-23 16:37:26 -08008473 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8474 if (newDefaultNetwork != null) {
8475 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008476 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008477
James Mattisd31bdfa2020-12-23 16:37:26 -08008478 // Set an app level managed default and return since further processing only applies to the
8479 // default network.
8480 if (mDefaultRequest != nri) {
8481 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8482 return;
8483 }
8484
8485 makeDefaultNetwork(newDefaultNetwork);
8486
James Mattise3ef1912020-12-20 11:09:58 -08008487 if (oldDefaultNetwork != null) {
8488 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8489 }
8490 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008491 handleApplyDefaultProxy(null != newDefaultNetwork
8492 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8493 updateTcpBufferSizes(null != newDefaultNetwork
8494 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008495 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008496 }
8497
James Mattisd31bdfa2020-12-23 16:37:26 -08008498 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8499 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8500 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8501 try {
8502 if (VDBG) {
8503 log("Setting default network for " + nri
8504 + " using UIDs " + nri.getUids()
8505 + " with old network " + (oldDefaultNetwork != null
8506 ? oldDefaultNetwork.network().getNetId() : "null")
8507 + " and new network " + (newDefaultNetwork != null
8508 ? newDefaultNetwork.network().getNetId() : "null"));
8509 }
8510 if (nri.getUids().isEmpty()) {
8511 throw new IllegalStateException("makeDefaultForApps called without specifying"
8512 + " any applications to set as the default." + nri);
8513 }
8514 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008515 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008516 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008517 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008518 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008519 }
8520 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008521 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008522 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008523 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008524 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008525 }
8526 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008527 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008528 }
8529 }
8530
8531 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8532 try {
8533 if (null != newDefaultNetwork) {
8534 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8535 } else {
8536 mNetd.networkClearDefault();
8537 }
8538 } catch (RemoteException | ServiceSpecificException e) {
8539 loge("Exception setting default network :" + e);
8540 }
8541 }
8542
Chalard Jean05cbe972019-12-09 11:50:38 +09008543 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008544 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09008545 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09008546 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09008547 processNewlySatisfiedListenRequests(nai);
8548 }
8549
8550 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008551 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8552 if (nri.isMultilayerRequest()) {
8553 continue;
8554 }
8555 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008556 if (!nr.isListen()) continue;
8557 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08008558 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008559 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
8560 }
8561 }
Chalard Jeancd397a22019-11-22 22:33:33 +09008562 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008563
Chalard Jeancd397a22019-11-22 22:33:33 +09008564 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008565 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8566 if (nri.isMultilayerRequest()) {
8567 continue;
8568 }
8569 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008570 if (!nr.isListen()) continue;
8571 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
8572 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09008573 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008574 }
8575 }
8576 }
8577
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008578 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008579 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008580 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08008581 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09008582 @Nullable public final NetworkRequest mOldNetworkRequest;
8583 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008584 @Nullable public final NetworkAgentInfo mOldNetwork;
8585 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08008586 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008587 @Nullable final NetworkRequest oldNetworkRequest,
8588 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008589 @Nullable final NetworkAgentInfo oldNetwork,
8590 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008591 mNetworkRequestInfo = networkRequestInfo;
8592 mOldNetworkRequest = oldNetworkRequest;
8593 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008594 mOldNetwork = oldNetwork;
8595 mNewNetwork = newNetwork;
8596 }
Chalard Jean49707572019-12-10 21:07:02 +09008597
8598 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09008599 final NetworkRequest requestToShow = null != mNewNetworkRequest
8600 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
8601 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08008602 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
8603 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09008604 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008605 }
8606
Chalard Jean46a62372019-12-10 21:25:24 +09008607 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008608
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008609 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09008610 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008611 }
8612
8613 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09008614 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09008615 // The code is never supposed to add two reassignments of the same request. Make
8616 // sure this stays true, but without imposing this expensive check on all
8617 // reassignments on all user devices.
8618 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08008619 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09008620 throw new IllegalStateException("Trying to reassign ["
8621 + reassignment + "] but already have ["
8622 + existing + "]");
8623 }
8624 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09008625 }
Chalard Jean46a62372019-12-10 21:25:24 +09008626 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008627 }
8628
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008629 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09008630 // the passed request.
8631 @Nullable
8632 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008633 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008634 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008635 }
8636 return null;
8637 }
Chalard Jean49707572019-12-10 21:07:02 +09008638
8639 public String toString() {
8640 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8641 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09008642 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008643 for (final RequestReassignment rr : getRequestReassignments()) {
8644 sj.add(rr.toString());
8645 }
8646 return sj.toString();
8647 }
8648
8649 public String debugString() {
8650 final StringBuilder sb = new StringBuilder();
8651 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09008652 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008653 for (final RequestReassignment rr : getRequestReassignments()) {
8654 sb.append("\n ").append(rr);
8655 }
8656 return sb.append("\n").toString();
8657 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008658 }
8659
Chalard Jean24344d72019-12-04 13:32:31 +09008660 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008661 @Nullable final NetworkRequest previousRequest,
8662 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09008663 @Nullable final NetworkAgentInfo previousSatisfier,
8664 @Nullable final NetworkAgentInfo newSatisfier,
8665 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08008666 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09008667 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09008668 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008669 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008670 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09008671 }
James Mattisa076c532020-12-02 14:12:41 -08008672 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09008673 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09008674 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09008675 // If this network switch can't be supported gracefully, the request is not
8676 // lingered. This allows letting go of the network sooner to reclaim some
8677 // performance on the new network, since the radio can't do both at the same
8678 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09008679 //
8680 // Also don't linger the request if the old network has been destroyed.
8681 // A destroyed network does not provide actual network connectivity, so
8682 // lingering it is not useful. In particular this ensures that a destroyed
8683 // network is outscored by its replacement,
8684 // then it is torn down immediately instead of being lingered, and any apps that
8685 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09008686 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8687 }
Chalard Jean24344d72019-12-04 13:32:31 +09008688 } else {
8689 if (VDBG || DDBG) log(" accepting network in place of null");
8690 }
junyulai0ac374f2020-12-14 18:41:52 +08008691
8692 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8693 // and immediately satisfies a request then remove the timer. This will happen for
8694 // all networks except in the case of an underlying network for a VCN.
8695 if (newSatisfier.isNascent()) {
8696 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08008697 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008698 }
8699
Chalard Jean5d6e23b2021-03-01 22:00:20 +09008700 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08008701 newSatisfier.unlingerRequest(newRequest.requestId);
8702 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008703 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08008704 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008705 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09008706 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008707 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008708 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08008709 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008710 }
James Mattisa076c532020-12-02 14:12:41 -08008711 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008712 }
James Mattisa076c532020-12-02 14:12:41 -08008713 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008714 }
8715
James Mattisa076c532020-12-02 14:12:41 -08008716 /**
8717 * This function is triggered when something can affect what network should satisfy what
8718 * request, and it computes the network reassignment from the passed collection of requests to
8719 * network match to the one that the system should now have. That data is encoded in an
8720 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8721 * satisfier.
8722 *
8723 * After the reassignment is computed, it is applied to the state objects.
8724 *
8725 * @param networkRequests the nri objects to evaluate for possible network reassignment
8726 * @return NetworkReassignment listing of proposed network assignment changes
8727 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008728 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08008729 private NetworkReassignment computeNetworkReassignment(
8730 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09008731 final NetworkReassignment changes = new NetworkReassignment();
8732
Chalard Jeanc81d4c32021-04-07 17:06:19 +09008733 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09008734 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008735 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09008736 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09008737 }
Chalard Jean857a1712019-12-10 21:08:07 +09008738
James Mattisa076c532020-12-02 14:12:41 -08008739 for (final NetworkRequestInfo nri : networkRequests) {
8740 // Non-multilayer listen requests can be ignored.
8741 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8742 continue;
8743 }
8744 NetworkAgentInfo bestNetwork = null;
8745 NetworkRequest bestRequest = null;
8746 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09008747 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08008748 // Stop evaluating as the highest possible priority request is satisfied.
8749 if (null != bestNetwork) {
8750 bestRequest = req;
8751 break;
8752 }
8753 }
James Mattisd31bdfa2020-12-23 16:37:26 -08008754 if (null == bestNetwork && isDefaultBlocked(nri)) {
8755 // Remove default networking if disallowed for managed default requests.
8756 bestNetwork = mNoServiceNetwork;
8757 }
8758 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09008759 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09008760 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08008761 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09008762 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008763 }
8764 return changes;
8765 }
8766
James Mattisa076c532020-12-02 14:12:41 -08008767 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8768 return new HashSet<>(mNetworkRequests.values());
8769 }
8770
Paul Jensenc88b39b2015-06-16 14:27:36 -04008771 /**
James Mattisa076c532020-12-02 14:12:41 -08008772 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04008773 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04008774 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008775 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08008776 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8777 }
8778
8779 /**
8780 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8781 * being disconnected.
8782 */
8783 private void rematchNetworksAndRequests(
8784 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8785 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09008786 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09008787 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08008788 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09008789 final long computed = SystemClock.elapsedRealtime();
8790 applyNetworkReassignment(changes, start);
8791 final long applied = SystemClock.elapsedRealtime();
8792 issueNetworkNeeds();
8793 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09008794 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09008795 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
8796 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09008797 log(changes.debugString());
8798 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09008799 // Shorter form, only one line of log
8800 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
8801 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09008802 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09008803 }
Chalard Jean64520dc2019-12-04 19:55:32 +09008804
Chalard Jeand7f762d2019-12-10 19:01:29 +09008805 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008806 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008807 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09008808
8809 // Since most of the time there are only 0 or 1 background networks, it would probably
8810 // be more efficient to just use an ArrayList here. TODO : measure performance
8811 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8812 for (final NetworkAgentInfo nai : nais) {
8813 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8814 }
8815
Chalard Jeand7f762d2019-12-10 19:01:29 +09008816 // First, update the lists of satisfied requests in the network agents. This is necessary
8817 // because some code later depends on this state to be correct, most prominently computing
8818 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09008819 for (final NetworkReassignment.RequestReassignment event :
8820 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008821 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8822 event.mOldNetworkRequest, event.mNewNetworkRequest,
8823 event.mOldNetwork, event.mNewNetwork,
8824 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09008825 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008826
James Mattise3ef1912020-12-20 11:09:58 -08008827 // Process default network changes if applicable.
8828 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008829
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008830 // Notify requested networks are available after the default net is switched, but
8831 // before LegacyTypeTracker sends legacy broadcasts
8832 for (final NetworkReassignment.RequestReassignment event :
8833 changes.getRequestReassignments()) {
8834 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008835 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008836 } else {
James Mattisa076c532020-12-02 14:12:41 -08008837 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008838 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008839 }
8840 }
8841
junyulai0ac374f2020-12-14 18:41:52 +08008842 // Update the inactivity state before processing listen callbacks, because the background
8843 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008844 // just yet though, because they have to be sent after the listens are processed to keep
8845 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08008846 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09008847 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08008848 // Rematching may have altered the inactivity state of some networks, so update all
8849 // inactivity timers. updateInactivityState reads the state from the network agent
8850 // and does nothing if the state has not changed : the source of truth is controlled
8851 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8852 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08008853 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08008854 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008855 }
8856 }
8857
Chalard Jeanb10ab412019-12-11 14:12:30 +09008858 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008859 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008860 // Process listen requests and update capabilities if the background state has
8861 // changed for this network. For consistency with previous behavior, send onLost
8862 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09008863 processNewlyLostListenRequests(nai);
8864 if (oldBackground != nai.isBackgroundNetwork()) {
8865 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008866 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09008867 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008868 }
8869
junyulai0ac374f2020-12-14 18:41:52 +08008870 for (final NetworkAgentInfo nai : inactiveNetworks) {
8871 // For nascent networks, if connecting with no foreground request, skip broadcasting
8872 // LOSING for backward compatibility. This is typical when mobile data connected while
8873 // wifi connected with mobile data always-on enabled.
8874 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008875 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008876 }
8877
James Mattise3ef1912020-12-20 11:09:58 -08008878 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09008879
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008880 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008881 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008882 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08008883 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008884 // This network has active linger timers and no requests, but is not
8885 // lingering. Linger it.
8886 //
8887 // One way (the only way?) this can happen if this network is unvalidated
8888 // and became unneeded due to another network improving its score to the
8889 // point where this network will no longer be able to satisfy any requests
8890 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08008891 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008892 notifyNetworkLosing(nai, now);
8893 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09008894 } else {
Chalard Jean49707572019-12-10 21:07:02 +09008895 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09008896 teardownUnneededNetwork(nai);
8897 }
8898 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04008899 }
8900 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008901
Chalard Jean62edfd82019-12-02 18:39:29 +09008902 /**
8903 * Apply a change in background state resulting from rematching networks with requests.
8904 *
8905 * During rematch, a network may change background states by starting to satisfy or stopping
8906 * to satisfy a foreground request. Listens don't count for this. When a network changes
8907 * background states, its capabilities need to be updated and callbacks fired for the
8908 * capability change.
8909 *
8910 * @param nai The network that changed background states
8911 */
8912 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8913 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8914 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8915 updateNetworkPermissions(nai, newNc);
8916 nai.getAndSetNetworkCapabilities(newNc);
8917 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8918 }
8919
Chalard Jeanf0344532019-11-19 19:23:38 +09008920 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08008921 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008922 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09008923 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8924 changes.getReassignment(mDefaultRequest);
8925 final NetworkAgentInfo oldDefaultNetwork =
8926 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8927 final NetworkAgentInfo newDefaultNetwork =
8928 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08008929
Chalard Jean5b409c72021-02-04 13:12:59 +09008930 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008931 // Maintain the illusion : since the legacy API only understands one network at a time,
8932 // if the default network changed, apps should see a disconnected broadcast for the
8933 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09008934 if (oldDefaultNetwork != null) {
8935 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8936 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008937 }
Chalard Jean5b409c72021-02-04 13:12:59 +09008938 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008939 // The new default network can be newly null if and only if the old default
8940 // network doesn't satisfy the default request any more because it lost a
8941 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09008942 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08008943 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09008944 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008945 }
8946 }
8947
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008948 // Now that all the callbacks have been sent, send the legacy network broadcasts
8949 // as needed. This is necessary so that legacy requests correctly bind dns
8950 // requests to this network. The legacy users are listening for this broadcast
8951 // and will generally do a dns request so they can ensureRouteToHost and if
8952 // they do that before the callbacks happen they'll use the default network.
8953 //
8954 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8955 // callbacks, but if apps can receive the broadcast before the callback, they still might
8956 // have an inconsistent view of networking.
8957 //
8958 // This *does* introduce a race where if the user uses the new api
8959 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8960 // they may get old info. Reverse this after the old startUsing api is removed.
8961 // This is on top of the multiple intent sequencing referenced in the todo above.
8962 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09008963 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008964 addNetworkToLegacyTypeTracker(nai);
8965 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08008966 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008967 }
8968
Chalard Jean0354d8c2021-01-12 10:58:56 +09008969 private void issueNetworkNeeds() {
8970 ensureRunningOnConnectivityServiceThread();
8971 for (final NetworkOfferInfo noi : mNetworkOffers) {
8972 issueNetworkNeeds(noi);
8973 }
8974 }
8975
8976 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8977 ensureRunningOnConnectivityServiceThread();
8978 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8979 informOffer(nri, noi.offer, mNetworkRanker);
8980 }
8981 }
8982
8983 /**
8984 * Inform a NetworkOffer about any new situation of a request.
8985 *
8986 * This function handles updates to offers. A number of events may happen that require
8987 * updating the registrant for this offer about the situation :
8988 * • The offer itself was updated. This may lead the offer to no longer being able
8989 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8990 * or conversely being strengthened enough to beat the satisfier (and therefore
8991 * start being needed)
8992 * • The network satisfying a request changed (including cases where the request
8993 * starts or stops being satisfied). The new network may be a stronger or weaker
8994 * match than the old one, possibly affecting whether the offer is needed.
8995 * • The network satisfying a request updated their score. This may lead the offer
8996 * to no longer be able to beat it if the current satisfier got better, or
8997 * conversely start being a good choice if the current satisfier got weaker.
8998 *
8999 * @param nri The request
9000 * @param offer The offer. This may be an updated offer.
9001 */
9002 private static void informOffer(@NonNull NetworkRequestInfo nri,
9003 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9004 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9005 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009006
9007 // Multi-layer requests have a currently active request, the one being satisfied.
9008 // Since the system will try to bring up a better network than is currently satisfying
9009 // the request, NetworkProviders need to be told the offers matching the requests *above*
9010 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9011 // not needed, and the offer is needed for the active request iff the offer can beat
9012 // the satisfier.
9013 // For non-multilayer requests, the logic above gracefully degenerates to only the
9014 // last case.
9015 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9016 // providers that the offer is needed for this request, until the active request is found.
9017 // In a second phase, deal with the currently active request. In a third phase, inform
9018 // the providers that offer is unneeded for the remaining requests.
9019
9020 // First phase : inform providers of all requests above the active request.
9021 int i;
9022 for (i = 0; nri.mRequests.size() > i; ++i) {
9023 final NetworkRequest request = nri.mRequests.get(i);
9024 if (activeRequest == request) break; // Found the active request : go to phase 2
9025 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9026 // Since this request is higher-priority than the one currently satisfied, if the
9027 // offer can satisfy it, the provider should try and bring up the network for sure ;
9028 // no need to even ask the ranker – an offer that can satisfy is always better than
9029 // no network. Hence tell the provider so unless it already knew.
9030 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
9031 offer.onNetworkNeeded(request);
9032 }
9033 }
9034
9035 // Second phase : deal with the active request (if any)
9036 if (null != activeRequest && activeRequest.isRequest()) {
9037 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00009038 // If an offer can satisfy the request, it is considered needed if it is currently
9039 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09009040 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00009041 && satisfier.factorySerialNumber == offer.providerId
9042 && activeRequest.canBeSatisfiedBy(offer.caps);
9043 final boolean newNeeded = currentlyServing
9044 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09009045 if (newNeeded != oldNeeded) {
9046 if (newNeeded) {
9047 offer.onNetworkNeeded(activeRequest);
9048 } else {
9049 // The offer used to be able to beat the satisfier. Now it can't.
9050 offer.onNetworkUnneeded(activeRequest);
9051 }
9052 }
9053 }
9054
9055 // Third phase : inform the providers that the offer isn't needed for any request
9056 // below the active one.
9057 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
9058 final NetworkRequest request = nri.mRequests.get(i);
9059 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9060 // Since this request is lower-priority than the one currently satisfied, if the
9061 // offer can satisfy it, the provider should not try and bring up the network.
9062 // Hence tell the provider so unless it already knew.
9063 if (offer.neededFor(request)) {
9064 offer.onNetworkUnneeded(request);
9065 }
9066 }
9067 }
9068
Chalard Jean61c79252019-11-07 23:07:32 +09009069 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
9070 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9071 NetworkRequest nr = nai.requestAt(i);
9072 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
9073 // legacy type tracker filters out repeat adds
9074 mLegacyTypeTracker.add(nr.legacyType, nai);
9075 }
9076 }
9077
9078 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09009079 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09009080 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
9081 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
9082 if (nai.isVPN()) {
9083 mLegacyTypeTracker.add(TYPE_VPN, nai);
9084 }
9085 }
9086
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09009087 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04009088 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +09009089 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09009090 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04009091 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09009092 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009093
Chalard Jean254bd162022-08-25 13:04:51 +09009094 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009095 // Don't repeat publish.
9096 if (newInetCondition == mDefaultInetConditionPublished) return;
9097
9098 mDefaultInetConditionPublished = newInetCondition;
9099 sendInetConditionBroadcast(nai.networkInfo);
9100 }
9101
Chalard Jeand61375d2020-01-14 22:46:36 +09009102 @NonNull
9103 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
9104 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009105 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09009106 final boolean suspended =
9107 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9108 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
9109 // Only override the state with SUSPENDED if the network is currently in CONNECTED
9110 // state. This is because the network could have been suspended before connecting,
9111 // or it could be disconnecting while being suspended, and in both these cases
9112 // the state should not be overridden. Note that the only detailed state that
9113 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
9114 // worry about multiple different substates of CONNECTED.
9115 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
9116 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009117 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
9118 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
9119 // network agent is created, then goes to suspended, then goes out of suspended without
9120 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +09009121 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009122 ? NetworkInfo.DetailedState.CONNECTED
9123 : NetworkInfo.DetailedState.CONNECTING,
9124 info.getReason(),
9125 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09009126 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009127 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09009128 return newInfo;
9129 }
9130
9131 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
9132 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
9133
Erik Kline99f301b2017-02-15 19:59:17 +09009134 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009135 NetworkInfo oldInfo = null;
9136 synchronized (networkAgent) {
9137 oldInfo = networkAgent.networkInfo;
9138 networkAgent.networkInfo = newInfo;
9139 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009140
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009141 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009142 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
9143 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009144 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009145
Chalard Jean254bd162022-08-25 13:04:51 +09009146 if (!networkAgent.isCreated()
Robin Leea8c0b6e2016-05-01 23:00:00 +01009147 && (state == NetworkInfo.State.CONNECTED
9148 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009149
9150 // A network that has just connected has zero requests and is thus a foreground network.
9151 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
9152
Luke Huangfdd11f82019-04-09 18:41:49 +08009153 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09009154 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009155 // Initialize the network's capabilities to their starting values according to the
9156 // underlying networks. This ensures that the capabilities are correct before
9157 // anything happens to the network.
9158 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09009159 }
Chalard Jean254bd162022-08-25 13:04:51 +09009160 networkAgent.setCreated();
Chiachang Wang3f6cc072021-03-24 18:39:17 +08009161 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +09009162 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Robin Leea8c0b6e2016-05-01 23:00:00 +01009163 }
9164
Chalard Jean254bd162022-08-25 13:04:51 +09009165 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
9166 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009167
lucaslin45e639b2019-04-03 17:09:28 +08009168 // NetworkCapabilities need to be set before sending the private DNS config to
9169 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09009170 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
9171
Erik Kline9a62f012018-03-21 07:18:33 -07009172 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08009173 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
9174 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009175
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +01009176 // If a rate limit has been configured and is applicable to this network (network
9177 // provides internet connectivity), apply it. The tc police filter cannot be attached
9178 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
9179 // updateInterfaces -> INetd#networkAddInterface.
9180 // Note: in case of a system server crash, the NetworkController constructor in netd
9181 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
9182 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
9183 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
9184 mIngressRateLimit);
9185 }
9186
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009187 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
9188 // command must be sent after updating LinkProperties to maximize chances of
9189 // NetworkMonitor seeing the correct LinkProperties when starting.
9190 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009191 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09009192 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009193 }
Chalard Jeand4900722022-02-06 12:25:38 +09009194 final NetworkMonitorParameters params = new NetworkMonitorParameters();
9195 params.networkAgentConfig = networkAgent.networkAgentConfig;
9196 params.networkCapabilities = networkAgent.networkCapabilities;
9197 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
9198 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +09009199 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
9200 // newer callback even before T. However getInterfaceVersion is a synchronized binder
9201 // call that would cause a Log.wtf to be emitted from the system_server process, and
9202 // in the absence of a satisfactory, scalable solution which follows an easy/standard
9203 // process to check the interface version, just use an SDK check. NetworkStack will
9204 // always be new enough when running on T+.
9205 if (SdkLevel.isAtLeastT()) {
9206 networkAgent.networkMonitor().notifyNetworkConnected(params);
9207 } else {
9208 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
9209 params.networkCapabilities);
9210 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09009211 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009212
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009213 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
9214 // be communicated to a particular NetworkAgent depends only on the network's immutable,
9215 // capabilities, so it only needs to be done once on initial connect, not every time the
9216 // network's capabilities change. Note that we do this before rematching the network,
9217 // so we could decide to tear it down immediately afterwards. That's fine though - on
9218 // disconnection NetworkAgents should stop any signal strength monitoring they have been
9219 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09009220 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009221
junyulai0ac374f2020-12-14 18:41:52 +08009222 // Before first rematching networks, put an inactivity timer without any request, this
9223 // allows {@code updateInactivityState} to update the state accordingly and prevent
9224 // tearing down for any {@code unneeded} evaluation in this period.
9225 // Note that the timer will not be rescheduled since the expiry time is
9226 // fixed after connection regardless of the network satisfying other requests or not.
9227 // But it will be removed as soon as the network satisfies a request for the first time.
9228 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
9229 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08009230 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009231
Paul Jensen05e85ee2014-09-11 11:00:39 -04009232 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009233 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009234
9235 // This has to happen after matching the requests, because callbacks are just requests.
9236 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009237 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009238 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04009239 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009240 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04009241 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09009242 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00009243 if (networkAgent.isVPN()) {
9244 // As the active or bound network changes for apps, broadcast the default proxy, as
9245 // apps may need to update their proxy data. This is called after disconnecting from
9246 // VPN to make sure we do not broadcast the old proxy data.
9247 // TODO(b/122649188): send the broadcast only to VPN users.
9248 mProxyTracker.sendProxyBroadcast();
9249 }
Chalard Jean254bd162022-08-25 13:04:51 +09009250 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
9251 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009252 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009253 }
9254 }
9255
Chalard Jean28018572020-12-21 18:36:52 +09009256 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09009257 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
9258 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009259 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07009260 }
9261
Erik Kline99f301b2017-02-15 19:59:17 +09009262 // Notify only this one new request of the current state. Transfer all the
9263 // current state by calling NetworkCapabilities and LinkProperties callbacks
9264 // so that callers can be guaranteed to have as close to atomicity in state
9265 // transfer as can be supported by this current API.
9266 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07009267 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09009268 if (nri.mPendingIntent != null) {
9269 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
9270 // Attempt no subsequent state pushes where intents are involved.
9271 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009272 }
Erik Kline99f301b2017-02-15 19:59:17 +09009273
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009274 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08009275 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009276 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
9277 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
9278 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08009279 }
9280
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009281 // Notify the requests on this NAI that the network is now lingered.
9282 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08009283 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009284 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
9285 }
9286
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009287 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
9288 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
9289 return vpnBlocked
9290 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
9291 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
9292 }
9293
9294 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
9295 if (blockedReasons == BLOCKED_REASON_NONE) {
9296 mUidBlockedReasons.delete(uid);
9297 } else {
9298 mUidBlockedReasons.put(uid, blockedReasons);
9299 }
9300 }
9301
junyulaif2c67e42018-08-07 19:50:45 +08009302 /**
9303 * Notify of the blocked state apps with a registered callback matching a given NAI.
9304 *
9305 * Unlike other callbacks, blocked status is different between each individual uid. So for
9306 * any given nai, all requests need to be considered according to the uid who filed it.
9307 *
9308 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009309 * @param oldMetered True if the previous network capabilities were metered.
9310 * @param newMetered True if the current network capabilities are metered.
9311 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
9312 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08009313 */
9314 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00009315 boolean newMetered, List<UidRange> oldBlockedUidRanges,
9316 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08009317
9318 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9319 NetworkRequest nr = nai.requestAt(i);
9320 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009321
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009322 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9323 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9324 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009325 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009326 : oldVpnBlocked;
9327
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009328 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9329 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9330 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009331 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009332 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009333 }
9334 }
9335 }
9336
9337 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009338 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009339 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009340 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009341 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009342 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009343 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009344 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009345 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009346
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009347 final int oldBlockedState = getBlockedState(
9348 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9349 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9350 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009351 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009352 }
junyulaif2c67e42018-08-07 19:50:45 +08009353 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9354 NetworkRequest nr = nai.requestAt(i);
9355 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009356 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009357 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
9358 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009359 }
9360 }
9361 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009362 }
9363
Chalard Jean3a3f5f22019-04-10 23:07:55 +09009364 @VisibleForTesting
9365 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09009366 // The NetworkInfo we actually send out has no bearing on the real
9367 // state of affairs. For example, if the default connection is mobile,
9368 // and a request for HIPRI has just gone away, we need to pretend that
9369 // HIPRI has just disconnected. So we need to set the type to HIPRI and
9370 // the state to DISCONNECTED, even though the network is of type MOBILE
9371 // and is still connected.
9372 NetworkInfo info = new NetworkInfo(nai.networkInfo);
9373 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09009374 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009375 if (state != DetailedState.DISCONNECTED) {
9376 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09009377 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009378 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009379 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07009380 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
9381 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
9382 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
9383 if (info.isFailover()) {
9384 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
9385 nai.networkInfo.setFailover(false);
9386 }
9387 if (info.getReason() != null) {
9388 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
9389 }
9390 if (info.getExtraInfo() != null) {
9391 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
9392 }
9393 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09009394 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08009395 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07009396 if (newDefaultAgent != null) {
9397 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
9398 newDefaultAgent.networkInfo);
9399 } else {
9400 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
9401 }
9402 }
9403 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
9404 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09009405 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009406 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09009407 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009408 }
9409 }
9410 }
9411
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009412 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009413 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009414 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09009415 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09009416 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009417 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
9418 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009419 NetworkRequestInfo nri = mNetworkRequests.get(nr);
9420 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009421 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009422 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009423 } else {
9424 sendPendingIntentForRequest(nri, networkAgent, notifyType);
9425 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009426 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009427 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009428
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009429 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
9430 notifyNetworkCallbacks(networkAgent, notifyType, 0);
9431 }
9432
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009433 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09009434 * Returns the list of all interfaces that could be used by network traffic that does not
9435 * explicitly specify a network. This includes the default network, but also all VPNs that are
9436 * currently connected.
9437 *
9438 * Must be called on the handler thread.
9439 */
junyulaie7c7d2a2021-01-26 15:29:15 +08009440 @NonNull
9441 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009442 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08009443 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08009444 final Set<Integer> activeNetIds = new ArraySet<>();
9445 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9446 if (nri.isBeingSatisfied()) {
9447 activeNetIds.add(nri.getSatisfier().network().netId);
9448 }
9449 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009450 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +09009451 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09009452 defaultNetworks.add(nai.network);
9453 }
9454 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009455 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09009456 }
9457
9458 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09009459 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
9460 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009461 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08009462 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009463 ensureRunningOnConnectivityServiceThread();
9464 String activeIface = null;
9465 LinkProperties activeLinkProperties = getActiveLinkProperties();
9466 if (activeLinkProperties != null) {
9467 activeIface = activeLinkProperties.getInterfaceName();
9468 }
Benedict Wong9308cd32019-06-12 17:46:31 +00009469
junyulai2050bed2021-01-23 09:46:34 +08009470 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009471 try {
junyulaide41fc22021-01-22 22:46:01 +08009472 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +09009473 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +08009474 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
9475 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009476 } catch (Exception ignored) {
9477 }
9478 }
9479
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07009480 @Override
Udam Sainicd645462016-01-04 12:16:14 -08009481 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08009482 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009483 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009484 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009485
9486 if (!TextUtils.isEmpty(settingUrl)) {
9487 return settingUrl;
9488 }
9489
9490 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009491 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009492 if (!TextUtils.isEmpty(settingUrl)) {
9493 return settingUrl;
9494 }
9495
9496 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009497 }
9498
9499 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009500 public void startNattKeepalive(Network network, int intervalSeconds,
9501 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009502 enforceKeepalivePermission();
9503 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009504 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai070f9ff2019-01-16 20:23:34 +08009505 intervalSeconds, cb,
junyulai011b1f12019-01-03 18:50:15 +08009506 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009507 }
9508
9509 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009510 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009511 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulaid05a1922019-01-15 11:32:44 +08009512 String dstAddr) {
Josh Gao461a1222020-06-16 15:58:11 -07009513 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009514 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009515 mKeepaliveTracker.startNattKeepalive(
9516 getNetworkAgentInfoForNetwork(network), fd, resourceId,
9517 intervalSeconds, cb,
9518 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
9519 } finally {
9520 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9521 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009522 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9523 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009524 }
9525 }
junyulaid05a1922019-01-15 11:32:44 +08009526 }
9527
9528 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009529 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009530 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009531 try {
9532 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08009533 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009534 mKeepaliveTracker.startTcpKeepalive(
9535 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
9536 } finally {
9537 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9538 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009539 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9540 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009541 }
9542 }
junyulai0835a1e2019-01-08 20:04:33 +08009543 }
9544
9545 @Override
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009546 public void stopKeepalive(Network network, int slot) {
9547 mHandler.sendMessage(mHandler.obtainMessage(
junyulai011b1f12019-01-03 18:50:15 +08009548 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009549 }
9550
9551 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07009552 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08009553 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07009554
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009555 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08009556 final long token = Binder.clearCallingIdentity();
9557 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009558 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
9559 UserHandle.getUserHandleForUid(uid))) {
9560 return;
9561 }
9562
Heemin Seogdb8489d2019-06-12 09:21:44 -07009563 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
9564 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009565
9566 // Turn airplane mode off
9567 setAirplaneMode(false);
9568
9569 // restore private DNS settings to default mode (opportunistic)
9570 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
9571 UserHandle.getUserHandleForUid(uid))) {
9572 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
9573 PRIVATE_DNS_MODE_OPPORTUNISTIC);
9574 }
9575
9576 Settings.Global.putString(mContext.getContentResolver(),
9577 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08009578 } finally {
9579 Binder.restoreCallingIdentity(token);
9580 }
Stuart Scottd5463642015-04-02 18:00:02 -07009581 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04009582
Ricky Wai7097cc92018-01-23 04:09:45 +00009583 @Override
9584 public byte[] getNetworkWatchlistConfigHash() {
9585 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
9586 if (nwm == null) {
9587 loge("Unable to get NetworkWatchlistManager");
9588 return null;
9589 }
9590 // Redirect it to network watchlist service to access watchlist file and calculate hash.
9591 return nwm.getWatchlistConfigHash();
9592 }
9593
Hugo Benichibe0c7652016-05-31 16:28:06 +09009594 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09009595 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08009596 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09009597 }
Hugo Benichif4210292017-04-21 15:07:12 +09009598
9599 private static boolean toBool(int encodedBoolean) {
9600 return encodedBoolean != 0; // Only 0 means false.
9601 }
9602
9603 private static int encodeBool(boolean b) {
9604 return b ? 1 : 0;
9605 }
mswest4632928412018-03-12 10:34:34 -07009606
9607 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009608 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
9609 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
9610 @NonNull String[] args) {
9611 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
9612 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07009613 }
9614
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009615 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07009616 @Override
9617 public int onCommand(String cmd) {
9618 if (cmd == null) {
9619 return handleDefaultCommands(cmd);
9620 }
9621 final PrintWriter pw = getOutPrintWriter();
9622 try {
9623 switch (cmd) {
9624 case "airplane-mode":
9625 final String action = getNextArg();
9626 if ("enable".equals(action)) {
9627 setAirplaneMode(true);
9628 return 0;
9629 } else if ("disable".equals(action)) {
9630 setAirplaneMode(false);
9631 return 0;
9632 } else if (action == null) {
9633 final ContentResolver cr = mContext.getContentResolver();
9634 final int enabled = Settings.Global.getInt(cr,
9635 Settings.Global.AIRPLANE_MODE_ON);
9636 pw.println(enabled == 0 ? "disabled" : "enabled");
9637 return 0;
9638 } else {
9639 onHelp();
9640 return -1;
9641 }
9642 default:
9643 return handleDefaultCommands(cmd);
9644 }
9645 } catch (Exception e) {
9646 pw.println(e);
9647 }
9648 return -1;
9649 }
9650
9651 @Override
9652 public void onHelp() {
9653 PrintWriter pw = getOutPrintWriter();
9654 pw.println("Connectivity service commands:");
9655 pw.println(" help");
9656 pw.println(" Print this help text.");
9657 pw.println(" airplane-mode [enable|disable]");
9658 pw.println(" Turn airplane mode on or off.");
9659 pw.println(" airplane-mode");
9660 pw.println(" Get airplane mode.");
9661 }
9662 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009663
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09009664 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009665 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
9666 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
9667 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +08009668 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009669 }
9670
he_won.hwang881307a2022-03-15 21:23:52 +09009671 private void maybeUpdateWifiRoamTimestamp(NetworkAgentInfo nai, NetworkCapabilities nc) {
9672 if (nai == null) return;
9673 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
9674 final TransportInfo newInfo = nc.getTransportInfo();
9675 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
9676 return;
9677 }
9678 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +09009679 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +09009680 }
9681 }
9682
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009683 /**
9684 * @param connectionInfo the connection to resolve.
9685 * @return {@code uid} if the connection is found and the app has permission to observe it
9686 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
9687 * connection is not found.
9688 */
9689 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009690 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
9691 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
9692 }
9693
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09009694 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009695 connectionInfo.local, connectionInfo.remote);
9696
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009697 if (uid == INVALID_UID) return uid; // Not found.
9698
9699 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
9700 // VPN, if any, that applies to the UID that owns the connection.
9701 if (checkNetworkStackPermission()) return uid;
9702
9703 final NetworkAgentInfo vpn = getVpnForUid(uid);
9704 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09009705 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009706 return INVALID_UID;
9707 }
9708
9709 return uid;
9710 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +00009711
Benedict Wong493e04b2018-11-09 14:45:34 -08009712 /**
9713 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
9714 *
9715 * <p>The TestNetworkService must be run in the system server due to TUN creation.
9716 */
9717 @Override
9718 public IBinder startOrGetTestNetworkService() {
9719 synchronized (mTNSLock) {
9720 TestNetworkService.enforceTestNetworkPermissions(mContext);
9721
9722 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +08009723 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -08009724 }
9725
9726 return mTNS;
9727 }
9728 }
Cody Kestingd199a9d2019-12-17 12:55:28 -08009729
Cody Kesting73708bf2019-12-18 10:57:50 -08009730 /**
9731 * Handler used for managing all Connectivity Diagnostics related functions.
9732 *
9733 * @see android.net.ConnectivityDiagnosticsManager
9734 *
9735 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9736 */
9737 @VisibleForTesting
9738 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009739 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9740
Cody Kesting73708bf2019-12-18 10:57:50 -08009741 /**
9742 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9743 * android.net.ConnectivityDiagnosticsManager}.
9744 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9745 * NetworkRequestInfo to be registered
9746 */
9747 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9748
9749 /**
9750 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9751 * android.net.ConnectivityDiagnosticsManager}.
9752 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9753 * arg1 = the uid of the caller
9754 */
9755 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9756
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009757 /**
9758 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009759 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009760 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9761 * NetworkMonitor.
9762 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009763 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009764 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009765
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009766 /**
9767 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9768 * been detected on the network.
9769 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9770 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9771 * arg2 = NetID.
9772 * data = PersistableBundle of extras passed from NetworkMonitor.
9773 */
9774 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9775
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009776 /**
9777 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9778 * the platform. This event will invoke {@link
9779 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9780 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -07009781 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009782 */
9783 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9784
Cody Kesting73708bf2019-12-18 10:57:50 -08009785 private ConnectivityDiagnosticsHandler(Looper looper) {
9786 super(looper);
9787 }
9788
9789 @Override
9790 public void handleMessage(Message msg) {
9791 switch (msg.what) {
9792 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9793 handleRegisterConnectivityDiagnosticsCallback(
9794 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9795 break;
9796 }
9797 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9798 handleUnregisterConnectivityDiagnosticsCallback(
9799 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9800 break;
9801 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009802 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009803 final ConnectivityReportEvent reportEvent =
9804 (ConnectivityReportEvent) msg.obj;
9805
Aaron Huang959d3642021-01-21 15:47:41 +08009806 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009807 break;
9808 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009809 case EVENT_DATA_STALL_SUSPECTED: {
9810 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +08009811 final Pair<Long, PersistableBundle> arg =
9812 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009813 if (nai == null) break;
9814
Aaron Huang959d3642021-01-21 15:47:41 +08009815 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009816 break;
9817 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009818 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -07009819 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009820 break;
9821 }
9822 default: {
9823 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9824 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009825 }
9826 }
9827 }
9828
9829 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9830 @VisibleForTesting
9831 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9832 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9833 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009834 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009835
9836 @VisibleForTesting
9837 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009838 @NonNull IConnectivityDiagnosticsCallback cb,
9839 @NonNull NetworkRequestInfo nri,
9840 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009841 mCb = cb;
9842 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009843 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009844 }
9845
9846 @Override
9847 public void binderDied() {
9848 log("ConnectivityDiagnosticsCallback IBinder died.");
9849 unregisterConnectivityDiagnosticsCallback(mCb);
9850 }
9851 }
9852
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009853 /**
9854 * Class used for sending information from {@link
9855 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9856 */
9857 private static class NetworkTestedResults {
9858 private final int mNetId;
9859 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009860 @Nullable private final String mRedirectUrl;
9861
9862 private NetworkTestedResults(
9863 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9864 mNetId = netId;
9865 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009866 mRedirectUrl = redirectUrl;
9867 }
9868 }
9869
9870 /**
9871 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9872 * ConnectivityDiagnosticsHandler}.
9873 */
9874 private static class ConnectivityReportEvent {
9875 private final long mTimestampMillis;
9876 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +08009877 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009878
Aaron Huang959d3642021-01-21 15:47:41 +08009879 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9880 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009881 mTimestampMillis = timestampMillis;
9882 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +08009883 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009884 }
9885 }
9886
Cody Kestingf1120be2020-08-03 18:01:40 -07009887 /**
9888 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
9889 * ConnectivityDiagnosticsHandler}.
9890 */
9891 private static class ReportedNetworkConnectivityInfo {
9892 public final boolean hasConnectivity;
9893 public final boolean isNetworkRevalidating;
9894 public final int reporterUid;
9895 @NonNull public final NetworkAgentInfo nai;
9896
9897 private ReportedNetworkConnectivityInfo(
9898 boolean hasConnectivity,
9899 boolean isNetworkRevalidating,
9900 int reporterUid,
9901 @NonNull NetworkAgentInfo nai) {
9902 this.hasConnectivity = hasConnectivity;
9903 this.isNetworkRevalidating = isNetworkRevalidating;
9904 this.reporterUid = reporterUid;
9905 this.nai = nai;
9906 }
9907 }
9908
Cody Kesting73708bf2019-12-18 10:57:50 -08009909 private void handleRegisterConnectivityDiagnosticsCallback(
9910 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9911 ensureRunningOnConnectivityServiceThread();
9912
9913 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -08009914 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009915 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9916
James Mattis64b8b0f2020-11-24 17:40:49 -08009917 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9918 // confusing for these networks to change when an NRI is satisfied in another layer.
9919 if (nri.isMultilayerRequest()) {
9920 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9921 + "network requests.");
9922 }
9923
Cody Kesting73708bf2019-12-18 10:57:50 -08009924 // This means that the client registered the same callback multiple times. Do
9925 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -08009926 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009927 if (VDBG) log("Diagnostics callback is already registered");
9928
9929 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9930 // incremented when the NetworkRequestInfo is created as part of
9931 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +08009932 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -08009933 return;
9934 }
9935
Cody Kesting31f1ff62020-03-05 10:46:02 -08009936 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -08009937
9938 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -08009939 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009940 } catch (RemoteException e) {
9941 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -08009942 return;
9943 }
9944
9945 // Once registered, provide ConnectivityReports for matching Networks
9946 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9947 synchronized (mNetworkForNetId) {
9948 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9949 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -08009950 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9951 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -08009952 matchingNetworks.add(nai);
9953 }
9954 }
9955 }
9956 for (final NetworkAgentInfo nai : matchingNetworks) {
9957 final ConnectivityReport report = nai.getConnectivityReport();
9958 if (report == null) {
9959 continue;
9960 }
9961 if (!checkConnectivityDiagnosticsPermissions(
9962 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9963 continue;
9964 }
9965
9966 try {
9967 cb.onConnectivityReportAvailable(report);
9968 } catch (RemoteException e) {
9969 // Exception while sending the ConnectivityReport. Move on to the next network.
9970 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009971 }
9972 }
9973
9974 private void handleUnregisterConnectivityDiagnosticsCallback(
9975 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9976 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009977 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009978
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009979 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9980 mConnectivityDiagnosticsCallbacks.remove(iCb);
9981 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009982 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9983 return;
9984 }
9985
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009986 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -08009987
Cody Kesting70fa2b22020-12-02 12:16:56 -08009988 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9989 // (if the Binder died)
9990 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9991 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -08009992 return;
9993 }
9994
Cody Kesting46cb1672020-03-04 13:35:20 -08009995 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9996 // incremented when the NetworkRequestInfo is created as part of
9997 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +08009998 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -08009999
Cody Kesting31f1ff62020-03-05 10:46:02 -080010000 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010001 }
10002
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010003 private void handleNetworkTestedWithExtras(
10004 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
10005 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080010006 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010007 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010008 final ConnectivityReport report =
10009 new ConnectivityReport(
10010 reportEvent.mNai.network,
10011 reportEvent.mTimestampMillis,
10012 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010013 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010014 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080010015 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070010016
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010017 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010018 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010019 for (final IConnectivityDiagnosticsCallback cb : results) {
10020 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080010021 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010022 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070010023 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010024 }
10025 }
10026 }
10027
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010028 private void handleDataStallSuspected(
10029 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
10030 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080010031 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010032 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010033 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080010034 new DataStallReport(
10035 nai.network,
10036 timestampMillis,
10037 detectionMethod,
10038 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010039 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080010040 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010041 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010042 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010043 for (final IConnectivityDiagnosticsCallback cb : results) {
10044 try {
10045 cb.onDataStallSuspected(report);
10046 } catch (RemoteException ex) {
10047 loge("Error invoking onDataStallSuspected", ex);
10048 }
10049 }
10050 }
10051
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010052 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070010053 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
10054 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
10055 final ConnectivityReport cachedReport = nai.getConnectivityReport();
10056
10057 // If the Network is being re-validated as a result of this call to
10058 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
10059 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010060 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010061 getMatchingPermissionedCallbacks(
10062 nai,
10063 reportedNetworkConnectivityInfo.isNetworkRevalidating
10064 ? Process.INVALID_UID
10065 : reportedNetworkConnectivityInfo.reporterUid);
10066
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010067 for (final IConnectivityDiagnosticsCallback cb : results) {
10068 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070010069 cb.onNetworkConnectivityReported(
10070 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010071 } catch (RemoteException ex) {
10072 loge("Error invoking onNetworkConnectivityReported", ex);
10073 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010074
10075 // If the Network isn't re-validating, also provide the cached report. If there is no
10076 // cached report, the Network is still being validated and a report will be sent once
10077 // validation is complete. Note that networks which never undergo validation will still
10078 // have a cached ConnectivityReport with RESULT_SKIPPED.
10079 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
10080 try {
10081 cb.onConnectivityReportAvailable(cachedReport);
10082 } catch (RemoteException ex) {
10083 loge("Error invoking onConnectivityReportAvailable", ex);
10084 }
10085 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010086 }
10087 }
10088
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010089 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090010090 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
10091 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010092 sanitized.setUids(null);
10093 sanitized.setAdministratorUids(new int[0]);
10094 sanitized.setOwnerUid(Process.INVALID_UID);
10095 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080010096 }
10097
Cody Kestingf1120be2020-08-03 18:01:40 -070010098 /**
10099 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
10100 *
10101 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
10102 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010103 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070010104 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010105 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010106 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010107 mConnectivityDiagnosticsCallbacks.entrySet()) {
10108 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
10109 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070010110
James Mattis64b8b0f2020-11-24 17:40:49 -080010111 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070010112 if (!nai.satisfies(nri.mRequests.get(0))) {
10113 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010114 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010115
10116 // UID for this callback must either be:
10117 // - INVALID_UID (which sends callbacks to all UIDs), or
10118 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
10119 // notified as a result)
10120 if (uid != Process.INVALID_UID && uid != nri.mUid) {
10121 continue;
10122 }
10123
10124 if (!checkConnectivityDiagnosticsPermissions(
10125 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10126 continue;
10127 }
10128
10129 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010130 }
10131 return results;
10132 }
10133
Cody Kesting7474f672021-05-11 14:22:40 -070010134 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
10135 @NonNull NetworkAgentInfo nai) {
10136 // TODO(b/188483916): replace with a transport-agnostic location-aware check
10137 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
10138 }
10139
Cody Kesting160ef392021-05-05 13:17:22 -070010140 private boolean hasLocationPermission(String packageName, int uid) {
10141 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
10142 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
10143 // call in a try-catch.
10144 try {
10145 if (!mLocationPermissionChecker.checkLocationPermission(
10146 packageName, null /* featureId */, uid, null /* message */)) {
10147 return false;
10148 }
10149 } catch (SecurityException e) {
10150 return false;
10151 }
10152
10153 return true;
10154 }
10155
10156 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
10157 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090010158 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070010159 && virtual.networkCapabilities.getOwnerUid() == uid
10160 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
10161 return true;
10162 }
10163 }
10164
10165 return false;
10166 }
10167
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010168 @VisibleForTesting
10169 boolean checkConnectivityDiagnosticsPermissions(
10170 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
10171 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
10172 return true;
10173 }
10174
Cody Kesting160ef392021-05-05 13:17:22 -070010175 // Administrator UIDs also contains the Owner UID
10176 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
10177 if (!CollectionUtils.contains(administratorUids, callbackUid)
10178 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010179 return false;
10180 }
10181
Cody Kesting7474f672021-05-11 14:22:40 -070010182 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
10183 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010184 }
10185
Cody Kestingd199a9d2019-12-17 12:55:28 -080010186 @Override
10187 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010188 @NonNull IConnectivityDiagnosticsCallback callback,
10189 @NonNull NetworkRequest request,
10190 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010191 Objects.requireNonNull(callback, "callback must not be null");
10192 Objects.requireNonNull(request, "request must not be null");
10193 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
10194
Cody Kesting73708bf2019-12-18 10:57:50 -080010195 if (request.legacyType != TYPE_NONE) {
10196 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
10197 + " Please use NetworkCapabilities instead.");
10198 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010199 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080010200 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010201
10202 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
10203 // and administrator uids to be safe.
10204 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080010205 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010206
10207 final NetworkRequest requestWithId =
10208 new NetworkRequest(
10209 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
10210
10211 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
10212 //
10213 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
10214 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
10215 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010216 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080010217 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010218 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010219
10220 mConnectivityDiagnosticsHandler.sendMessage(
10221 mConnectivityDiagnosticsHandler.obtainMessage(
10222 ConnectivityDiagnosticsHandler
10223 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
10224 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010225 }
10226
10227 @Override
10228 public void unregisterConnectivityDiagnosticsCallback(
10229 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010230 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080010231 mConnectivityDiagnosticsHandler.sendMessage(
10232 mConnectivityDiagnosticsHandler.obtainMessage(
10233 ConnectivityDiagnosticsHandler
10234 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010235 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080010236 0,
10237 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010238 }
Cody Kestingf53a0752020-04-15 12:33:28 -070010239
10240 @Override
10241 public void simulateDataStall(int detectionMethod, long timestampMillis,
10242 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010243 Objects.requireNonNull(network, "network must not be null");
10244 Objects.requireNonNull(extras, "extras must not be null");
10245
paulhu3ffffe72021-09-16 10:15:22 +080010246 enforceAnyPermissionOf(mContext,
10247 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070010248 android.Manifest.permission.NETWORK_STACK);
10249 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
10250 if (!nc.hasTransport(TRANSPORT_TEST)) {
Chalard Jean15228572022-01-28 19:29:12 +090010251 throw new SecurityException("Data Stall simulation is only possible for test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070010252 }
10253
10254 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010255 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -070010256 throw new SecurityException("Data Stall simulation is only possible for network "
10257 + "creators");
10258 }
10259
Cody Kesting652e3ec2020-05-21 12:08:21 -070010260 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
10261 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
10262 // Data Stall information as a DataStallReportParcelable and passing to
10263 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
10264 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070010265 final DataStallReportParcelable p = new DataStallReportParcelable();
10266 p.timestampMillis = timestampMillis;
10267 p.detectionMethod = detectionMethod;
10268
10269 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
10270 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
10271 }
10272 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
10273 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
10274 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
10275 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
10276 }
10277
Serik Beketayevec8ad212020-12-07 22:43:07 -080010278 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070010279 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010280
lucaslin66f44212021-02-23 01:12:55 +080010281 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
10282 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080010283 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080010284 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080010285 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080010286 }
lucaslin37a16d92021-01-21 19:48:09 +080010287
10288 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010289 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080010290 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010291 nai.clatd.interfaceLinkStateChanged(iface, up);
10292 }
10293 }
10294
10295 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010296 public void onInterfaceRemoved(@NonNull String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080010297 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010298 nai.clatd.interfaceRemoved(iface);
10299 }
lucaslin66f44212021-02-23 01:12:55 +080010300 }
10301 }
10302
lucaslin1a8b4c62021-01-21 02:02:55 +080010303 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
10304
10305 /**
10306 * Class used for updating network activity tracking with netd and notify network activity
10307 * changes.
10308 */
10309 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080010310 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080010311 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080010312 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080010313 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
10314 new RemoteCallbackList<>();
10315 // Indicate the current system default network activity is active or not.
10316 @GuardedBy("mActiveIdleTimers")
10317 private boolean mNetworkActive;
10318 @GuardedBy("mActiveIdleTimers")
Chalard Jean46bfbf02022-02-02 00:56:25 +090010319 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1193a5d2021-01-21 02:04:15 +080010320 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010321
Chalard Jean46bfbf02022-02-02 00:56:25 +090010322 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080010323 public final int timeout;
10324 public final int transportType;
10325
10326 IdleTimerParams(int timeout, int transport) {
10327 this.timeout = timeout;
10328 this.transportType = transport;
10329 }
10330 }
10331
10332 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080010333 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080010334 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080010335 mNetd = netd;
10336 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010337 }
10338
lucaslin66f44212021-02-23 01:12:55 +080010339 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
10340 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
10341 synchronized (mActiveIdleTimers) {
10342 mNetworkActive = active;
10343 // If there are no idle timers, it means that system is not monitoring
10344 // activity, so the system default network for those default network
10345 // unspecified apps is always considered active.
10346 //
10347 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
10348 // any network activity change event. Whenever this event is received,
10349 // the mActiveIdleTimers should be always not empty. The legacy behavior
10350 // is no-op. Remove to refer to mNetworkActive only.
10351 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
10352 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
10353 }
10354 }
10355 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010356
lucaslin1193a5d2021-01-21 02:04:15 +080010357 // The network activity should only be updated from ConnectivityService handler thread
10358 // when mActiveIdleTimers lock is held.
10359 @GuardedBy("mActiveIdleTimers")
10360 private void reportNetworkActive() {
10361 final int length = mNetworkActivityListeners.beginBroadcast();
10362 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
10363 try {
10364 for (int i = 0; i < length; i++) {
10365 try {
10366 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
10367 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010368 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080010369 }
10370 }
10371 } finally {
10372 mNetworkActivityListeners.finishBroadcast();
10373 }
10374 }
10375
10376 @GuardedBy("mActiveIdleTimers")
10377 public void handleReportNetworkActivity() {
10378 synchronized (mActiveIdleTimers) {
10379 reportNetworkActive();
10380 }
10381 }
10382
lucaslin1a8b4c62021-01-21 02:02:55 +080010383 // This is deprecated and only to support legacy use cases.
10384 private int transportTypeToLegacyType(int type) {
10385 switch (type) {
10386 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010387 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080010388 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010389 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080010390 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010391 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080010392 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010393 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080010394 default:
10395 loge("Unexpected transport in transportTypeToLegacyType: " + type);
10396 }
10397 return ConnectivityManager.TYPE_NONE;
10398 }
10399
10400 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
10401 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
10402 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
10403 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
10404 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
10405 final long ident = Binder.clearCallingIdentity();
10406 try {
10407 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
10408 RECEIVE_DATA_ACTIVITY_CHANGE,
10409 null /* resultReceiver */,
10410 null /* scheduler */,
10411 0 /* initialCode */,
10412 null /* initialData */,
10413 null /* initialExtra */);
10414 } finally {
10415 Binder.restoreCallingIdentity(ident);
10416 }
10417 }
10418
10419 /**
10420 * Setup data activity tracking for the given network.
10421 *
10422 * Every {@code setupDataActivityTracking} should be paired with a
10423 * {@link #removeDataActivityTracking} for cleanup.
10424 */
10425 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
10426 final String iface = networkAgent.linkProperties.getInterfaceName();
10427
10428 final int timeout;
10429 final int type;
10430
10431 if (networkAgent.networkCapabilities.hasTransport(
10432 NetworkCapabilities.TRANSPORT_CELLULAR)) {
10433 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010434 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080010435 10);
10436 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10437 } else if (networkAgent.networkCapabilities.hasTransport(
10438 NetworkCapabilities.TRANSPORT_WIFI)) {
10439 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010440 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080010441 15);
10442 type = NetworkCapabilities.TRANSPORT_WIFI;
10443 } else {
10444 return; // do not track any other networks
10445 }
10446
lucaslinb961efc2021-01-21 02:03:17 +080010447 updateRadioPowerState(true /* isActive */, type);
10448
lucaslin1a8b4c62021-01-21 02:02:55 +080010449 if (timeout > 0 && iface != null) {
10450 try {
lucaslin1193a5d2021-01-21 02:04:15 +080010451 synchronized (mActiveIdleTimers) {
10452 // Networks start up.
10453 mNetworkActive = true;
10454 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
10455 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
10456 reportNetworkActive();
10457 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010458 } catch (Exception e) {
10459 // You shall not crash!
10460 loge("Exception in setupDataActivityTracking " + e);
10461 }
10462 }
10463 }
10464
10465 /**
10466 * Remove data activity tracking when network disconnects.
10467 */
10468 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
10469 final String iface = networkAgent.linkProperties.getInterfaceName();
10470 final NetworkCapabilities caps = networkAgent.networkCapabilities;
10471
lucaslinb961efc2021-01-21 02:03:17 +080010472 if (iface == null) return;
10473
10474 final int type;
10475 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
10476 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10477 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
10478 type = NetworkCapabilities.TRANSPORT_WIFI;
10479 } else {
10480 return; // do not track any other networks
10481 }
10482
10483 try {
10484 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080010485 synchronized (mActiveIdleTimers) {
10486 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
10487 // The call fails silently if no idle timer setup for this interface
10488 mNetd.idletimerRemoveInterface(iface, params.timeout,
10489 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080010490 }
lucaslinb961efc2021-01-21 02:03:17 +080010491 } catch (Exception e) {
10492 // You shall not crash!
10493 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080010494 }
10495 }
10496
10497 /**
10498 * Update data activity tracking when network state is updated.
10499 */
10500 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
10501 NetworkAgentInfo oldNetwork) {
10502 if (newNetwork != null) {
10503 setupDataActivityTracking(newNetwork);
10504 }
10505 if (oldNetwork != null) {
10506 removeDataActivityTracking(oldNetwork);
10507 }
10508 }
lucaslinb961efc2021-01-21 02:03:17 +080010509
10510 private void updateRadioPowerState(boolean isActive, int transportType) {
10511 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
10512 switch (transportType) {
10513 case NetworkCapabilities.TRANSPORT_CELLULAR:
10514 bs.reportMobileRadioPowerState(isActive, NO_UID);
10515 break;
10516 case NetworkCapabilities.TRANSPORT_WIFI:
10517 bs.reportWifiRadioPowerState(isActive, NO_UID);
10518 break;
10519 default:
10520 logw("Untracked transport type:" + transportType);
10521 }
10522 }
lucaslin1193a5d2021-01-21 02:04:15 +080010523
10524 public boolean isDefaultNetworkActive() {
10525 synchronized (mActiveIdleTimers) {
10526 // If there are no idle timers, it means that system is not monitoring activity,
10527 // so the default network is always considered active.
10528 //
10529 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
10530 // tracking is disabled (negative idle timer value configured), or no active default
10531 // network. In the latter case, this reports active but it should report inactive.
10532 return mNetworkActive || mActiveIdleTimers.isEmpty();
10533 }
10534 }
10535
10536 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
10537 mNetworkActivityListeners.register(l);
10538 }
10539
10540 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
10541 mNetworkActivityListeners.unregister(l);
10542 }
lucaslin012f7a12021-01-21 02:04:35 +080010543
10544 public void dump(IndentingPrintWriter pw) {
10545 synchronized (mActiveIdleTimers) {
10546 pw.print("mNetworkActive="); pw.println(mNetworkActive);
10547 pw.println("Idle timers:");
10548 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
10549 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
10550 final IdleTimerParams params = ent.getValue();
10551 pw.print(" timeout="); pw.print(params.timeout);
10552 pw.print(" type="); pw.println(params.transportType);
10553 }
10554 }
10555 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010556 }
James Mattis47db0582021-01-01 14:13:35 -080010557
Daniel Brightf9e945b2020-06-15 16:10:01 -070010558 /**
10559 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
10560 *
10561 * @param socketInfo the socket information
10562 * @param callback the callback to register
10563 */
10564 @Override
10565 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
10566 @NonNull final IQosCallback callback) {
10567 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
10568 if (nai == null || nai.networkCapabilities == null) {
10569 try {
10570 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
10571 } catch (final RemoteException ex) {
10572 loge("registerQosCallbackInternal: RemoteException", ex);
10573 }
10574 return;
10575 }
10576 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
10577 }
10578
10579 /**
10580 * Register a {@link IQosCallback} with base {@link QosFilter}.
10581 *
10582 * @param filter the filter to register
10583 * @param callback the callback to register
10584 * @param nai the agent information related to the filter's network
10585 */
10586 @VisibleForTesting
10587 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
10588 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010589 Objects.requireNonNull(filter, "filter must be non-null");
10590 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010591
10592 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080010593 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
10594 // on this network is unregistered when the app loses permission or b) no QoS
10595 // callbacks are sent for restricted networks unless the app currently has permission
10596 // to access restricted networks.
10597 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070010598 }
10599 mQosCallbackTracker.registerCallback(callback, filter, nai);
10600 }
10601
10602 /**
10603 * Unregisters the given callback.
10604 *
10605 * @param callback the callback to unregister
10606 */
10607 @Override
10608 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010609 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010610 mQosCallbackTracker.unregisterCallback(callback);
10611 }
James Mattis47db0582021-01-01 14:13:35 -080010612
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010613 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
10614 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
10615 // Enterprise device can be fully managed like device owner and such use case
10616 // also should be supported. Calling app check for work profile and fully managed device
10617 // is already done in DevicePolicyManager.
10618 // This check is an extra caution to be sure device is fully managed or not.
10619 final UserManager um = mContext.getSystemService(UserManager.class);
10620 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
10621 if (um.isManagedProfile(profile.getIdentifier())) {
10622 return true;
10623 }
10624 if (SdkLevel.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
10625 return false;
10626 }
10627
James Mattis45d81842021-01-10 14:24:24 -080010628 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010629 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010630 *
10631 * See the documentation for the individual preferences for a description of the supported
10632 * behaviors.
10633 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010634 * @param profile If the device owner is set, any profile is allowed.
10635 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010636 * @param preferences the list of profile network preferences for the
10637 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010638 * @param listener an optional listener to listen for completion of the operation.
10639 */
10640 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010641 public void setProfileNetworkPreferences(
10642 @NonNull final UserHandle profile,
10643 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090010644 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010645 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010646 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010647
10648 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010649 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
10650 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
10651 .build();
10652 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010653 }
10654
paulhu3ffffe72021-09-16 10:15:22 +080010655 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010656 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010657 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010658 }
10659 if (profile.getIdentifier() < 0) {
10660 throw new IllegalArgumentException("Must explicitly specify a user handle ("
10661 + "UserHandle.CURRENT not supported)");
10662 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010663 if (!isNetworkPreferenceAllowedForProfile(profile)) {
10664 throw new IllegalArgumentException("Profile must be a managed profile "
10665 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010666 }
paulhuaa0743d2021-05-26 21:56:03 +080010667
Chalard Jean46bfbf02022-02-02 00:56:25 +090010668 final List<ProfileNetworkPreferenceList.Preference> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010669 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010670 for (final ProfileNetworkPreference preference : preferences) {
10671 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010672 boolean allowFallback = true;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010673 switch (preference.getPreference()) {
10674 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
10675 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010676 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010677 if (preference.getPreferenceEnterpriseId() != 0) {
10678 throw new IllegalArgumentException(
10679 "Invalid enterprise identifier in setProfileNetworkPreferences");
10680 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010681 break;
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010682 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
10683 allowFallback = false;
10684 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010685 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010686 // This code is needed even though there is a check later on,
10687 // because isRangeAlreadyInPreferenceList assumes that every preference
10688 // has a UID list.
10689 if (hasDefaultPreference) {
10690 throw new IllegalArgumentException(
10691 "Default profile preference should not be set along with other "
10692 + "preference");
10693 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010694 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
10695 throw new IllegalArgumentException(
10696 "Invalid enterprise identifier in setProfileNetworkPreferences");
10697 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010698 final Set<UidRange> uidRangeSet =
10699 getUidListToBeAppliedForNetworkPreference(profile, preference);
10700 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
10701 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
10702 } else {
10703 throw new IllegalArgumentException(
10704 "Overlapping uid range in setProfileNetworkPreferences");
10705 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010706 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010707 nc.addEnterpriseId(
10708 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010709 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10710 break;
10711 default:
10712 throw new IllegalArgumentException(
10713 "Invalid preference in setProfileNetworkPreferences");
10714 }
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010715 preferenceList.add(new ProfileNetworkPreferenceList.Preference(
10716 profile, nc, allowFallback));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010717 if (hasDefaultPreference && preferenceList.size() > 1) {
10718 throw new IllegalArgumentException(
10719 "Default profile preference should not be set along with other preference");
10720 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010721 }
10722 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010723 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010724 }
10725
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010726 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
10727 @NonNull final UserHandle profile,
10728 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
10729 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080010730 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
10731 profileNetworkPreference.getIncludedUids());
10732
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010733 if (uidRangeSet.size() > 0) {
10734 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
10735 throw new IllegalArgumentException(
10736 "Allow uid range is outside the uid range of profile.");
10737 }
10738 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080010739 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010740 profileNetworkPreference.getExcludedUids());
10741 if (disallowUidRangeSet.size() > 0) {
10742 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
10743 throw new IllegalArgumentException(
10744 "disallow uid range is outside the uid range of profile.");
10745 }
10746 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
10747 disallowUidRangeSet);
10748 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010749 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010750 uidRangeSet.add(profileUids);
10751 }
10752 }
10753 return uidRangeSet;
10754 }
10755
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010756 private boolean isEnterpriseIdentifierValid(
10757 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010758 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010759 return true;
10760 }
10761 return false;
10762 }
10763
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010764 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010765 @NonNull final ProfileNetworkPreferenceList prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010766 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010767 for (final ProfileNetworkPreferenceList.Preference pref : prefs.preferences) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010768 // The NRI for a user should contain the request for capabilities.
10769 // If fallback to default network is needed then NRI should include
10770 // the request for the default network. Create an image of it to
10771 // have the correct UIDs in it (also a request can only be part of one NRI, because
10772 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010773 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
10774 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010775 if (pref.allowFallback) {
10776 nrs.add(createDefaultInternetRequestForTransport(
10777 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10778 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010779 if (VDBG) {
10780 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
10781 pref.capabilities.getUids()));
10782 }
10783
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010784 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080010785 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080010786 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010787 result.add(nri);
10788 }
10789 return result;
10790 }
10791
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010792 /**
10793 * Compare if the given UID range sets have the same UIDs.
10794 *
10795 */
10796 private boolean isRangeAlreadyInPreferenceList(
10797 @NonNull List<ProfileNetworkPreferenceList.Preference> preferenceList,
10798 @NonNull Set<UidRange> uidRangeSet) {
10799 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
10800 return false;
10801 }
10802 for (ProfileNetworkPreferenceList.Preference pref : preferenceList) {
10803 if (UidRangeUtils.doesRangeSetOverlap(
10804 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
10805 return true;
10806 }
10807 }
10808 return false;
10809 }
10810
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010811 private void handleSetProfileNetworkPreference(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010812 @NonNull final List<ProfileNetworkPreferenceList.Preference> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010813 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010814 /*
10815 * handleSetProfileNetworkPreference is always called for single user.
10816 * preferenceList only contains preferences for different uids within the same user
10817 * (enforced by getUidListToBeAppliedForNetworkPreference).
10818 * Clear all the existing preferences for the user before applying new preferences.
10819 *
10820 */
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010821 mProfileNetworkPreferences = mProfileNetworkPreferences.withoutUser(
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010822 preferenceList.get(0).user);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010823 for (final ProfileNetworkPreferenceList.Preference preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010824 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
10825 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010826
paulhu74128522021-09-28 02:29:03 +000010827 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
10828 addPerAppDefaultNetworkRequests(
10829 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai31d38bf2022-07-04 17:28:39 +080010830
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010831 // Finally, rematch.
10832 rematchAllNetworksAndRequests();
10833
10834 if (null != listener) {
10835 try {
10836 listener.onComplete();
10837 } catch (RemoteException e) {
10838 loge("Listener for setProfileNetworkPreference has died");
10839 }
10840 }
10841 }
10842
paulhu51f77dc2021-06-07 02:34:20 +000010843 @VisibleForTesting
10844 @NonNull
10845 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
10846 @NonNull final Set<Integer> uids) {
10847 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10848 if (uids.size() == 0) {
10849 // Should not create NetworkRequestInfo if no preferences. Without uid range in
10850 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
10851 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
10852 return nris;
10853 }
10854
10855 final List<NetworkRequest> requests = new ArrayList<>();
10856 // The NRI should be comprised of two layers:
10857 // - The request for the mobile network preferred.
10858 // - The request for the default network, for fallback.
10859 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090010860 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000010861 requests.add(createDefaultInternetRequestForTransport(
10862 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10863 final Set<UidRange> ranges = new ArraySet<>();
10864 for (final int uid : uids) {
10865 ranges.add(new UidRange(uid, uid));
10866 }
10867 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080010868 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080010869 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000010870 return nris;
10871 }
10872
10873 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000010874 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000010875 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
10876 addPerAppDefaultNetworkRequests(
10877 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000010878 // Finally, rematch.
10879 rematchAllNetworksAndRequests();
10880 }
10881
Patrick Rohr2857ac42022-01-21 14:58:16 +010010882 private void handleIngressRateLimitChanged() {
10883 final long oldIngressRateLimit = mIngressRateLimit;
10884 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
10885 mContext);
10886 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
10887 if (canNetworkBeRateLimited(networkAgent)) {
10888 // If rate limit has previously been enabled, remove the old limit first.
10889 if (oldIngressRateLimit >= 0) {
10890 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
10891 }
10892 if (mIngressRateLimit >= 0) {
10893 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10894 mIngressRateLimit);
10895 }
10896 }
10897 }
10898 }
10899
10900 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090010901 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
10902 if (!SdkLevel.isAtLeastT()) return false;
10903
Patrick Rohrff3b3f82022-02-09 15:15:52 +010010904 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
10905 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
10906 // internet connectivity can be rate limited.
10907 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
10908 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010010909 return false;
10910 }
10911
10912 final String iface = networkAgent.linkProperties.getInterfaceName();
10913 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010010914 // This may happen in tests, but if there is no interface then there is nothing that
10915 // can be rate limited.
10916 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010010917 return false;
10918 }
10919 return true;
10920 }
10921
James Mattis45d81842021-01-10 14:24:24 -080010922 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080010923 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
10924 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080010925 }
10926
10927 /**
10928 * Used by automotive devices to set the network preferences used to direct traffic at an
10929 * application level as per the given OemNetworkPreferences. An example use-case would be an
10930 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
10931 * vehicle via a particular network.
10932 *
10933 * Calling this will overwrite the existing preference.
10934 *
James Mattisda32cfe2021-01-26 16:23:52 -080010935 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090010936 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080010937 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080010938 */
James Mattis47db0582021-01-01 14:13:35 -080010939 @Override
James Mattis45d81842021-01-10 14:24:24 -080010940 public void setOemNetworkPreference(
10941 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010942 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080010943
James Mattisfa270db2021-05-31 17:11:10 -070010944 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10945 // Only bypass the permission/device checks if this is a valid test request.
10946 if (isValidTestOemNetworkPreference(preference)) {
10947 enforceManageTestNetworksPermission();
10948 } else {
10949 enforceAutomotiveDevice();
10950 enforceOemNetworkPreferencesPermission();
10951 validateOemNetworkPreferences(preference);
10952 }
James Mattis45d81842021-01-10 14:24:24 -080010953
James Mattis45d81842021-01-10 14:24:24 -080010954 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
10955 new Pair<>(preference, listener)));
10956 }
10957
James Mattisfa270db2021-05-31 17:11:10 -070010958 /**
10959 * Check the validity of an OEM network preference to be used for testing purposes.
10960 * @param preference the preference to validate
10961 * @return true if this is a valid OEM network preference test request.
10962 */
10963 private boolean isValidTestOemNetworkPreference(
10964 @NonNull final OemNetworkPreferences preference) {
10965 // Allow for clearing of an existing OemNetworkPreference used for testing.
10966 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
10967 // changes after this check is complete. This is an unlikely scenario as calling of this API
10968 // is controlled by the OEM therefore the added complexity is not worth adding given those
10969 // circumstances. That said, it is an edge case to be aware of hence this comment.
10970 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
10971 && isTestOemNetworkPreference(mOemNetworkPreferences);
10972 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
10973 }
10974
10975 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
10976 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
10977 return prefMap.size() == 1
10978 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
10979 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
10980 }
10981
James Mattis45d81842021-01-10 14:24:24 -080010982 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
10983 for (@OemNetworkPreferences.OemNetworkPreference final int pref
10984 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070010985 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
10986 throw new IllegalArgumentException(
10987 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
10988 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080010989 }
10990 }
10991 }
10992
10993 private void handleSetOemNetworkPreference(
10994 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010995 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080010996 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10997 if (DBG) {
10998 log("set OEM network preferences :" + preference.toString());
10999 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011000
James Mattiscb1e0362021-04-06 17:07:42 -070011001 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000011002 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
11003 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
11004 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080011005 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080011006
11007 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011008 try {
11009 listener.onComplete();
11010 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080011011 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011012 }
James Mattis45d81842021-01-10 14:24:24 -080011013 }
11014 }
11015
paulhu74128522021-09-28 02:29:03 +000011016 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080011017 // Skip the requests which are set by other network preference. Because the uid range rules
11018 // should stay in netd.
11019 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080011020 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080011021 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080011022 }
11023
James Mattis3ce3d3c2021-02-09 18:18:28 -080011024 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
11025 ensureRunningOnConnectivityServiceThread();
11026 mDefaultNetworkRequests.addAll(nris);
11027 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
11028 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080011029 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000011030 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
11031 nrisToRegister.addAll(
11032 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
11033 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011034 }
11035
11036 /**
11037 * All current requests that are tracking the default network need to be assessed as to whether
11038 * or not the current set of per-application default requests will be changing their default
11039 * network. If so, those requests will need to be updated so that they will send callbacks for
11040 * default network changes at the appropriate time. Additionally, those requests tracking the
11041 * default that were previously updated by this flow will need to be reassessed.
11042 * @return the nris which will need to be updated.
11043 */
11044 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
11045 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
11046 // Get the distinct nris to check since for multilayer requests, it is possible to have the
11047 // same nri in the map's values for each of its NetworkRequest objects.
11048 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080011049 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011050 // Include this nri if it is currently being tracked.
11051 if (isPerAppTrackedNri(nri)) {
11052 defaultCallbackRequests.add(nri);
11053 continue;
11054 }
11055 // We only track callbacks for requests tracking the default.
11056 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
11057 continue;
11058 }
11059 // Include this nri if it will be tracked by the new per-app default requests.
11060 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011061 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080011062 if (isNriGoingToBeTracked) {
11063 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080011064 }
11065 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080011066 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080011067 }
11068
James Mattis3ce3d3c2021-02-09 18:18:28 -080011069 /**
11070 * Create nris for those network requests that are currently tracking the default network that
11071 * are being controlled by a per-application default.
11072 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
11073 * foundation when creating the nri. Important items include the calling uid's original
11074 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
11075 * requests are assumed to have already been validated as needing to be updated.
11076 * @return the Set of nris to use when registering network requests.
11077 */
11078 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
11079 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
11080 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
11081 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
11082 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011083 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011084
Chalard Jean9473c982021-07-29 20:03:04 +090011085 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080011086 if (trackingNri == mDefaultRequest) {
11087 callbackRequestsToRegister.add(new NetworkRequestInfo(
11088 callbackRequest,
11089 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
11090 continue;
11091 }
11092
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011093 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011094 callbackRequestsToRegister.add(new NetworkRequestInfo(
11095 callbackRequest,
11096 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011097 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090011098 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080011099 }
11100 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080011101 }
11102
Chalard Jean17215832021-03-01 14:06:28 +090011103 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
11104 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090011105 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011106 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090011107 }
11108 }
11109
James Mattis45d81842021-01-10 14:24:24 -080011110 /**
11111 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
11112 */
11113 @VisibleForTesting
11114 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011115 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080011116 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011117 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080011118 final SparseArray<Set<Integer>> uids =
11119 createUidsFromOemNetworkPreferences(preference);
11120 for (int i = 0; i < uids.size(); i++) {
11121 final int key = uids.keyAt(i);
11122 final Set<Integer> value = uids.valueAt(i);
11123 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
11124 // No need to add an nri without any requests.
11125 if (0 == nri.mRequests.size()) {
11126 continue;
11127 }
11128 nris.add(nri);
11129 }
11130
11131 return nris;
11132 }
11133
11134 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
11135 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070011136 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080011137 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080011138 final List<UserHandle> users =
11139 mContext.getSystemService(UserManager.class).getUserHandles(true);
11140 if (null == users || users.size() == 0) {
11141 if (VDBG || DDBG) {
11142 log("No users currently available for setting the OEM network preference.");
11143 }
James Mattisb6b6a432021-06-01 22:30:36 -070011144 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080011145 }
James Mattis45d81842021-01-10 14:24:24 -080011146 for (final Map.Entry<String, Integer> entry :
11147 preference.getNetworkPreferences().entrySet()) {
11148 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070011149 // Add the rules for all users as this policy is device wide.
11150 for (final UserHandle user : users) {
11151 try {
11152 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
11153 if (!prefToUids.contains(pref)) {
11154 prefToUids.put(pref, new ArraySet<>());
11155 }
11156 prefToUids.get(pref).add(uid);
11157 } catch (PackageManager.NameNotFoundException e) {
11158 // Although this may seem like an error scenario, it is ok that uninstalled
11159 // packages are sent on a network preference as the system will watch for
11160 // package installations associated with this network preference and update
11161 // accordingly. This is done to minimize race conditions on app install.
11162 continue;
James Mattis45d81842021-01-10 14:24:24 -080011163 }
James Mattis45d81842021-01-10 14:24:24 -080011164 }
11165 }
James Mattisb6b6a432021-06-01 22:30:36 -070011166 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080011167 }
11168
11169 private NetworkRequestInfo createNriFromOemNetworkPreferences(
11170 @OemNetworkPreferences.OemNetworkPreference final int preference,
11171 @NonNull final Set<Integer> uids) {
11172 final List<NetworkRequest> requests = new ArrayList<>();
11173 // Requests will ultimately be evaluated by order of insertion therefore it matters.
11174 switch (preference) {
11175 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
11176 requests.add(createUnmeteredNetworkRequest());
11177 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070011178 requests.add(createDefaultInternetRequestForTransport(
11179 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080011180 break;
11181 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
11182 requests.add(createUnmeteredNetworkRequest());
11183 requests.add(createOemPaidNetworkRequest());
11184 break;
11185 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
11186 requests.add(createOemPaidNetworkRequest());
11187 break;
11188 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
11189 requests.add(createOemPrivateNetworkRequest());
11190 break;
James Mattisfa270db2021-05-31 17:11:10 -070011191 case OEM_NETWORK_PREFERENCE_TEST:
11192 requests.add(createUnmeteredNetworkRequest());
11193 requests.add(createTestNetworkRequest());
11194 requests.add(createDefaultRequest());
11195 break;
11196 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
11197 requests.add(createTestNetworkRequest());
11198 break;
James Mattis45d81842021-01-10 14:24:24 -080011199 default:
11200 // This should never happen.
11201 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
11202 + " called with invalid preference of " + preference);
11203 }
11204
James Mattisfa270db2021-05-31 17:11:10 -070011205 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090011206 for (final int uid : uids) {
11207 ranges.add(new UidRange(uid, uid));
11208 }
11209 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080011210 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080011211 }
11212
11213 private NetworkRequest createUnmeteredNetworkRequest() {
11214 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11215 .addCapability(NET_CAPABILITY_NOT_METERED)
11216 .addCapability(NET_CAPABILITY_VALIDATED);
11217 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
11218 }
11219
11220 private NetworkRequest createOemPaidNetworkRequest() {
11221 // NET_CAPABILITY_OEM_PAID is a restricted capability.
11222 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11223 .addCapability(NET_CAPABILITY_OEM_PAID)
11224 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11225 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11226 }
11227
11228 private NetworkRequest createOemPrivateNetworkRequest() {
11229 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
11230 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11231 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
11232 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11233 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11234 }
11235
11236 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070011237 final NetworkCapabilities netcap = new NetworkCapabilities();
11238 netcap.addCapability(NET_CAPABILITY_INTERNET);
11239 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
11240 return netcap;
11241 }
11242
11243 private NetworkRequest createTestNetworkRequest() {
11244 final NetworkCapabilities netcap = new NetworkCapabilities();
11245 netcap.clearAll();
11246 netcap.addTransportType(TRANSPORT_TEST);
11247 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080011248 }
James Mattis47db0582021-01-01 14:13:35 -080011249 }
markchien738ad912021-12-09 18:15:45 +080011250
11251 @Override
11252 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
11253 enforceNetworkStackOrSettingsPermission();
11254
11255 try {
11256 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011257 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011258 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011259 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011260 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011261 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011262 throw new IllegalStateException(e);
11263 }
11264 }
11265
11266 @Override
11267 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
11268 enforceNetworkStackOrSettingsPermission();
11269
11270 try {
11271 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011272 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011273 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011274 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011275 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011276 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011277 throw new IllegalStateException(e);
11278 }
11279 }
markchiene1561fa2021-12-09 22:00:56 +080011280
11281 @Override
markchien3c04e662022-03-22 16:29:56 +080011282 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080011283 enforceNetworkStackOrSettingsPermission();
11284
markchien3c04e662022-03-22 16:29:56 +080011285 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
11286 int firewallRule = getFirewallRuleType(chain, rule);
11287
11288 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
11289 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
11290 }
11291
markchiene1561fa2021-12-09 22:00:56 +080011292 try {
markchien3c04e662022-03-22 16:29:56 +080011293 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011294 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080011295 throw new IllegalStateException(e);
11296 }
11297 }
markchien98a6f952022-01-13 23:43:53 +080011298
markchien3c04e662022-03-22 16:29:56 +080011299 private int getFirewallRuleType(int chain, int rule) {
11300 final int defaultRule;
11301 switch (chain) {
11302 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000011303 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
11304 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000011305 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080011306 defaultRule = FIREWALL_RULE_ALLOW;
11307 break;
11308 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
11309 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
11310 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
11311 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
11312 defaultRule = FIREWALL_RULE_DENY;
11313 break;
11314 default:
11315 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
11316 }
11317 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
11318
11319 return rule;
11320 }
11321
markchien98a6f952022-01-13 23:43:53 +080011322 @Override
11323 public void setFirewallChainEnabled(final int chain, final boolean enable) {
11324 enforceNetworkStackOrSettingsPermission();
11325
11326 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011327 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011328 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080011329 throw new IllegalStateException(e);
11330 }
11331 }
11332
markchien00a0bed2022-01-13 23:46:13 +080011333 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011334 public boolean getFirewallChainEnabled(final int chain) {
11335 enforceNetworkStackOrSettingsPermission();
11336
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000011337 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011338 }
11339
11340 @Override
markchien00a0bed2022-01-13 23:46:13 +080011341 public void replaceFirewallChain(final int chain, final int[] uids) {
11342 enforceNetworkStackOrSettingsPermission();
11343
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000011344 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080011345 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070011346}