blob: 0035aa03ee46366272d53c5c1441a3ea8326b013 [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 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003043 }
3044
The Android Open Source Project28527d22009-03-03 19:31:44 -08003045 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003046 * Start listening for default data network activity state changes.
3047 */
3048 @Override
3049 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003050 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003051 }
3052
3053 /**
3054 * Stop listening for default data network activity state changes.
3055 */
3056 @Override
3057 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003058 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003059 }
3060
3061 /**
3062 * Check whether the default network radio is currently active.
3063 */
3064 @Override
3065 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003066 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003067 }
3068
3069 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003070 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003071 * and set it on it's iface.
3072 */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003073 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
3074 final String iface = newLp.getInterfaceName();
3075 final int mtu = newLp.getMtu();
Pierre Imai07c53a32016-02-08 16:01:40 +09003076 if (oldLp == null && mtu == 0) {
3077 // Silently ignore unset MTU value.
3078 return;
3079 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003080 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
3081 if (VDBG) log("identical MTU - not setting");
3082 return;
3083 }
paulhucbbc3db2019-03-08 16:35:20 +08003084 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003085 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003086 return;
3087 }
sy.yun4aa73922013-09-02 05:24:09 +09003088
w19976e714f1d2014-08-05 15:18:11 -07003089 // Cannot set MTU without interface name
3090 if (TextUtils.isEmpty(iface)) {
3091 loge("Setting MTU size with null iface.");
3092 return;
3093 }
3094
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003095 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003096 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003097 mNetd.interfaceSetMtu(iface, mtu);
3098 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003099 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003100 }
3101 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003102
Chenbo Feng15416292018-11-08 17:36:21 -08003103 @VisibleForTesting
3104 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003105
lucaslin821c9782018-11-28 19:27:52 +08003106 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003107 String[] values = null;
3108 if (tcpBufferSizes != null) {
3109 values = tcpBufferSizes.split(",");
3110 }
3111
3112 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003113 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003114 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3115 values = tcpBufferSizes.split(",");
3116 }
3117
3118 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3119
3120 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003121 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003122
Chenbo Feng15416292018-11-08 17:36:21 -08003123 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3124 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3125 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003126 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003127 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003128 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003129 }
3130 }
3131
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003132 @Override
3133 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003134 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003135 NETWORK_RESTORE_DELAY_PROP_NAME);
3136 if(restoreDefaultNetworkDelayStr != null &&
3137 restoreDefaultNetworkDelayStr.length() != 0) {
3138 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003139 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003140 } catch (NumberFormatException e) {
3141 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003142 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003143 // if the system property isn't set, use the value for the apn type
3144 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3145
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003146 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3147 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003148 }
3149 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003150 }
3151
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003152 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003153 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003154 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003155 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003156 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003157 // Start gathering diagnostic information.
3158 netDiags.add(new NetworkDiagnostics(
3159 nai.network,
3160 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003161 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003162 DIAG_TIME_MS));
3163 }
3164
3165 for (NetworkDiagnostics netDiag : netDiags) {
3166 pw.println();
3167 netDiag.waitForMeasurements();
3168 netDiag.dump(pw);
3169 }
3170 }
3171
The Android Open Source Project28527d22009-03-03 19:31:44 -08003172 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003173 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3174 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003175 if (!checkDumpPermission(mContext, TAG, writer)) return;
3176
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003177 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003178 }
3179
lucaslin99473f62020-12-10 15:10:54 +08003180 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3181 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3182 != PackageManager.PERMISSION_GRANTED) {
3183 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003184 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003185 + " due to missing android.permission.DUMP permission");
3186 return false;
3187 } else {
3188 return true;
3189 }
3190 }
3191
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003192 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003193 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003194
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003195 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003196 dumpNetworkDiagnostics(pw);
3197 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003198 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003199 dumpNetworks(pw);
3200 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003201 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003202 dumpNetworkRequests(pw);
3203 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003204 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3205 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3206 dumpTrafficController(pw, fd, verbose);
3207 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003208 }
Erik Kline9647f382015-06-05 17:47:34 +09003209
Junyu Lai0da479b2022-04-20 15:06:29 +08003210 pw.println("NetworkProviders for:");
3211 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003212 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003213 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003214 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003215 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003216 pw.println();
3217
Chalard Jean5b409c72021-02-04 13:12:59 +09003218 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003219 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003220 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003221 pw.println("none");
3222 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003223 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003224 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003225 pw.println();
3226
James Mattis8b298a02021-06-01 22:34:04 -07003227 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003228 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003229 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003230 pw.decreaseIndent();
3231 pw.println();
3232
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003233 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003234 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003235 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003236 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003237 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003238
junyulaif2c67e42018-08-07 19:50:45 +08003239 pw.println("Status for known UIDs:");
3240 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003241 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003242 for (int i = 0; i < size; i++) {
3243 // Don't crash if the array is modified while dumping in bugreports.
3244 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003245 final int uid = mUidBlockedReasons.keyAt(i);
3246 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3247 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003248 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003249 } catch (ArrayIndexOutOfBoundsException e) {
3250 pw.println(" ArrayIndexOutOfBoundsException");
3251 } catch (ConcurrentModificationException e) {
3252 pw.println(" ConcurrentModificationException");
3253 }
3254 }
3255 pw.println();
3256 pw.decreaseIndent();
3257
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003258 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003259 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003260 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003261 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003262 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003263
Junyu Lai0da479b2022-04-20 15:06:29 +08003264 pw.println("Network Offers:");
3265 pw.increaseIndent();
3266 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3267 pw.println(offerInfo.offer);
3268 }
3269 pw.decreaseIndent();
3270 pw.println();
3271
Robert Greenwalt94e22142014-07-30 16:31:24 -07003272 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003273
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003274 pw.println();
markchien5e866652019-09-30 14:40:57 +08003275 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003276
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003277 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003278 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003279
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003280 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003281
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003282 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003283 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003284 pw.println("mNetworkRequestInfoLogs (most recent first):");
3285 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003286 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003287 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003288
3289 pw.println();
3290 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3291 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003292 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003293 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003294
3295 pw.println();
3296 pw.println("NetTransition WakeLock activity (most recent first):");
3297 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003298 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3299 pw.println("total releases: " + mTotalWakelockReleases);
3300 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3301 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3302 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3303 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3304 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3305 }
James Mattiscb1e0362021-04-06 17:07:42 -07003306 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003307
3308 pw.println();
3309 pw.println("bandwidth update requests (by uid):");
3310 pw.increaseIndent();
3311 synchronized (mBandwidthRequests) {
3312 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3313 pw.println("[" + mBandwidthRequests.keyAt(i)
3314 + "]: " + mBandwidthRequests.valueAt(i));
3315 }
3316 }
3317 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003318 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003319
James Mattiscb1e0362021-04-06 17:07:42 -07003320 pw.println();
3321 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3322 pw.increaseIndent();
3323 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003324 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003325 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003326
3327 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003328
3329 pw.println();
3330 pw.println("Permission Monitor:");
3331 pw.increaseIndent();
3332 mPermissionMonitor.dump(pw);
3333 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003334
3335 pw.println();
3336 pw.println("Legacy network activity:");
3337 pw.increaseIndent();
3338 mNetworkActivityTracker.dump(pw);
3339 pw.decreaseIndent();
Ken Chendaf5cb62022-07-04 11:09:28 +08003340
3341 // pre-T is logged by netd.
3342 if (SdkLevel.isAtLeastT()) {
3343 pw.println();
3344 pw.println("BPF programs & maps:");
3345 pw.increaseIndent();
3346 // Flush is required. Otherwise, the traces in fd can interleave with traces in pw.
3347 pw.flush();
3348 dumpTrafficController(pw, fd, /*verbose=*/ true);
3349 pw.decreaseIndent();
3350 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003351 }
3352
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003353 private void dumpNetworks(IndentingPrintWriter pw) {
3354 for (NetworkAgentInfo nai : networksSortedById()) {
3355 pw.println(nai.toString());
3356 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003357 pw.println("Nat464Xlat:");
3358 pw.increaseIndent();
3359 nai.dumpNat464Xlat(pw);
3360 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003361 pw.println(String.format(
3362 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3363 nai.numForegroundNetworkRequests(),
3364 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3365 nai.numBackgroundNetworkRequests(),
3366 nai.numNetworkRequests()));
3367 pw.increaseIndent();
3368 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3369 pw.println(nai.requestAt(i).toString());
3370 }
3371 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003372 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003373 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003374 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003375 pw.decreaseIndent();
3376 pw.decreaseIndent();
3377 }
3378 }
3379
James Mattis8b298a02021-06-01 22:34:04 -07003380 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3381 if (!mProfileNetworkPreferences.isEmpty()) {
3382 pw.println("Profile preferences:");
3383 pw.increaseIndent();
3384 pw.println(mProfileNetworkPreferences.preferences);
3385 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003386 }
James Mattis8b298a02021-06-01 22:34:04 -07003387 if (!mOemNetworkPreferences.isEmpty()) {
3388 pw.println("OEM preferences:");
3389 pw.increaseIndent();
3390 pw.println(mOemNetworkPreferences);
3391 pw.decreaseIndent();
3392 }
3393 if (!mMobileDataPreferredUids.isEmpty()) {
3394 pw.println("Mobile data preferred UIDs:");
3395 pw.increaseIndent();
3396 pw.println(mMobileDataPreferredUids);
3397 pw.decreaseIndent();
3398 }
James Mattis45d81842021-01-10 14:24:24 -08003399
James Mattis8b298a02021-06-01 22:34:04 -07003400 pw.println("Default requests:");
3401 pw.increaseIndent();
3402 dumpPerAppDefaultRequests(pw);
3403 pw.decreaseIndent();
3404 }
3405
3406 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003407 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3408 if (mDefaultRequest == defaultRequest) {
3409 continue;
3410 }
3411
James Mattis8b298a02021-06-01 22:34:04 -07003412 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3413 final String networkOutput;
3414 if (null == satisfier) {
3415 networkOutput = "null";
3416 } else if (mNoServiceNetwork.equals(satisfier)) {
3417 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003418 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003419 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003420 }
James Mattis8b298a02021-06-01 22:34:04 -07003421 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3422 ? "" : " asUid: " + defaultRequest.mAsUid;
3423 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3424 + defaultRequest.mPid + asUidString + "]";
3425 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3426 + " Preference order: " + defaultRequest.mPreferenceOrder
3427 + " Tracked UIDs: " + defaultRequest.getUids();
3428 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003429 }
3430 }
3431
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003432 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003433 NetworkRequestInfo[] infos = null;
3434 while (infos == null) {
3435 try {
3436 infos = requestsSortedById();
3437 } catch (ConcurrentModificationException e) {
3438 // mNetworkRequests should only be accessed from handler thread, except dump().
3439 // As dump() is never called in normal usage, it would be needlessly expensive
3440 // to lock the collection only for its benefit. Instead, retry getting the
3441 // requests if ConcurrentModificationException is thrown during dump().
3442 }
3443 }
3444 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003445 pw.println(nri.toString());
3446 }
3447 }
3448
Ken Chene6d511f2022-01-25 11:10:42 +08003449 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
3450 boolean verbose) {
3451 try {
3452 mBpfNetMaps.dump(fd, verbose);
3453 } catch (ServiceSpecificException e) {
3454 pw.println(e.getMessage());
3455 } catch (IOException e) {
3456 loge("Dump BPF maps failed, " + e);
3457 }
3458 }
3459
Chalard Jean524f0b12021-10-25 21:11:56 +09003460 private void dumpAllRequestInfoLogsToLogcat() {
3461 try (PrintWriter logPw = new PrintWriter(new Writer() {
3462 @Override
3463 public void write(final char[] cbuf, final int off, final int len) {
3464 // This method is called with 0-length and 1-length arrays for empty strings
3465 // or strings containing only the DEL character.
3466 if (len <= 1) return;
3467 Log.e(TAG, new String(cbuf, off, len));
3468 }
3469 @Override public void flush() {}
3470 @Override public void close() {}
3471 })) {
3472 mNetworkRequestInfoLogs.dump(logPw);
3473 }
3474 }
3475
Hugo Benichia480ba52018-09-03 08:19:02 +09003476 /**
3477 * Return an array of all current NetworkAgentInfos sorted by network id.
3478 */
3479 private NetworkAgentInfo[] networksSortedById() {
3480 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003481 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003482 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003483 return networks;
3484 }
3485
3486 /**
3487 * Return an array of all current NetworkRequest sorted by request id.
3488 */
James Mattis258ea3c2020-11-15 15:04:40 -08003489 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003490 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003491 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003492 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003493 // Sort the array based off the NRI containing the min requestId in its requests.
3494 Arrays.sort(requests,
3495 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3496 Comparator.comparingInt(req -> req.requestId)).requestId
3497 )
3498 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003499 return requests;
3500 }
3501
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003502 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003503 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003504 if (officialNai != null && officialNai.equals(nai)) return true;
3505 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003506 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003507 " - " + nai);
3508 }
3509 return false;
3510 }
3511
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003512 private boolean isDisconnectRequest(Message msg) {
3513 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
3514 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
3515 return info.getState() == NetworkInfo.State.DISCONNECTED;
3516 }
3517
Robert Greenwalt2034b912009-08-12 16:08:25 -07003518 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003519 private class NetworkStateTrackerHandler extends Handler {
3520 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003521 super(looper);
3522 }
3523
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003524 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003525 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3526 final NetworkAgentInfo nai = arg.first;
3527 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003528 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003529 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003530 }
3531 return;
3532 }
3533
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003534 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09003535 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003536 return;
3537 }
3538
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003539 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003540 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09003541 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
3542 final NetworkCapabilities sanitized =
3543 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09003544 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003545 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003546 break;
3547 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003548 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003549 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003550 processLinkPropertiesFromAgent(nai, newLp);
3551 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003552 break;
3553 }
3554 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003555 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003556 updateNetworkInfo(nai, info);
3557 break;
3558 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003559 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003560 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003561 break;
3562 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003563 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09003564 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003565 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003566 // Note that if the NAI had been connected, this would affect the
3567 // score, and therefore would require re-mixing the score and performing
3568 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003569 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003570 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3571 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003572 // Mark the network as temporarily accepting partial connectivity so that it
3573 // will be validated (and possibly become default) even if it only provides
3574 // partial internet access. Note that if user connects to partial connectivity
3575 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3576 // out of wifi coverage) and if the same wifi is available again, the device
3577 // will auto connect to this wifi even though the wifi has "no internet".
3578 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003579 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003580 break;
3581 }
junyulai011b1f12019-01-03 18:50:15 +08003582 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003583 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003584 break;
3585 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003586 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003587 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003588 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003589
3590 if (isLegacyLockdownNai(nai)
3591 && (underlying == null || underlying.size() != 1)) {
3592 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3593 + " must have exactly one underlying network: " + underlying);
3594 }
3595
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003596 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3597 nai.declaredUnderlyingNetworks = (underlying != null)
3598 ? underlying.toArray(new Network[0]) : null;
3599
3600 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3601 if (DBG) {
3602 log(nai.toShortString() + " changed underlying networks to "
3603 + Arrays.toString(nai.declaredUnderlyingNetworks));
3604 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003605 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003606 notifyIfacesChangedForNetworkStats();
3607 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003608 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003609 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003610 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3611 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3612 nai.teardownDelayMs = msg.arg1;
3613 } else {
3614 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3615 }
Chalard Jean550b5212021-03-05 23:07:53 +09003616 break;
3617 }
3618 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3619 nai.setLingerDuration((int) arg.second);
3620 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003621 }
Tyler Wear72388212021-09-09 14:49:02 -07003622 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3623 DscpPolicy policy = (DscpPolicy) arg.second;
3624 if (mDscpPolicyTracker != null) {
3625 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3626 }
3627 break;
3628 }
3629 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3630 if (mDscpPolicyTracker != null) {
3631 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3632 }
3633 break;
3634 }
3635 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3636 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08003637 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07003638 }
3639 break;
3640 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09003641 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003642 // If nai is not yet created, or is already destroyed, ignore.
3643 if (!shouldDestroyNativeNetwork(nai)) break;
3644
3645 final int timeoutMs = (int) arg.second;
3646 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3647 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
3648 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
3649 }
3650
3651 // Marking a network awaiting replacement is used to ensure that any requests
3652 // satisfied by the network do not switch to another network until a
3653 // replacement is available or the wait for a replacement times out.
3654 // If the network is inactive (i.e., nascent or lingering), then there are no
3655 // such requests, and there is no point keeping it. Just tear it down.
3656 // Note that setLingerDuration(0) cannot be used to do this because the network
3657 // could be nascent.
3658 nai.clearInactivityState();
3659 if (unneeded(nai, UnneededFor.TEARDOWN)) {
3660 Log.d(TAG, nai.toShortString()
3661 + " marked awaiting replacement is unneeded, tearing down instead");
3662 teardownUnneededNetwork(nai);
3663 break;
3664 }
3665
3666 Log.d(TAG, "Marking " + nai.toShortString()
3667 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
3668 destroyNativeNetwork(nai);
3669
3670 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
3671 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
3672 // consider the fact that the network could already have disconnected or been
3673 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
3674 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
3675 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
3676 mKeepaliveTracker.handleStopAllKeepalives(nai,
3677 SocketKeepalive.ERROR_INVALID_NETWORK);
3678
3679 nai.updateScoreForNetworkAgentUpdate();
3680 // This rematch is almost certainly not going to result in any changes, because
3681 // the destroyed flag is only just above the "current satisfier wins"
3682 // tie-breaker. But technically anything that affects scoring should rematch.
3683 rematchAllNetworksAndRequests();
3684 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
3685 break;
3686 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003687 }
3688 }
3689
3690 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003691 final int netId = msg.arg2;
3692 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003693 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09003694 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003695 switch (msg.what) {
3696 default:
3697 return false;
lucasline117e2e2019-10-22 18:27:33 +08003698 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08003699 if (nai == null) {
3700 break;
3701 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003702 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
3703 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08003704 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003705 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08003706 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003707 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08003708 if (probePrivateDnsCompleted) {
3709 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3710 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003711 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003712 }
3713 // Only show the notification when the private DNS is broken and the
3714 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003715 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003716 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3717 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003718 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003719 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3720 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3721 // private DNS is broken, it means this network is being reevaluated.
3722 // Either probing private DNS is not necessary any more or it hasn't been
3723 // done yet. In either case, the networkCapabilities should be updated to
3724 // reflect the new status.
3725 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003726 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003727 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003728 }
3729 break;
3730 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003731 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003732 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3733
Erik Kline31b4a9e2018-01-11 21:07:29 +09003734 if (nai == null) break;
3735
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003736 handleNetworkTested(nai, results.mTestResult,
3737 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003738 break;
3739 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003740 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09003741 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07003742 // If captive portal status has changed, update capabilities or disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09003743 if (nai != null && (visible != nai.captivePortalDetected())) {
3744 nai.setCaptivePortalDetected(visible);
3745 if (visible && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3746 == getCaptivePortalMode()) {
Chalard Jean49707572019-12-10 21:07:02 +09003747 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003748 nai.onPreventAutomaticReconnect();
Calvin Ondada1452016-10-11 15:10:46 -07003749 teardownUnneededNetwork(nai);
3750 break;
3751 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003752 updateCapabilitiesForNetwork(nai);
Paul Jensen53f08952015-06-16 14:27:36 -04003753 }
3754 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003755 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003756 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003757 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3758 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003759 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003760 if (nai == null) {
3761 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3762 break;
3763 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003764 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003765 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003766 (PendingIntent) msg.obj,
3767 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003768 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003769 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003770 break;
3771 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003772 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09003773 if (nai == null) break;
3774
Erik Kline9a62f012018-03-21 07:18:33 -07003775 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003776 break;
3777 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003778 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003779 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003780 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003781 break;
3782 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003783 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003784 return true;
3785 }
3786
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003787 private void handleNetworkTested(
3788 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
he_won.hwang881307a2022-03-15 21:23:52 +09003789 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3790 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
3791 // Assume the validation failure is due to a temporary failure after roaming
3792 // and ignore it. NetworkMonitor will continue to retry validation. If it
3793 // continues to fail after the block timeout expires, the network will be
3794 // marked unvalidated. If it succeeds, then validation state will not change.
3795 return;
3796 }
3797
Chalard Jean254bd162022-08-25 13:04:51 +09003798 final boolean wasValidated = nai.isValidated();
3799 final boolean wasPartial = nai.partialConnectivity();
3800 nai.setPartialConnectivity((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3801 final boolean partialConnectivityChanged = (wasPartial != nai.partialConnectivity());
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003802
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003803 if (DBG) {
3804 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3805 ? " with redirect to " + redirectUrl
3806 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003807 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003808 }
Chalard Jean254bd162022-08-25 13:04:51 +09003809 if (valid != nai.isValidated()) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003810 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09003811 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003812 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003813 if (valid) {
3814 handleFreshlyValidatedNetwork(nai);
3815 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3816 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003817 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003818 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003819 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003820 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003821 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003822 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003823 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003824 NotificationType.PRIVATE_DNS_BROKEN);
3825 // If network becomes valid, the hasShownBroken should be reset for
3826 // that network so that the notification will be fired when the private
3827 // DNS is broken again.
3828 nai.networkAgentConfig.hasShownBroken = false;
3829 }
3830 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003831 updateCapabilitiesForNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003832 }
3833 updateInetCondition(nai);
3834 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003835 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003836 nai.onValidationStatusChanged(
3837 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3838 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003839
3840 // If NetworkMonitor detects partial connectivity before
3841 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3842 // immediately. Re-notify partial connectivity silently if no internet
3843 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09003844 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003845 // Remove delayed message if there is a pending message.
3846 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3847 handlePromptUnvalidated(nai.network);
3848 }
3849
Chalard Jean254bd162022-08-25 13:04:51 +09003850 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003851 handleNetworkUnvalidated(nai);
3852 }
3853 }
3854
Calvin Ondada1452016-10-11 15:10:46 -07003855 private int getCaptivePortalMode() {
3856 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08003857 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3858 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07003859 }
3860
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003861 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3862 switch (msg.what) {
3863 default:
3864 return false;
3865 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3866 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3867 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3868 handleLingerComplete(nai);
3869 }
3870 break;
3871 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003872 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3873 handleNetworkAgentRegistered(msg);
3874 break;
3875 }
3876 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3877 handleNetworkAgentDisconnected(msg);
3878 break;
3879 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003880 }
3881 return true;
3882 }
3883
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003884 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09003885 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08003886 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09003887 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003888 maybeHandleNetworkAgentMessage(msg);
3889 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003890 }
3891 }
3892
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003893 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09003894 private final int mNetId;
3895 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003896
3897 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003898 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003899 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003900 }
3901
3902 @Override
3903 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3904 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09003905 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003906 }
3907
3908 @Override
3909 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003910 // Legacy version of notifyNetworkTestedWithExtras.
3911 // Would only be called if the system has a NetworkStack module older than the
3912 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08003913 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003914 }
3915
3916 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003917 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09003918 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3919 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003920 final Message msg = mTrackerHandler.obtainMessage(
3921 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003922 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003923 new NetworkTestedResults(
3924 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003925 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003926
3927 // Invoke ConnectivityReport generation for this Network test event.
3928 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3929 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003930
Cody Kestingf1120be2020-08-03 18:01:40 -07003931 // NetworkMonitor reports the network validation result as a bitmask while
3932 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
3933 // logical value for ConnectivityDiagnostics.
3934 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
3935 p.result);
3936
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003937 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07003938 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003939 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3940 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3941
Aaron Huang959d3642021-01-21 15:47:41 +08003942 ConnectivityReportEvent reportEvent =
3943 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3944 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09003945 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003946 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003947 }
3948
3949 @Override
3950 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3951 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3952 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09003953 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003954 }
3955
3956 @Override
lucasline117e2e2019-10-22 18:27:33 +08003957 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3958 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3959 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003960 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08003961 }
3962
3963 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003964 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3965 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3966 EVENT_CAPPORT_DATA_CHANGED,
3967 0, mNetId, data));
3968 }
3969
3970 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003971 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003972 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003973 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003974
3975 final PendingIntent pendingIntent;
3976 // Only the system server can register notifications with package "android"
3977 final long token = Binder.clearCallingIdentity();
3978 try {
paulhu7746e4e2020-06-09 19:07:03 +08003979 pendingIntent = PendingIntent.getBroadcast(
3980 mContext,
3981 0 /* requestCode */,
3982 intent,
3983 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003984 } finally {
3985 Binder.restoreCallingIdentity(token);
3986 }
3987 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3988 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09003989 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003990 }
3991
3992 @Override
3993 public void hideProvisioningNotification() {
3994 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09003995 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003996 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003997
3998 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003999 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004000 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004001 }
4002
4003 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004004 public int getInterfaceVersion() {
4005 return this.VERSION;
4006 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004007
4008 @Override
4009 public String getInterfaceHash() {
4010 return this.HASH;
4011 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004012 }
4013
Cody Kestingf1120be2020-08-03 18:01:40 -07004014 /**
4015 * Converts the given NetworkMonitor-specific validation result bitmask to a
4016 * ConnectivityDiagnostics-specific validation result int.
4017 */
4018 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4019 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4020 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4021 }
4022 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4023 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4024 }
4025 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4026 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4027 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4028 }
4029
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004030 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004031 log("Data stall detected with methods: " + p.detectionMethod);
4032
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004033 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004034 int detectionMethod = 0;
4035 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4036 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4037 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4038 }
4039 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4040 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4041 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4042 p.tcpMetricsCollectionPeriodMillis);
4043 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004044 }
4045
Cody Kestingf53a0752020-04-15 12:33:28 -07004046 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004047 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004048 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004049
4050 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4051 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4052 // the cost of going through two handlers.
4053 mConnectivityDiagnosticsHandler.sendMessage(msg);
4054 }
4055
Cody Kestingb37958e2020-05-15 10:36:01 -07004056 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4057 return (p.detectionMethod & detectionMethod) != 0;
4058 }
4059
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004060 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4061 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004062 }
4063
Erik Klinea73af002018-06-26 18:53:43 +09004064 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4065 if (nai == null) return;
4066 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4067 // in order to restart a validation pass from within netd.
4068 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4069 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004070 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004071 }
4072 }
4073
Erik Kline31b4a9e2018-01-11 21:07:29 +09004074 private void handlePrivateDnsSettingsChanged() {
4075 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4076
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004077 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004078 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004079 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004080 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4081 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004082 }
4083 }
4084
Erik Kline9a62f012018-03-21 07:18:33 -07004085 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4086 // Private DNS only ever applies to networks that might provide
4087 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004088 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004089
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004090 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004091 // schedule DNS resolutions. If a DNS resolution is required the
4092 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004093 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004094
4095 // With Private DNS bypass support, we can proceed to update the
4096 // Private DNS config immediately, even if we're in strict mode
4097 // and have not yet resolved the provider name into a set of IPs.
4098 updatePrivateDns(nai, cfg);
4099 }
4100
4101 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4102 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004103 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004104 }
4105
dalyk1720e542018-03-05 12:42:22 -05004106 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4107 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4108 if (nai == null) {
4109 return;
4110 }
4111 mDnsManager.updatePrivateDnsValidation(update);
4112 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4113 }
4114
paulhu7c0a2e62021-01-08 00:51:49 +08004115 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004116 int prefixLength) {
4117 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4118 if (nai == null) return;
4119
paulhu7c0a2e62021-01-08 00:51:49 +08004120 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4121 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004122
4123 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004124 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004125 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004126 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004127 prefixLength);
4128 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004129 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004130 return;
4131 }
4132 }
4133
Lorenzo Colittid523d142020-04-01 20:16:30 +09004134 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004135 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4136 }
4137
Hai Shalome58bdc62021-01-11 18:45:34 -08004138 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004139 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004140 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004141 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4142 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4143 }
4144
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004145 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004146 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004147 * @param nai the agent info to update
4148 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004149 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004150 */
junyulai2b6f0c22021-02-03 20:15:30 +08004151 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4152 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4153 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004154 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004155 // one lingered request, set inactive.
4156 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004157 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004158 if (DBG) log("Unsetting inactive " + nai.toShortString());
4159 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004160 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004161 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004162 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004163 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4164 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004165 }
junyulai2b6f0c22021-02-03 20:15:30 +08004166 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004167 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004168 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004169 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004170 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004171 }
4172
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004173 private void handleNetworkAgentRegistered(Message msg) {
4174 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4175 if (!mNetworkAgentInfos.contains(nai)) {
4176 return;
4177 }
4178
4179 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4180 if (VDBG) log("NetworkAgent registered");
4181 } else {
4182 loge("Error connecting NetworkAgent");
4183 mNetworkAgentInfos.remove(nai);
4184 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004185 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004186 synchronized (mNetworkForNetId) {
4187 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004188 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004189 mNetIdManager.releaseNetId(nai.network.getNetId());
4190 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004191 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004192 }
4193 }
4194 }
Paul Jensend5f53392014-11-25 15:26:53 -05004195
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004196 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004197 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004198 }
4199
he_won.hwang881307a2022-03-15 21:23:52 +09004200 private boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004201 // T+ devices should use unregisterAfterReplacement.
he_won.hwang881307a2022-03-15 21:23:52 +09004202 if (SdkLevel.isAtLeastT()) return false;
4203 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4204 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
4205 if (blockTimeOut <= MAX_VALIDATION_FAILURE_BLOCKING_TIME_MS
4206 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004207 final long currentTimeMs = SystemClock.elapsedRealtime();
4208 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004209 if (timeSinceLastRoam <= blockTimeOut) {
4210 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4211 return true;
4212 }
4213 }
4214 return false;
4215 }
4216
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004217 private void handleNetworkAgentDisconnected(Message msg) {
4218 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004219 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004220 }
4221
Chalard Jeand9fffc32018-05-11 20:19:20 +09004222 // Destroys a network, remove references to it from the internal state managed by
4223 // ConnectivityService, free its interfaces and clean up.
4224 // Must be called on the Handler thread.
4225 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004226 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004227
4228 if (!mNetworkAgentInfos.contains(nai)) return;
4229
Chalard Jeand9fffc32018-05-11 20:19:20 +09004230 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004231 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004232 }
lucaslinb25c9a62019-02-12 15:30:13 +08004233 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004234 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004235 // A network agent has disconnected.
4236 // TODO - if we move the logic to the network agent (have them disconnect
4237 // because they lost all their requests or because their score isn't good)
4238 // then they would disconnect organically, report their new state and then
4239 // disconnect the channel.
4240 if (nai.networkInfo.isConnected()) {
4241 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4242 null, null);
4243 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004244 final boolean wasDefault = isDefaultNetwork(nai);
4245 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004246 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004247 }
4248 notifyIfacesChangedForNetworkStats();
4249 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4250 // by other networks that are already connected. Perhaps that can be done by
4251 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4252 // of rematchAllNetworksAndRequests
4253 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004254 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004255
4256 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004257 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4258 // Disable wakeup packet monitoring for each interface.
4259 wakeupModifyInterface(iface, nai.networkCapabilities, false);
4260 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004261 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004262 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004263 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004264 synchronized (mNetworkForNetId) {
4265 // Remove the NetworkAgent, but don't mark the netId as
4266 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004267 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004268 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004269 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004270 // Remove all previously satisfied requests.
4271 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004272 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004273 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004274 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004275 if (currentNetwork != null
4276 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004277 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004278 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4279 // rematch not to keep disconnected agents instead of setting it here ; this
4280 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004281 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004282 for (final NetworkOfferInfo noi : mNetworkOffers) {
4283 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004284 }
James Mattise3ef1912020-12-20 11:09:58 -08004285
Chalard Jean5b409c72021-02-04 13:12:59 +09004286 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004287 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004288 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004289 // network, because while incorrect this is the closest to the old (also
4290 // incorrect) behavior.
4291 mNetworkActivityTracker.updateDataActivityTracking(
4292 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004293 ensureNetworkTransitionWakelock(nai.toShortString());
4294 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004295 }
4296 }
junyulai2b6f0c22021-02-03 20:15:30 +08004297 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004298 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004299 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004300 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004301 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004302 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004303 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004304
4305 // Immediate teardown.
4306 if (nai.teardownDelayMs == 0) {
4307 destroyNetwork(nai);
4308 return;
4309 }
4310
4311 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09004312 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304313 try {
4314 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4315 } catch (RemoteException e) {
4316 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4317 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004318 }
4319 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4320 }
4321
4322 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004323 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004324 // Tell netd to clean up the configuration for this network
4325 // (routing rules, DNS, etc).
4326 // This may be slow as it requires a lot of netd shelling out to ip and
4327 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004328 // after we've rematched networks with requests (which might change the default
4329 // network or service a new request from an app), so network traffic isn't interrupted
4330 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004331 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004332 }
Chalard Jean254bd162022-08-25 13:04:51 +09004333 if (!nai.isCreated() && !SdkLevel.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004334 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
4335 // This can never run if the code above runs because shouldDestroyNativeNetwork is
4336 // false if the network was never created.
4337 // TODO: delete when S is no longer supported.
4338 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004339 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004340 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004341 }
4342
Ken Chen6df7a902021-04-09 15:08:42 +08004343 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004344 try {
4345 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004346 final NativeNetworkConfig config;
4347 if (nai.isVPN()) {
4348 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004349 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004350 return false;
4351 }
4352 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4353 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004354 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08004355 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004356 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004357 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004358 getNetworkPermission(nai.networkCapabilities),
4359 false /* secure */,
4360 VpnManager.TYPE_VPN_NONE,
4361 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08004362 }
Ken Chen6df7a902021-04-09 15:08:42 +08004363 mNetd.networkCreate(config);
4364 mDnsResolver.createNetworkCache(nai.network.getNetId());
4365 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4366 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004367 return true;
4368 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004369 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004370 return false;
4371 }
4372 }
4373
Ken Chen6df7a902021-04-09 15:08:42 +08004374 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004375 if (mDscpPolicyTracker != null) {
4376 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
4377 }
Luke Huangfdd11f82019-04-09 18:41:49 +08004378 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004379 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004380 } catch (RemoteException | ServiceSpecificException e) {
4381 loge("Exception destroying network(networkDestroy): " + e);
4382 }
4383 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004384 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004385 } catch (RemoteException | ServiceSpecificException e) {
4386 loge("Exception destroying network: " + e);
4387 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004388 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
4389 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
4390 // gets created, could add data to DnsManager data structures that will never get deleted.
4391 mDnsManager.removeNetwork(nai.network);
4392
4393 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09004394 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004395 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
4396 }
4397
Chalard Jean254bd162022-08-25 13:04:51 +09004398 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004399 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08004400 }
4401
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004402 // If this method proves to be too slow then we can maintain a separate
4403 // pendingIntent => NetworkRequestInfo map.
4404 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4405 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004406 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4407 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4408 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004409 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004410 return entry.getValue();
4411 }
4412 }
4413 return null;
4414 }
4415
Chalard Jean524f0b12021-10-25 21:11:56 +09004416 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4417 if (SdkLevel.isAtLeastT()) {
4418 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4419 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4420 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4421 // bug is fixed.
4422 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004423 throw new IllegalStateException("This NRI is already registered. New : " + nri
4424 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004425 }
4426 }
4427 }
4428 }
4429
Chalard Jeanac9ace02022-01-26 16:54:05 +09004430 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
4431 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08004432 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004433 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
4434 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004435 }
4436 return false;
4437 }
4438
James Mattisf7027322020-12-13 16:28:14 -08004439 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004440 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004441 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4442 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4443 final NetworkRequestInfo existingRequest =
4444 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004445 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004446 if (DBG) {
4447 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4448 + nri.mRequests.get(0) + " because their intents matched.");
4449 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004450 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004451 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004452 }
Erik Kline05f2b402015-04-30 12:58:40 +09004453 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004454 }
4455
James Mattisf7027322020-12-13 16:28:14 -08004456 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004457 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004458 }
4459
James Mattis3ce3d3c2021-02-09 18:18:28 -08004460 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004461 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004462 for (final NetworkRequestInfo nri : nris) {
4463 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004464 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004465 for (final NetworkRequest req : nri.mRequests) {
4466 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004467 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004468 if (req.isListen()) {
4469 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4470 if (req.networkCapabilities.hasSignalStrength()
4471 && network.satisfiesImmutableCapabilitiesOf(req)) {
4472 updateSignalStrengthThresholds(network, "REGISTER", req);
4473 }
James Mattisf7027322020-12-13 16:28:14 -08004474 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004475 }
4476 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004477
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004478 // If this NRI has a satisfier already, it is replacing an older request that
4479 // has been removed. Track it.
4480 final NetworkRequest activeRequest = nri.getActiveRequest();
4481 if (null != activeRequest) {
4482 // If there is an active request, then for sure there is a satisfier.
4483 nri.getSatisfier().addRequest(activeRequest);
4484 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004485 }
James Mattisf7027322020-12-13 16:28:14 -08004486
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004487 if (mFlags.noRematchAllRequestsOnRegister()) {
4488 rematchNetworksAndRequests(nris);
4489 } else {
4490 rematchAllNetworksAndRequests();
4491 }
James Mattis45d81842021-01-10 14:24:24 -08004492
Chalard Jean0354d8c2021-01-12 10:58:56 +09004493 // Requests that have not been matched to a network will not have been sent to the
4494 // providers, because the old satisfier and the new satisfier are the same (null in this
4495 // case). Send these requests to the providers.
4496 for (final NetworkRequestInfo nri : nris) {
4497 for (final NetworkOfferInfo noi : mNetworkOffers) {
4498 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004499 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004500 }
4501 }
4502
James Mattisf7027322020-12-13 16:28:14 -08004503 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4504 final int callingUid) {
4505 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004506 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004507 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4508 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4509 handleReleaseNetworkRequest(
4510 nri.mRequests.get(0),
4511 callingUid,
4512 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004513 }
4514 }
4515
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004516 // Determines whether the network is the best (or could become the best, if it validated), for
4517 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4518 // on the value of reason:
4519 //
4520 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4521 // then it should be torn down.
4522 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4523 // then it should be lingered.
4524 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004525 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004526
Chalard Jean254bd162022-08-25 13:04:51 +09004527 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09004528 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4529 return false;
4530 }
4531
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004532 final int numRequests;
4533 switch (reason) {
4534 case TEARDOWN:
4535 numRequests = nai.numRequestNetworkRequests();
4536 break;
4537 case LINGER:
4538 numRequests = nai.numForegroundNetworkRequests();
4539 break;
4540 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004541 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004542 return true;
4543 }
4544
Chalard Jean947acd42021-03-08 22:29:27 +09004545 if (numRequests > 0) return false;
4546
Paul Jensende49eb12015-06-25 15:30:08 -04004547 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004548 if (reason == UnneededFor.LINGER
4549 && !nri.isMultilayerRequest()
4550 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004551 // Background requests don't affect lingering.
4552 continue;
4553 }
4554
James Mattis3d229892020-11-16 16:46:28 -08004555 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004556 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004557 }
4558 }
Paul Jensende49eb12015-06-25 15:30:08 -04004559 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004560 }
4561
James Mattis3d229892020-11-16 16:46:28 -08004562 private boolean isNetworkPotentialSatisfier(
4563 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4564 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004565 // request, return immediately. For multilayer requests, check to see if any of the
4566 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004567 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4568 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004569 return false;
4570 }
4571 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004572 // This multilayer listen request is satisfied therefore no further requests need to be
4573 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004574 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004575 return false;
4576 }
James Mattis3d229892020-11-16 16:46:28 -08004577 // As non-multilayer listen requests have already returned, the below would only happen
4578 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004579 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004580 continue;
4581 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09004582 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08004583 // there is hope for it to become one if it validated, then it is needed.
4584 if (candidate.satisfies(req)) {
4585 // As soon as a network is found that satisfies a request, return. Specifically for
4586 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4587 // is important so as to not evaluate lower priority requests further in
4588 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004589 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4590 ? nri.getSatisfier() : null;
4591 // Note that this catches two important cases:
4592 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4593 // is currently satisfying the request. This is desirable when
4594 // cellular ends up validating but WiFi does not.
4595 // 2. Unvalidated WiFi will not be reaped when validated cellular
4596 // is currently satisfying the request. This is desirable when
4597 // WiFi ends up validating and out scoring cellular.
4598 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004599 }
4600 }
4601
4602 return false;
4603 }
4604
Erik Kline0c04b742016-07-07 16:50:58 +09004605 private NetworkRequestInfo getNriForAppRequest(
4606 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004607 // Looking up the app passed param request in mRequests isn't possible since it may return
4608 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4609 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004610 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4611 // to avoid potential race conditions when validating a package->uid mapping when sending
4612 // the callback on the very low-chance that an application shuts down prior to the callback
4613 // being sent.
4614 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4615 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004616
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004617 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004618 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004619 log(String.format("UID %d attempted to %s for unowned request %s",
4620 callingUid, requestedOperation, nri));
4621 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004622 }
Erik Kline0c04b742016-07-07 16:50:58 +09004623 }
4624
4625 return nri;
4626 }
4627
James Mattisf7027322020-12-13 16:28:14 -08004628 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4629 final String callingMethod) {
4630 if (nri.isMultilayerRequest()) {
4631 throw new IllegalStateException(
4632 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004633 }
4634 }
4635
James Mattisf7027322020-12-13 16:28:14 -08004636 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004637 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004638 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4639 // single NetworkRequest and thus does not apply to multilayer requests.
4640 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4641 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004642 return;
4643 }
James Mattis2516da32021-01-31 17:06:19 -08004644 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004645 return;
4646 }
James Mattisf7027322020-12-13 16:28:14 -08004647 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4648 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004649 }
4650 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004651 callCallbackForRequest(
4652 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004653 }
4654
James Mattisf7027322020-12-13 16:28:14 -08004655 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4656 final int callingUid,
4657 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004658 final NetworkRequestInfo nri =
4659 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4660 if (nri == null) {
4661 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004662 }
James Mattisf7027322020-12-13 16:28:14 -08004663 if (VDBG || (DBG && request.isRequest())) {
4664 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004665 }
4666 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004667 if (callOnUnavailable) {
4668 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4669 }
Erik Kline155a59a2015-11-25 12:49:38 +09004670 }
Erik Kline0c04b742016-07-07 16:50:58 +09004671
James Mattisa076c532020-12-02 14:12:41 -08004672 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004673 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004674 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004675 if (null == mNetworkRequests.remove(req)) {
4676 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4677 continue;
4678 }
James Mattisa076c532020-12-02 14:12:41 -08004679 if (req.isListen()) {
4680 removeListenRequestFromNetworks(req);
4681 }
4682 }
James Mattis8f036802021-06-20 16:26:01 -07004683 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004684 if (mDefaultNetworkRequests.remove(nri)) {
4685 // If this request was one of the defaults, then the UID rules need to be updated
4686 // WARNING : if the app(s) for which this network request is the default are doing
4687 // traffic, this will kill their connected sockets, even if an equivalent request
4688 // is going to be reinstated right away ; unconnected traffic will go on the default
4689 // until the new default is set, which will happen very soon.
4690 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4691 // remove ranges for those requests that won't have a replacement
4692 final NetworkAgentInfo satisfier = nri.getSatisfier();
4693 if (null != satisfier) {
4694 try {
paulhu0e79d952021-06-09 16:11:35 +08004695 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4696 satisfier.network.getNetId(),
4697 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004698 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004699 } catch (RemoteException e) {
4700 loge("Exception setting network preference default network", e);
4701 }
4702 }
4703 }
Junyu Lai00d92df2022-07-05 11:01:52 +08004704 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09004705 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004706 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004707
4708 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004709 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004710 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004711 }
4712 }
4713
Chalard Jean0354d8c2021-01-12 10:58:56 +09004714 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4715 // needed for this offer.
4716 for (final NetworkOfferInfo noi : mNetworkOffers) {
4717 for (final NetworkRequest req : nri.mRequests) {
4718 if (req.isRequest() && noi.offer.neededFor(req)) {
4719 noi.offer.onNetworkUnneeded(req);
4720 }
4721 }
4722 }
James Mattisa076c532020-12-02 14:12:41 -08004723 }
4724
James Mattis3ce3d3c2021-02-09 18:18:28 -08004725 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4726 for (final NetworkRequestInfo nri : nris) {
4727 if (mDefaultRequest == nri) {
4728 // Make sure we never remove the default request.
4729 continue;
4730 }
4731 handleRemoveNetworkRequest(nri);
4732 }
4733 }
4734
James Mattisa076c532020-12-02 14:12:41 -08004735 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4736 // listens don't have a singular affected Network. Check all networks to see
4737 // if this listen request applies and remove it.
4738 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4739 nai.removeRequest(req.requestId);
4740 if (req.networkCapabilities.hasSignalStrength()
4741 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4742 updateSignalStrengthThresholds(nai, "RELEASE", req);
4743 }
4744 }
4745 }
4746
4747 /**
4748 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4749 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4750 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4751 */
4752 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4753 boolean wasKept = false;
4754 final NetworkAgentInfo nai = nri.getSatisfier();
4755 if (nai != null) {
4756 final int requestLegacyType = nri.getActiveRequest().legacyType;
4757 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4758 nai.removeRequest(nri.getActiveRequest().requestId);
4759 if (VDBG || DDBG) {
4760 log(" Removing from current network " + nai.toShortString()
4761 + ", leaving " + nai.numNetworkRequests() + " requests.");
4762 }
4763 // If there are still lingered requests on this network, don't tear it down,
4764 // but resume lingering instead.
4765 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004766 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004767 notifyNetworkLosing(nai, now);
4768 }
4769 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4770 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4771 teardownUnneededNetwork(nai);
4772 } else {
4773 wasKept = true;
4774 }
James Mattisa076c532020-12-02 14:12:41 -08004775 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4776 // Went from foreground to background.
4777 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004778 }
4779
Erik Kline0c04b742016-07-07 16:50:58 +09004780 // Maintain the illusion. When this request arrived, we might have pretended
4781 // that a network connected to serve it, even though the network was already
4782 // connected. Now that this request has gone away, we might have to pretend
4783 // that the network disconnected. LegacyTypeTracker will generate that
4784 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004785 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004786 boolean doRemove = true;
4787 if (wasKept) {
4788 // check if any of the remaining requests for this network are for the
4789 // same legacy type - if so, don't remove the nai
4790 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4791 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004792 if (otherRequest.legacyType == requestLegacyType
4793 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004794 if (DBG) log(" still have other legacy request - leaving");
4795 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004796 }
4797 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004798 }
4799
Erik Kline0c04b742016-07-07 16:50:58 +09004800 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004801 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004802 }
4803 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004804 }
4805 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004806
Junyu Lai00d92df2022-07-05 11:01:52 +08004807 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004808 return checkAnyPermissionOf(
4809 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4810 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4811 }
4812
Lorenzo Colittid6459092016-07-04 12:55:44 +09004813 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004814 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004815 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004816 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004817 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004818 }
4819
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004820 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004821 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4822 enforceNetworkStackSettingsOrSetup();
4823 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4824 encodeBool(accept), encodeBool(always), network));
4825 }
4826
4827 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004828 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004829 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004830 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4831 }
4832
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004833 @Override
4834 public void setTestAllowBadWifiUntil(long timeMs) {
4835 enforceSettingsPermission();
4836 if (!Build.isDebuggable()) {
4837 throw new IllegalStateException("Does not support in non-debuggable build");
4838 }
4839
4840 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4841 throw new IllegalArgumentException("It should not exceed "
4842 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4843 }
4844
4845 mHandler.sendMessage(
4846 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
4847 }
4848
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004849 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4850 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4851 " accept=" + accept + " always=" + always);
4852
4853 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4854 if (nai == null) {
4855 // Nothing to do.
4856 return;
4857 }
4858
Chalard Jean254bd162022-08-25 13:04:51 +09004859 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004860 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004861 return;
4862 }
4863
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004864 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08004865 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004866 }
4867
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004868 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4869 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004870 // If network becomes partial connectivity and user already accepted to use this
4871 // network, we should respect the user's option and don't need to popup the
4872 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004873 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004874 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004875 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004876 }
4877
4878 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004879 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004880 }
4881
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004882 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04004883 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004884 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09004885 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04004886 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004887 }
4888
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004889 }
4890
lucaslin2240ef62019-03-12 13:08:03 +08004891 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4892 boolean always) {
4893 if (DBG) {
4894 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4895 + " always=" + always);
4896 }
4897
4898 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4899 if (nai == null) {
4900 // Nothing to do.
4901 return;
4902 }
4903
Chalard Jean254bd162022-08-25 13:04:51 +09004904 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08004905 // The network validated while the dialog box was up. Take no action.
4906 return;
4907 }
4908
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004909 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4910 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004911 }
4912
4913 // TODO: Use the current design or save the user choice into IpMemoryStore.
4914 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004915 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08004916 }
4917
4918 if (!accept) {
4919 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004920 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08004921 // Tear down the network.
4922 teardownUnneededNetwork(nai);
4923 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08004924 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4925 // result in a partial connectivity result which will be processed by
4926 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08004927 //
4928 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4929 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004930 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08004931 }
4932 }
4933
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004934 private void handleSetAvoidUnvalidated(Network network) {
4935 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09004936 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004937 // Nothing to do. The network either disconnected or revalidated.
4938 return;
4939 }
Chalard Jean254bd162022-08-25 13:04:51 +09004940 if (0L == nai.getAvoidUnvalidated()) {
4941 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09004942 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004943 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004944 }
4945 }
4946
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004947 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09004948 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004949 mHandler.sendMessageDelayed(
4950 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4951 PROMPT_UNVALIDATED_DELAY_MS);
4952 }
4953
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004954 @Override
4955 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08004956 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004957 mHandler.post(() -> {
4958 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4959 if (nai == null) return;
4960 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004961 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004962 });
4963 }
4964
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004965 /**
4966 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4967 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004968 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004969 * @param appExtras Bundle to use as intent extras for the captive portal application.
4970 * Must be treated as opaque to avoid preventing the captive portal app to
4971 * update its arguments.
4972 */
4973 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004974 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08004975 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4976 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004977
4978 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4979 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004980 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4981 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004982 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4983
lucaslin75ff7022020-12-17 04:14:35 +08004984 final long token = Binder.clearCallingIdentity();
4985 try {
4986 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4987 } finally {
4988 Binder.restoreCallingIdentity(token);
4989 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004990 }
4991
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004992 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4993 private final Network mNetwork;
4994
4995 private CaptivePortalImpl(Network network) {
4996 mNetwork = network;
4997 }
4998
4999 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005000 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005001 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5002 enforceSettingsPermission();
5003 }
5004
Chiachang Wang938bfba2020-01-09 13:50:55 +08005005 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005006 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005007 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005008 }
5009
5010 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005011 public void appRequest(final int request) {
5012 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5013 if (nm == null) return;
5014
5015 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005016 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005017 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005018 }
5019 }
5020
5021 @Nullable
5022 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5023 // getNetworkAgentInfoForNetwork is thread-safe
5024 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5025 if (nai == null) return null;
5026
5027 // nai.networkMonitor() is thread-safe
5028 return nai.networkMonitor();
5029 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005030 }
5031
Hugo Benichic9048bc2016-09-14 23:23:08 +00005032 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005033 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005034 }
5035
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005036 /**
5037 * Return whether the device should maintain continuous, working connectivity by switching away
5038 * from WiFi networks having no connectivity.
5039 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5040 */
5041 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005042 if (!checkNetworkStackPermission()) {
5043 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5044 }
5045 return avoidBadWifi();
5046 }
5047
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005048 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005049 ensureRunningOnConnectivityServiceThread();
5050 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005051 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005052 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005053 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005054 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5055 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5056 for (final NetworkOfferInfo noi : offersToUpdate) {
5057 updateOfferScore(noi.offer);
5058 }
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005059 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005060 }
5061
Erik Kline95ecfee2016-10-02 18:02:14 +09005062 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005063 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005064 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005065 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005066 if (!configRestrict) {
5067 pw.println("Bad Wi-Fi avoidance: unrestricted");
5068 return;
5069 }
5070
5071 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5072 pw.increaseIndent();
5073 pw.println("Config restrict: " + configRestrict);
5074
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005075 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005076 String description;
5077 // Can't use a switch statement because strings are legal case labels, but null is not.
5078 if ("0".equals(value)) {
5079 description = "get stuck";
5080 } else if (value == null) {
5081 description = "prompt";
5082 } else if ("1".equals(value)) {
5083 description = "avoid";
5084 } else {
5085 description = value + " (?)";
5086 }
5087 pw.println("User setting: " + description);
5088 pw.println("Network overrides:");
5089 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005090 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005091 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005092 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005093 }
5094 }
5095 pw.decreaseIndent();
5096 pw.decreaseIndent();
5097 }
5098
paulhu7746e4e2020-06-09 19:07:03 +08005099 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5100 // unify the method.
5101 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5102 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5103 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5104 return settingsComponent != null
5105 ? settingsComponent.getPackageName() : "com.android.settings";
5106 }
5107
lucaslinb1e8e382019-01-24 15:55:30 +08005108 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005109 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005110 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005111 switch (type) {
5112 case NO_INTERNET:
5113 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005114 // High priority because it is only displayed for explicitly selected networks.
5115 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005116 break;
lucasline117e2e2019-10-22 18:27:33 +08005117 case PRIVATE_DNS_BROKEN:
5118 action = Settings.ACTION_WIRELESS_SETTINGS;
5119 // High priority because we should let user know why there is no internet.
5120 highPriority = true;
5121 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005122 case LOST_INTERNET:
5123 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005124 // High priority because it could help the user avoid unexpected data usage.
5125 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005126 break;
lucaslin2240ef62019-03-12 13:08:03 +08005127 case PARTIAL_CONNECTIVITY:
5128 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005129 // Don't bother the user with a high-priority notification if the network was not
5130 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005131 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005132 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005133 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005134 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005135 return;
5136 }
5137
5138 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005139 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005140 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005141 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005142 // Some OEMs have their own Settings package. Thus, need to get the current using
5143 // Settings package name instead of just use default name "com.android.settings".
5144 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5145 intent.setClassName(settingsPkgName,
5146 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005147 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005148
paulhu2af50222020-10-11 22:52:27 +08005149 PendingIntent pendingIntent = PendingIntent.getActivity(
5150 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005151 0 /* requestCode */,
5152 intent,
paulhu2af50222020-10-11 22:52:27 +08005153 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005154
Serik Beketayevec8ad212020-12-07 22:43:07 -08005155 mNotifier.showNotification(
5156 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005157 }
5158
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005159 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5160 // Don't prompt if the network is validated, and don't prompt on captive portals
5161 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005162 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005163 return false;
5164 }
5165
5166 // If a network has partial connectivity, always prompt unless the user has already accepted
5167 // partial connectivity and selected don't ask again. This ensures that if the device
5168 // automatically connects to a network that has partial Internet access, the user will
5169 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005170 // because we have prompted them.
5171 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005172 return true;
5173 }
5174
5175 // If a network has no Internet access, only prompt if the network was explicitly selected
5176 // and if the user has not already told us to use the network regardless of whether it
5177 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005178 if (nai.networkAgentConfig.explicitlySelected
5179 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005180 return true;
5181 }
5182
5183 return false;
5184 }
5185
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005186 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09005187 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005188 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5189
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005190 if (nai == null || !shouldPromptUnvalidated(nai)) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005191 return;
5192 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005193
5194 // Stop automatically reconnecting to this network in the future. Automatically connecting
5195 // to a network that provides no or limited connectivity is not useful, because the user
5196 // cannot use that network except through the notification shown by this method, and the
5197 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005198 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005199
lucaslin2240ef62019-03-12 13:08:03 +08005200 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
5201 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
5202 // popup the notification immediately when the network is partial connectivity.
Chalard Jean254bd162022-08-25 13:04:51 +09005203 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005204 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005205 } else {
5206 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5207 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005208 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005209
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005210 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5211 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005212 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005213
lucaslin2240ef62019-03-12 13:08:03 +08005214 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5215 return;
5216 }
5217
5218 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005219 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005220 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005221 }
5222
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005223 @Override
5224 public int getMultipathPreference(Network network) {
5225 enforceAccessPermission();
5226
5227 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005228 if (nai != null && nai.networkCapabilities
5229 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005230 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5231 }
5232
Aaron Huang9a57acf2020-12-08 10:03:29 +08005233 final NetworkPolicyManager netPolicyManager =
5234 mContext.getSystemService(NetworkPolicyManager.class);
5235
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005236 final long token = Binder.clearCallingIdentity();
5237 final int networkPreference;
5238 try {
5239 networkPreference = netPolicyManager.getMultipathPreference(network);
5240 } finally {
5241 Binder.restoreCallingIdentity(token);
5242 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005243 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005244 return networkPreference;
5245 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005246 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5247 }
5248
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005249 @Override
5250 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005251 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005252 }
5253
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005254 private class InternalHandler extends Handler {
5255 public InternalHandler(Looper looper) {
5256 super(looper);
5257 }
5258
5259 @Override
5260 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005261 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005262 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005263 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005264 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005265 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005266 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005267 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005268 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005269 break;
5270 }
Jason Monka69f1b02013-10-10 14:02:51 -04005271 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005272 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5273 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005274 break;
5275 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005276 case EVENT_REGISTER_NETWORK_PROVIDER: {
5277 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005278 break;
5279 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005280 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5281 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005282 break;
5283 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005284 case EVENT_REGISTER_NETWORK_OFFER: {
5285 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5286 break;
5287 }
5288 case EVENT_UNREGISTER_NETWORK_OFFER: {
5289 final NetworkOfferInfo offer =
5290 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5291 if (null != offer) {
5292 handleUnregisterNetworkOffer(offer);
5293 }
5294 break;
5295 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005296 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005297 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5298 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5299 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005300 break;
5301 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005302 case EVENT_REGISTER_NETWORK_REQUEST:
5303 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005304 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005305 break;
5306 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005307 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5308 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005309 handleRegisterNetworkRequestWithIntent(msg);
5310 break;
5311 }
Erik Kline155a59a2015-11-25 12:49:38 +09005312 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5313 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5314 handleTimedOutNetworkRequest(nri);
5315 break;
5316 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005317 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5318 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5319 break;
5320 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005321 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005322 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5323 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005324 break;
5325 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005326 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005327 Network network = (Network) msg.obj;
5328 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005329 break;
5330 }
lucaslin2240ef62019-03-12 13:08:03 +08005331 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5332 Network network = (Network) msg.obj;
5333 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5334 toBool(msg.arg2));
5335 break;
5336 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005337 case EVENT_SET_AVOID_UNVALIDATED: {
5338 handleSetAvoidUnvalidated((Network) msg.obj);
5339 break;
5340 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005341 case EVENT_PROMPT_UNVALIDATED: {
5342 handlePromptUnvalidated((Network) msg.obj);
5343 break;
5344 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005345 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5346 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005347 break;
5348 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005349 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005350 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005351 mKeepaliveTracker.handleStartKeepalive(msg);
5352 break;
5353 }
5354 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005355 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005356 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5357 int slot = msg.arg1;
5358 int reason = msg.arg2;
5359 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
5360 break;
5361 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005362 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5363 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5364 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005365 break;
5366 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005367 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5368 handlePrivateDnsSettingsChanged();
5369 break;
dalyk1720e542018-03-05 12:42:22 -05005370 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5371 handlePrivateDnsValidationUpdate(
5372 (PrivateDnsValidationUpdate) msg.obj);
5373 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005374 case EVENT_UID_BLOCKED_REASON_CHANGED:
5375 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005376 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005377 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5378 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5379 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005380 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005381 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5382 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005383 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005384 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005385 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005386 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005387 final Pair<List<ProfileNetworkPreferenceList.Preference>,
5388 IOnCompleteListener> arg =
5389 (Pair<List<ProfileNetworkPreferenceList.Preference>,
5390 IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005391 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005392 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005393 }
lucaslin1193a5d2021-01-21 02:04:15 +08005394 case EVENT_REPORT_NETWORK_ACTIVITY:
5395 mNetworkActivityTracker.handleReportNetworkActivity();
5396 break;
paulhu51f77dc2021-06-07 02:34:20 +00005397 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5398 handleMobileDataPreferredUidsChanged();
5399 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005400 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5401 final long timeMs = ((Long) msg.obj).longValue();
5402 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5403 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01005404 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
5405 handleIngressRateLimitChanged();
5406 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005407 }
5408 }
5409 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005410
Lorenzo Colittid6459092016-07-04 12:55:44 +09005411 @Override
markchien5776f962019-12-16 20:15:20 +08005412 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005413 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08005414 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005415 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5416 Context.TETHERING_SERVICE);
5417 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005418 }
5419
Lorenzo Colittid6459092016-07-04 12:55:44 +09005420 @Override
markchien5776f962019-12-16 20:15:20 +08005421 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005422 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08005423 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005424 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5425 Context.TETHERING_SERVICE);
5426 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005427 }
5428
Lorenzo Colittid6459092016-07-04 12:55:44 +09005429 @Override
markchien5776f962019-12-16 20:15:20 +08005430 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005431 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005432 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005433 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5434 Context.TETHERING_SERVICE);
5435 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005436 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005437
markchien5776f962019-12-16 20:15:20 +08005438
Lorenzo Colittid6459092016-07-04 12:55:44 +09005439 @Override
markchien5776f962019-12-16 20:15:20 +08005440 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005441 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005442 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005443 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5444 Context.TETHERING_SERVICE);
5445
5446 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005447 }
5448
Lorenzo Colittid6459092016-07-04 12:55:44 +09005449 @Override
markchien5776f962019-12-16 20:15:20 +08005450 @Deprecated
5451 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08005452 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005453 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5454 Context.TETHERING_SERVICE);
5455
5456 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005457 }
5458
Udam Saini8f7d6a72017-06-07 12:06:28 -07005459 @Override
markchien5776f962019-12-16 20:15:20 +08005460 @Deprecated
5461 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08005462 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005463 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5464 Context.TETHERING_SERVICE);
5465 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005466 }
5467
Robert Greenwalte0b00512014-07-02 09:59:16 -07005468 // Called when we lose the default network and have no replacement yet.
5469 // This will automatically be cleared after X seconds or a new default network
5470 // becomes CONNECTED, whichever happens first. The timer is started by the
5471 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005472 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005473 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005474 if (mNetTransitionWakeLock.isHeld()) {
5475 return;
5476 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005477 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005478 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5479 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005480 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005481 mWakelockLogs.log("ACQUIRE for " + forWhom);
5482 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005483 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005484 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005485 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005486 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005487
Hugo Benichi471b62a2017-03-30 23:18:10 +09005488 // Called when we gain a new default network to release the network transition wakelock in a
5489 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5490 // message is cancelled.
5491 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005492 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005493 if (!mNetTransitionWakeLock.isHeld()) {
5494 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005495 }
5496 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005497 // Cancel self timeout on wakelock hold.
5498 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5499 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5500 mHandler.sendMessageDelayed(msg, 1000);
5501 }
5502
5503 // Called when either message of ensureNetworkTransitionWakelock or
5504 // scheduleReleaseNetworkTransitionWakelock is processed.
5505 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5506 String event = eventName(eventId);
5507 synchronized (this) {
5508 if (!mNetTransitionWakeLock.isHeld()) {
5509 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005510 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005511 return;
5512 }
5513 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005514 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5515 mTotalWakelockDurationMs += lockDuration;
5516 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5517 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005518 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005519 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005520 }
5521
Robert Greenwalt986c7412010-09-08 15:24:47 -07005522 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005523 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005524 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005525 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005526 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005527 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005528 }
5529
Lorenzo Colittid6459092016-07-04 12:55:44 +09005530 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005531 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005532 enforceAccessPermission();
5533 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005534 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005535 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005536
5537 final NetworkAgentInfo nai;
5538 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005539 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005540 } else {
5541 nai = getNetworkAgentInfoForNetwork(network);
5542 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005543
5544 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005545 mHandler.obtainMessage(
5546 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005547 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005548
Hugo Benichid6b510a2017-04-06 17:22:18 +09005549 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005550 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005551 if (nai == null
5552 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005553 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005554 return;
5555 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005556 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09005557 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005558 mConnectivityDiagnosticsHandler.sendMessage(
5559 mConnectivityDiagnosticsHandler.obtainMessage(
5560 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5561 new ReportedNetworkConnectivityInfo(
5562 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005563 return;
5564 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005565 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005566 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005567 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005568 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005569 // Validating a network that has not yet connected could result in a call to
5570 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09005571 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005572 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005573 }
paulhu7aeba372020-12-30 00:42:19 +08005574 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5575 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005576 return;
5577 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005578
5579 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5580 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5581 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5582 // completed.
5583 mConnectivityDiagnosticsHandler.sendMessage(
5584 mConnectivityDiagnosticsHandler.obtainMessage(
5585 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5586 new ReportedNetworkConnectivityInfo(
5587 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005588 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005589 }
5590
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005591 // TODO: call into netd.
5592 private boolean queryUserAccess(int uid, Network network) {
5593 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5594 if (nai == null) return false;
5595
5596 // Any UID can use its default network.
5597 if (nai == getDefaultNetworkForUid(uid)) return true;
5598
5599 // Privileged apps can use any network.
5600 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5601 return true;
5602 }
5603
5604 // An unprivileged UID can use a VPN iff the VPN applies to it.
5605 if (nai.isVPN()) {
5606 return nai.networkCapabilities.appliesToUid(uid);
5607 }
5608
5609 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5610 // sockets, i.e., if it is the owner.
5611 final NetworkAgentInfo vpn = getVpnForUid(uid);
5612 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5613 && uid != vpn.networkCapabilities.getOwnerUid()) {
5614 return false;
5615 }
5616
5617 // The UID's permission must be at least sufficient for the network. Since the restricted
5618 // permission was already checked above, that just leaves background networks.
5619 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5620 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5621 }
5622
5623 // Unrestricted network. Anyone gets to use it.
5624 return true;
5625 }
5626
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005627 /**
5628 * Returns information about the proxy a certain network is using. If given a null network, it
5629 * it will return the proxy for the bound network for the caller app or the default proxy if
5630 * none.
5631 *
5632 * @param network the network we want to get the proxy information for.
5633 * @return Proxy information if a network has a proxy configured, or otherwise null.
5634 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005635 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005636 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005637 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005638 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005639 if (network == null) {
5640 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005641 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005642 true);
5643 if (activeNetwork == null) {
5644 return null;
5645 }
5646 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005647 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005648 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5649 // caller may not have.
5650 return getLinkPropertiesProxyInfo(network);
5651 }
5652 // No proxy info available if the calling UID does not have network access.
5653 return null;
5654 }
5655
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005656
5657 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005658 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5659 if (nai == null) return null;
5660 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005661 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5662 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005663 }
5664 }
5665
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005666 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005667 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08005668 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005669 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005670 }
5671
Chalard Jean777e2e52018-06-07 18:02:37 +09005672 @Override
5673 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005674 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005675 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005676 }
5677
Jason Monk4d5e20f2014-04-25 15:00:09 -04005678 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005679 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005680 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005681 proxy = null;
5682 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005683 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005684 }
5685
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005686 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5687 // when any network changes proxy.
5688 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5689 // multi-network world where an app might be bound to a non-default network.
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005690 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensenc0618a62014-12-10 15:12:18 -05005691 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5692 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5693
Chalard Jean7d97afc2018-06-07 17:41:29 +09005694 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005695 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005696 }
5697 }
5698
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005699 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005700 final private HashMap<Uri, Integer> mUriEventMap;
5701 final private Context mContext;
5702 final private Handler mHandler;
5703
5704 SettingsObserver(Context context, Handler handler) {
5705 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005706 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005707 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005708 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005709 }
5710
Erik Kline05f2b402015-04-30 12:58:40 +09005711 void observe(Uri uri, int what) {
5712 mUriEventMap.put(uri, what);
5713 final ContentResolver resolver = mContext.getContentResolver();
5714 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005715 }
5716
5717 @Override
5718 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005719 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005720 }
5721
5722 @Override
5723 public void onChange(boolean selfChange, Uri uri) {
5724 final Integer what = mUriEventMap.get(uri);
5725 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005726 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005727 } else {
5728 loge("No matching event to send for URI=" + uri);
5729 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005730 }
5731 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005732
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005733 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005734 Log.d(TAG, s);
5735 }
5736
5737 private static void logw(String s) {
5738 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005739 }
5740
Daniel Brightf9e945b2020-06-15 16:10:01 -07005741 private static void logwtf(String s) {
5742 Log.wtf(TAG, s);
5743 }
5744
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005745 private static void logwtf(String s, Throwable t) {
5746 Log.wtf(TAG, s, t);
5747 }
5748
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005749 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005750 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005751 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005752
Hugo Benichi39621362017-02-11 17:04:43 +09005753 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005754 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005755 }
5756
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005757 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005758 * Return the information of all ongoing VPNs.
5759 *
5760 * <p>This method is used to update NetworkStatsService.
5761 *
5762 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08005763 */
junyulai2050bed2021-01-23 09:46:34 +08005764 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005765 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09005766 if (mLockdownEnabled) {
5767 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08005768 }
junyulai2050bed2021-01-23 09:46:34 +08005769 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005770 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08005771 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005772 if (info != null) {
5773 infoList.add(info);
5774 }
5775 }
junyulai2050bed2021-01-23 09:46:34 +08005776 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08005777 }
5778
5779 /**
5780 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00005781 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08005782 */
junyulai2050bed2021-01-23 09:46:34 +08005783 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005784 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08005785 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5786 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09005787 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5788 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5789 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08005790 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5791 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00005792 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00005793 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08005794 }
5795 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005796
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005797 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005798
5799 List<String> interfaces = new ArrayList<>();
5800 for (Network network : underlyingNetworks) {
5801 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5802 if (underlyingNai == null) continue;
5803 LinkProperties lp = underlyingNai.linkProperties;
5804 for (String iface : lp.getAllInterfaceNames()) {
5805 if (!TextUtils.isEmpty(iface)) {
5806 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00005807 }
5808 }
Benedict Wong34857f82019-06-12 17:46:15 +00005809 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005810
5811 if (interfaces.isEmpty()) return null;
5812
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005813 // Must be non-null or NetworkStatsService will crash.
5814 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5815 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08005816 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08005817 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005818
junyulai2050bed2021-01-23 09:46:34 +08005819 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5820 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08005821 }
5822
James Mattisd31bdfa2020-12-23 16:37:26 -08005823 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08005824 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5825 Network[] underlyingNetworks) {
5826 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005827 if (underlyingNetworks == null && defaultNetwork != null) {
5828 // null underlying networks means to track the default.
5829 underlyingNetworks = new Network[] { defaultNetwork };
5830 }
5831 return underlyingNetworks;
5832 }
5833
5834 // Returns true iff |network| is an underlying network of |nai|.
5835 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5836 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5837 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09005838 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08005839 final Network[] underlying = underlyingNetworksOrDefault(
5840 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005841 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005842 }
5843
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005844 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005845 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005846 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005847 * When underlying networks change, such networks may have to update capabilities to reflect
5848 * things like the metered bit, their transports, and so on. The capabilities are calculated
5849 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005850 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005851 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005852 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005853 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005854 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005855 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005856 }
5857 }
5858 }
5859
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005860 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5861 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5862 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5863 // a VPN is not up.
5864 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5865 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5866 for (UidRange range : blockedUidRanges) {
5867 if (range.contains(uid)) return true;
5868 }
5869 return false;
5870 }
5871
5872 @Override
5873 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08005874 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005875 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5876 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5877 }
5878
5879 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5880 if (DBG) {
5881 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5882 + Arrays.toString(ranges));
5883 }
5884 // Cannot use a Set since the list of UID ranges might contain duplicates.
5885 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5886 for (int i = 0; i < ranges.length; i++) {
5887 if (requireVpn) {
5888 newVpnBlockedUidRanges.add(ranges[i]);
5889 } else {
5890 newVpnBlockedUidRanges.remove(ranges[i]);
5891 }
5892 }
5893
5894 try {
5895 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5896 } catch (RemoteException | ServiceSpecificException e) {
5897 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5898 + Arrays.toString(ranges) + "): netd command failed: " + e);
5899 }
5900
Motomu Utsumib08654c2022-05-11 05:56:26 +00005901 if (SdkLevel.isAtLeastT()) {
5902 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
5903 }
5904
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005905 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5906 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00005907 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5908 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005909 }
5910
5911 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5912 }
5913
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07005914 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005915 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08005916 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005917 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01005918 }
5919
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005920 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5921 return mLockdownEnabled
5922 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5923 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00005924 }
5925
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005926 private NetworkAgentInfo getLegacyLockdownNai() {
5927 if (!mLockdownEnabled) {
5928 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005929 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005930 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005931 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5932 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005933
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005934 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005935 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5936 // a local variable. There is no need to make a copy because its contents cannot change.
5937 final Network[] underlying = nai.declaredUnderlyingNetworks;
5938 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005939 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005940 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005941
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005942 // The legacy lockdown VPN always uses the default network.
5943 // If the VPN's underlying network is no longer the current default network, it means that
5944 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005945 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5946 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005947 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005948 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005949 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005950 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005951
5952 return nai;
5953 };
5954
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005955 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5956 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5957 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005958 private DetailedState getLegacyLockdownState(DetailedState origState) {
5959 if (origState != DetailedState.CONNECTED) {
5960 return origState;
5961 }
5962 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5963 ? DetailedState.CONNECTING
5964 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005965 }
5966
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005967 private void filterForLegacyLockdown(NetworkInfo ni) {
5968 if (!mLockdownEnabled || !ni.isConnected()) return;
5969 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5970 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5971 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5972 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5973 // network, this time with a state of CONNECTED.
5974 //
5975 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5976 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5977 // is not too far off the truth, since an always-on VPN, when not connected, is always
5978 // trying to reconnect.
5979 if (getLegacyLockdownNai() == null) {
5980 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5981 }
5982 }
5983
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005984 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005985 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04005986 String action) {
paulhu8e96a752019-08-12 16:25:11 +08005987 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09005988 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5989 return;
5990 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04005991 final long ident = Binder.clearCallingIdentity();
5992 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09005993 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09005994 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09005995 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04005996 } finally {
5997 Binder.restoreCallingIdentity(ident);
5998 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005999 }
Wink Savillecb117d32013-08-29 14:57:08 -07006000
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006001 @Override
6002 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006003 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006004 final long ident = Binder.clearCallingIdentity();
6005 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006006 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006007 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006008 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6009 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006010 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006011 } finally {
6012 Binder.restoreCallingIdentity(ident);
6013 }
6014 }
6015
James Mattis02220e22021-03-13 19:27:21 -08006016 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006017 mPermissionMonitor.onUserAdded(user);
James Mattisae9aeb02021-03-01 17:09:11 -08006018 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6019 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6020 }
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006021 }
6022
James Mattis02220e22021-03-13 19:27:21 -08006023 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006024 mPermissionMonitor.onUserRemoved(user);
Chalard Jean0f57a492021-03-09 21:09:20 +09006025 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006026 handleSetProfileNetworkPreference(
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08006027 List.of(new ProfileNetworkPreferenceList.Preference(user, null, true)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006028 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006029 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6030 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6031 }
junyulaid91e7052020-08-28 13:44:33 +08006032 }
6033
James Mattis02220e22021-03-13 19:27:21 -08006034 private void onPackageChanged(@NonNull final String packageName) {
6035 // This is necessary in case a package is added or removed, but also when it's replaced to
6036 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6037 // as one in the preferences, then it should follow the same routing as that other package,
6038 // which means updating the rules is never to be needed in this case (whether it joins or
6039 // leaves a UID with a preference).
6040 if (isMappedInOemNetworkPreference(packageName)) {
6041 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6042 }
6043 }
6044
6045 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006046 @Override
6047 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006048 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006049 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006050 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006051
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006052 // User should be filled for below intents, check the existence.
6053 if (user == null) {
6054 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6055 return;
6056 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006057
Lorenzo Colitticd675292021-02-04 17:32:07 +09006058 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006059 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006060 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006061 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006062 } else {
junyulaid91e7052020-08-28 13:44:33 +08006063 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006064 }
6065 }
6066 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006067
James Mattis02220e22021-03-13 19:27:21 -08006068 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6069 @Override
6070 public void onReceive(Context context, Intent intent) {
6071 ensureRunningOnConnectivityServiceThread();
6072 switch (intent.getAction()) {
6073 case Intent.ACTION_PACKAGE_ADDED:
6074 case Intent.ACTION_PACKAGE_REMOVED:
6075 case Intent.ACTION_PACKAGE_REPLACED:
6076 onPackageChanged(intent.getData().getSchemeSpecificPart());
6077 break;
6078 default:
6079 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6080 }
6081 }
6082 };
6083
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006084 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006085 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006086
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006087 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006088 public final String name;
6089 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006090 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006091 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006092
lifraf3a3492021-03-10 13:58:14 +08006093 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6094 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006095 this.name = name;
6096 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006097 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006098 mDeathRecipient = deathRecipient;
6099
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006100 if (mDeathRecipient == null) {
6101 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006102 }
6103 }
6104
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006105 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006106 try {
6107 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6108 } catch (RemoteException e) {
6109 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006110 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006111 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006112 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006113
James Mattis4fce5d12020-11-12 15:53:42 -08006114 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6115 for (int i = 0; i < requests.size(); i++) {
6116 ensureNetworkRequestHasType(requests.get(i));
6117 }
6118 }
6119
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006120 private void ensureNetworkRequestHasType(NetworkRequest request) {
6121 if (request.type == NetworkRequest.Type.NONE) {
6122 throw new IllegalArgumentException(
6123 "All NetworkRequests in ConnectivityService must have a type");
6124 }
6125 }
6126
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006127 /**
6128 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006129 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006130 */
James Mattis258ea3c2020-11-15 15:04:40 -08006131 @VisibleForTesting
6132 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006133 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6134 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006135 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006136
James Mattisa076c532020-12-02 14:12:41 -08006137 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6138 void setSatisfier(
6139 @Nullable final NetworkAgentInfo satisfier,
6140 @Nullable final NetworkRequest activeRequest) {
6141 mSatisfier = satisfier;
6142 mActiveRequest = activeRequest;
6143 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006144
James Mattisd31bdfa2020-12-23 16:37:26 -08006145 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006146 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006147 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006148 private NetworkAgentInfo mSatisfier;
6149 NetworkAgentInfo getSatisfier() {
6150 return mSatisfier;
6151 }
6152
6153 // The request in mRequests assigned to a network agent. This is null if none of the
6154 // requests in mRequests can be satisfied. This member has the constraint of only being
6155 // accessible on the handler thread.
6156 @Nullable
6157 private NetworkRequest mActiveRequest;
6158 NetworkRequest getActiveRequest() {
6159 return mActiveRequest;
6160 }
6161
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006162 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006163 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006164 @Nullable
6165 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006166
6167 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006168 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006169 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006170 final int mPid;
6171 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006172 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006173 @Nullable
6174 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006175
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006176 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006177 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006178
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006179 // Effective UID of this request. This is different from mUid when a privileged process
6180 // files a request on behalf of another UID. This UID is used to determine blocked status,
6181 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6182 // maximum limit of registered callbacks per UID.
6183 final int mAsUid;
6184
paulhu48291862021-07-14 14:53:57 +08006185 // Preference order of this request.
6186 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006187
James Mattis3ce3d3c2021-02-09 18:18:28 -08006188 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6189 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6190 // maintained for keying off of. This is only a concern when the original nri
6191 // mNetworkRequests changes which happens currently for apps that register callbacks to
6192 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6193 // that match the per-app default nri that currently tracks the calling app's uid so that
6194 // callbacks are fired at the appropriate time. When the callbacks fire,
6195 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6196 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6197 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6198 @NonNull
6199 private final NetworkRequest mNetworkRequestForCallback;
6200 NetworkRequest getNetworkRequestForCallback() {
6201 return mNetworkRequestForCallback;
6202 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006203
James Mattisd31bdfa2020-12-23 16:37:26 -08006204 /**
6205 * Get the list of UIDs this nri applies to.
6206 */
6207 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006208 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006209 // networkCapabilities.getUids() returns a defensive copy.
6210 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006211 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6212 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006213 }
6214
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006215 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6216 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006217 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006218 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006219 }
6220
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006221 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006222 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006223 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006224 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006225 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006226 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006227 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006228 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006229 mBinder = null;
6230 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006231 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006232 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006233 mPerUidCounter = getRequestCounter(this);
6234 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006235 /**
6236 * Location sensitive data not included in pending intent. Only included in
6237 * {@link NetworkCallback}.
6238 */
6239 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006240 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006241 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006242 }
6243
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006244 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006245 @Nullable final IBinder binder,
6246 @NetworkCallback.Flag int callbackFlags,
6247 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006248 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
6249 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08006250 }
6251
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006252 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006253 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006254 @Nullable final IBinder binder,
6255 @NetworkCallback.Flag int callbackFlags,
6256 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006257 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006258 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006259 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006260 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006261 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006262 mBinder = binder;
6263 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006264 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006265 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006266 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006267 mPerUidCounter = getRequestCounter(this);
6268 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006269 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006270 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006271 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006272 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006273 }
6274
James Mattis3ce3d3c2021-02-09 18:18:28 -08006275 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6276 @NonNull final List<NetworkRequest> r) {
6277 super();
6278 ensureAllNetworkRequestsHaveType(r);
6279 mRequests = initializeRequests(r);
6280 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006281 final NetworkAgentInfo satisfier = nri.getSatisfier();
6282 if (null != satisfier) {
6283 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6284 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09006285 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006286 // As this code creates a new NRI with a new set of requests, figure out which of
6287 // the list of requests should be the active request. It is always the first
6288 // request of the list that can be satisfied by the satisfier since the order of
6289 // requests is a priority order.
6290 // Note even in the presence of a satisfier there may not be an active request,
6291 // when the satisfier is the no-service network.
6292 NetworkRequest activeRequest = null;
6293 for (final NetworkRequest candidate : r) {
6294 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6295 activeRequest = candidate;
6296 break;
6297 }
6298 }
6299 setSatisfier(satisfier, activeRequest);
6300 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006301 mMessenger = nri.mMessenger;
6302 mBinder = nri.mBinder;
6303 mPid = nri.mPid;
6304 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006305 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006306 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006307 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006308 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006309 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006310 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006311 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006312 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006313 }
6314
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006315 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006316 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006317 }
6318
paulhue9913722021-05-26 15:19:20 +08006319 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006320 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006321 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006322 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006323 }
6324
James Mattis2516da32021-01-31 17:06:19 -08006325 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6326 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6327 // false.
6328 boolean isBeingSatisfied() {
6329 return (null != mSatisfier && null != mActiveRequest);
6330 }
6331
James Mattis3d229892020-11-16 16:46:28 -08006332 boolean isMultilayerRequest() {
6333 return mRequests.size() > 1;
6334 }
6335
James Mattis45d81842021-01-10 14:24:24 -08006336 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6337 // Creating a defensive copy to prevent the sender from modifying the list being
6338 // reflected in the return value of this method.
6339 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006340 return Collections.unmodifiableList(tempRequests);
6341 }
6342
James Mattisb1392002021-03-31 13:57:52 -07006343 void linkDeathRecipient() {
6344 if (null != mBinder) {
6345 try {
6346 mBinder.linkToDeath(this, 0);
6347 } catch (RemoteException e) {
6348 binderDied();
6349 }
6350 }
6351 }
6352
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006353 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006354 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006355 try {
6356 mBinder.unlinkToDeath(this, 0);
6357 } catch (NoSuchElementException e) {
6358 // Temporary workaround for b/194394697 pending analysis of additional logs
6359 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6360 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006361 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006362 }
6363
paulhu48291862021-07-14 14:53:57 +08006364 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6365 // Compare two preference orders.
6366 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006367 }
6368
paulhu48291862021-07-14 14:53:57 +08006369 int getPreferenceOrderForNetd() {
6370 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6371 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6372 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006373 }
paulhu48291862021-07-14 14:53:57 +08006374 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006375 }
6376
James Mattis4fce5d12020-11-12 15:53:42 -08006377 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006378 public void binderDied() {
6379 log("ConnectivityService NetworkRequestInfo binderDied(" +
Chalard Jean524f0b12021-10-25 21:11:56 +09006380 "uid/pid:" + mUid + "/" + mPid + ", " + mRequests + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09006381 // As an immutable collection, mRequests cannot change by the time the
6382 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6383 // is acceptable. Use handleReleaseNetworkRequest and not directly
6384 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6385 // the app already unregistered the request.
6386 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6387 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006388 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006389
James Mattis4fce5d12020-11-12 15:53:42 -08006390 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006391 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006392 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6393 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006394 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006395 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006396 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006397 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006398 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006399 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006400 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006401 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006402 }
6403
Junyu Lai00d92df2022-07-05 11:01:52 +08006404 // Keep backward compatibility since the ServiceSpecificException is used by
6405 // the API surface, see {@link ConnectivityManager#convertServiceException}.
6406 public static class RequestInfoPerUidCounter extends PerUidCounter {
6407 RequestInfoPerUidCounter(int maxCountPerUid) {
6408 super(maxCountPerUid);
6409 }
6410
6411 @Override
6412 public synchronized void incrementCountOrThrow(int uid) {
6413 try {
6414 super.incrementCountOrThrow(uid);
6415 } catch (IllegalStateException e) {
6416 throw new ServiceSpecificException(
6417 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
6418 "Uid " + uid + " exceeded its allotted requests limit");
6419 }
6420 }
6421
6422 @Override
6423 public synchronized void decrementCountOrThrow(int uid) {
6424 throw new UnsupportedOperationException("Use decrementCount instead.");
6425 }
6426
6427 public synchronized void decrementCount(int uid) {
6428 try {
6429 super.decrementCountOrThrow(uid);
6430 } catch (IllegalStateException e) {
6431 logwtf("Exception when decrement per uid request count: ", e);
6432 }
6433 }
6434 }
6435
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006436 // This checks that the passed capabilities either do not request a
6437 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006438 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006439 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006440 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006441 throw new SecurityException("Insufficient permissions to request a specific SSID");
6442 }
paulhu1a407652019-03-22 16:35:06 +08006443
6444 if (nc.hasSignalStrength()
6445 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6446 throw new SecurityException(
6447 "Insufficient permissions to request a specific signal strength");
6448 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006449 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006450
junyulai2217bec2021-04-14 23:33:31 +08006451 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006452 enforceNetworkFactoryPermission();
6453 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006454 }
6455
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006456 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006457 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006458 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006459 // mNetworkRequests may contain the same value multiple times in case of
6460 // multilayer requests. It won't matter in this case because the thresholds
6461 // will then be the same and be deduplicated as they enter the `thresholds` set.
6462 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006463 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6464 for (final NetworkRequest req : nri.mRequests) {
6465 if (req.networkCapabilities.hasSignalStrength()
6466 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6467 thresholds.add(req.networkCapabilities.getSignalStrength());
6468 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006469 }
6470 }
6471 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006472 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006473 }
6474
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006475 private void updateSignalStrengthThresholds(
6476 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006477 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006478
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006479 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006480 String detail;
6481 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6482 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6483 } else {
6484 detail = reason;
6485 }
6486 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006487 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006488 }
6489
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006490 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006491 }
6492
Chalard Jeandd421992021-12-16 23:16:02 +09006493 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07006494 if (nc == null) {
6495 return;
6496 }
6497 NetworkSpecifier ns = nc.getNetworkSpecifier();
6498 if (ns == null) {
6499 return;
6500 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006501 if (ns instanceof MatchAllNetworkSpecifier) {
6502 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6503 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006504 }
6505
Chalard Jeandd421992021-12-16 23:16:02 +09006506 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08006507 ensureValidNetworkSpecifier(nc);
6508 if (nc.isPrivateDnsBroken()) {
6509 throw new IllegalArgumentException("Can't request broken private DNS");
6510 }
Chalard Jeande665262022-02-25 16:12:12 +09006511 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09006512 throw new IllegalArgumentException("Can't request access UIDs");
6513 }
lucasline117e2e2019-10-22 18:27:33 +08006514 }
6515
Chalard Jeandd421992021-12-16 23:16:02 +09006516 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
6517 ensureListenableCapabilities(nc);
6518 final String badCapability = nc.describeFirstNonRequestableCapability();
6519 if (badCapability != null) {
6520 throw new IllegalArgumentException("Cannot request network with " + badCapability);
6521 }
6522 }
6523
Chiachang Wang3bc52762021-11-25 14:17:57 +08006524 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6525 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006526 private boolean isTargetSdkAtleast(int version, int callingUid,
6527 @NonNull String callingPackageName) {
6528 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006529 final PackageManager pm =
6530 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006531 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006532 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006533 if (callingVersion < version) return false;
6534 } catch (PackageManager.NameNotFoundException e) { }
6535 return true;
6536 }
6537
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006538 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006539 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006540 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006541 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006542 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006543 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006544 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6545 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006546 throw new SecurityException("Insufficient permissions to specify legacy type");
6547 }
markchienfac84a22020-03-18 21:16:15 +08006548 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006549 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006550 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006551 // Privileged callers can track the default network of another UID by passing in a UID.
6552 if (asUid != Process.INVALID_UID) {
6553 enforceSettingsPermission();
6554 } else {
6555 asUid = callingUid;
6556 }
junyulaiad010792021-01-11 16:53:38 +08006557 final NetworkRequest.Type reqType;
6558 try {
6559 reqType = NetworkRequest.Type.values()[reqTypeInt];
6560 } catch (ArrayIndexOutOfBoundsException e) {
6561 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6562 }
6563 switch (reqType) {
6564 case TRACK_DEFAULT:
6565 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006566 // is unused and will be replaced by ones appropriate for the UID (usually, the
6567 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006568 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006569 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006570 enforceAccessPermission();
6571 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006572 case TRACK_SYSTEM_DEFAULT:
6573 enforceSettingsPermission();
6574 networkCapabilities = new NetworkCapabilities(defaultNc);
6575 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006576 case BACKGROUND_REQUEST:
6577 enforceNetworkStackOrSettingsPermission();
6578 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006579 case REQUEST:
6580 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6581 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006582 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08006583 // TODO: this is incorrect. We mark the request as metered or not depending on
6584 // the state of the app when the request is filed, but we never change the
6585 // request if the app changes network state. http://b/29964605
6586 enforceMeteredApnPolicy(networkCapabilities);
6587 break;
junyulai1b1c8742021-03-12 20:05:08 +08006588 case LISTEN_FOR_BEST:
6589 enforceAccessPermission();
6590 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6591 break;
junyulaiad010792021-01-11 16:53:38 +08006592 default:
6593 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006594 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006595 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006596 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006597 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006598
junyulai1b1c8742021-03-12 20:05:08 +08006599 // Enforce FOREGROUND if the caller does not have permission to use background network.
6600 if (reqType == LISTEN_FOR_BEST) {
6601 restrictBackgroundRequestForCaller(networkCapabilities);
6602 }
6603
6604 // Set the UID range for this request to the single UID of the requester, unless the
6605 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006606 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6607 // are no visible methods to set the UIDs, an app could use reflection to try and get
6608 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006609 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006610 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6611 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006612
Etan Cohen85000162017-02-05 10:42:27 -08006613 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006614 throw new IllegalArgumentException("Bad timeout specified");
6615 }
Etan Cohen9786d922015-11-18 10:56:15 -08006616
James Mattis3ce3d3c2021-02-09 18:18:28 -08006617 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006618 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006619 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006620 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006621 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006622 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006623
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006624 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6625 // copied from the default request above. (This is necessary to ensure, for example, that
6626 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6627 // changes don't alter request matching.
6628 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6629 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006630 throw new IllegalStateException(
6631 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006632 + networkCapabilities + " vs. " + defaultNc);
6633 }
6634
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006635 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006636 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006637 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006638 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006639 }
6640 return networkRequest;
6641 }
6642
James Mattis3ce3d3c2021-02-09 18:18:28 -08006643 /**
6644 * Return the nri to be used when registering a network request. Specifically, this is used with
6645 * requests registered to track the default request. If there is currently a per-app default
6646 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6647 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006648 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6649 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006650 * @param nr the network request for the nri.
6651 * @param msgr the messenger for the nri.
6652 * @param binder the binder for the nri.
6653 * @param callingAttributionTag the calling attribution tag for the nri.
6654 * @return the nri to register.
6655 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006656 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006657 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006658 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006659 @Nullable String callingAttributionTag) {
6660 final List<NetworkRequest> requests;
6661 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6662 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006663 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006664 } else {
6665 requests = Collections.singletonList(nr);
6666 }
Roshan Pius951c0032020-12-22 15:10:42 -08006667 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006668 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006669 }
6670
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006671 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08006672 String callingPackageName, String callingAttributionTag, final int callingUid) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006673 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08006674 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
6675 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
6676 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
6677 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006678 }
junyulai96bd9fe2022-03-08 17:36:42 +08006679 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006680 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006681 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006682 }
6683 }
6684
fenglu3f357402015-03-20 11:29:56 -07006685 @Override
fenglub00f4882015-04-21 17:12:05 -07006686 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006687 enforceAccessPermission();
6688 NetworkAgentInfo nai = null;
6689 if (network == null) {
6690 return false;
6691 }
6692 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006693 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006694 }
6695 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006696 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006697 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006698 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006699 Integer uidReqs = mBandwidthRequests.get(uid);
6700 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006701 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006702 }
6703 mBandwidthRequests.put(uid, ++uidReqs);
6704 }
fenglu3f357402015-03-20 11:29:56 -07006705 return true;
6706 }
6707 return false;
6708 }
6709
Felipe Leme0a5ae422016-06-20 16:36:29 -07006710 private boolean isSystem(int uid) {
6711 return uid < Process.FIRST_APPLICATION_UID;
6712 }
fenglu3f357402015-03-20 11:29:56 -07006713
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006714 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006715 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006716 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006717 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006718 return;
6719 }
Hugo Benichi39621362017-02-11 17:04:43 +09006720 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6721 // Policy already enforced.
6722 return;
6723 }
paulhuaf50d7d2020-12-24 19:47:34 +08006724 final long ident = Binder.clearCallingIdentity();
6725 try {
6726 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6727 // If UID is restricted, don't allow them to bring up metered APNs.
6728 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6729 }
6730 } finally {
6731 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006732 }
6733 }
6734
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006735 @Override
6736 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006737 PendingIntent operation, @NonNull String callingPackageName,
6738 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006739 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006740 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006741 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006742 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006743 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006744 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006745 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006746 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006747 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006748 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6749 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09006750
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006751 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006752 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006753 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6754 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006755 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006756 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6757 nri));
6758 return networkRequest;
6759 }
6760
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006761 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6762 mHandler.sendMessageDelayed(
6763 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006764 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006765 }
6766
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006767 @Override
6768 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006769 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006770 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006771 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006772 }
6773
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006774 // In order to implement the compatibility measure for pre-M apps that call
6775 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6776 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6777 // This ensures it has permission to do so.
6778 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6779 if (nc == null) {
6780 return false;
6781 }
6782 int[] transportTypes = nc.getTransportTypes();
6783 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6784 return false;
6785 }
6786 try {
6787 mContext.enforceCallingOrSelfPermission(
6788 android.Manifest.permission.ACCESS_WIFI_STATE,
6789 "ConnectivityService");
6790 } catch (SecurityException e) {
6791 return false;
6792 }
6793 return true;
6794 }
6795
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006796 @Override
6797 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08006798 Messenger messenger, IBinder binder,
6799 @NetworkCallback.Flag int callbackFlags,
6800 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006801 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006802 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6803 enforceAccessPermission();
6804 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006805
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006806 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006807 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006808 Binder.getCallingPid(), callingUid, callingPackageName);
6809 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09006810 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6811 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6812 // onLost and onAvailable callbacks when networks move in and out of the background.
6813 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6814 // can't request networks.
6815 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09006816 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07006817
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006818 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006819 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08006820 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006821 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08006822 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006823 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006824
6825 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6826 return networkRequest;
6827 }
6828
6829 @Override
6830 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08006831 PendingIntent operation, @NonNull String callingPackageName,
6832 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006833 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006834 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04006835 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6836 enforceAccessPermission();
6837 }
Chalard Jeandd421992021-12-16 23:16:02 +09006838 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006839 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006840 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006841 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006842 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006843
6844 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006845 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006846 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6847 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006848 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04006849
WeiZhang1cc3f172021-06-03 19:02:04 -05006850 mHandler.sendMessage(mHandler.obtainMessage(
6851 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006852 }
6853
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006854 /** Returns the next Network provider ID. */
6855 public final int nextNetworkProviderId() {
6856 return mNextNetworkProviderId.getAndIncrement();
6857 }
6858
Erik Kline0c04b742016-07-07 16:50:58 +09006859 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006860 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006861 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09006862 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006863 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006864 }
6865
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006866 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6867 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006868 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6869 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6870 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08006871 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006872 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006873 return;
6874 }
6875
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006876 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6877 mNetworkProviderInfos.put(npi.messenger, npi);
6878 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006879 }
6880
6881 @Override
6882 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006883 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08006884 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006885 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08006886 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006887 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6888 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006889 }
6890
6891 @Override
6892 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006893 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006894 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006895 }
6896
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006897 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09006898 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006899 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6900 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09006901 Objects.requireNonNull(score);
6902 Objects.requireNonNull(caps);
6903 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09006904 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006905 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09006906 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
6907 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006908 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6909 }
6910
Chalard Jeanbb902a52021-08-18 01:35:19 +09006911 private void updateOfferScore(final NetworkOffer offer) {
6912 final boolean yieldToBadWiFi =
6913 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
6914 final NetworkOffer newOffer = new NetworkOffer(
6915 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
6916 offer.caps, offer.callback, offer.providerId);
6917 if (offer.equals(newOffer)) return;
6918 handleRegisterNetworkOffer(newOffer);
6919 }
6920
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006921 @Override
6922 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08006923 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006924 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6925 }
6926
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006927 private void handleUnregisterNetworkProvider(Messenger messenger) {
6928 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6929 if (npi == null) {
6930 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006931 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006932 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006933 // Unregister all the offers from this provider
6934 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6935 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09006936 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006937 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6938 toRemove.add(noi);
6939 }
6940 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09006941 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006942 handleUnregisterNetworkOffer(noi);
6943 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006944 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006945 }
6946
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006947 @Override
James Mattisf7027322020-12-13 16:28:14 -08006948 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006949 if (request.hasTransport(TRANSPORT_TEST)) {
6950 enforceNetworkFactoryOrTestNetworksPermission();
6951 } else {
6952 enforceNetworkFactoryPermission();
6953 }
James Mattisf7027322020-12-13 16:28:14 -08006954 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6955 if (nri != null) {
6956 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6957 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6958 mHandler.post(() -> handleReleaseNetworkRequest(
6959 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6960 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006961 }
6962
Paul Jensen1f567382015-02-13 14:18:39 -05006963 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6964 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006965 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05006966 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006967 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05006968 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006969 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006970
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09006971 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05006972 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006973 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006974
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006975 // UID ranges for users that are currently blocked by VPNs.
6976 // This array is accessed and iterated on multiple threads without holding locks, so its
6977 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6978 // (on the handler thread).
6979 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6980
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006981 // Must only be accessed on the handler thread
6982 @NonNull
6983 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6984
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006985 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006986 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006987
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006988 // Current OEM network preferences. This object must only be written to on the handler thread.
6989 // Since it is immutable and always non-null, other threads may read it if they only care
6990 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08006991 @NonNull
6992 private OemNetworkPreferences mOemNetworkPreferences =
6993 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006994 // Current per-profile network preferences. This object follows the same threading rules as
6995 // the OEM network preferences above.
6996 @NonNull
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006997 private ProfileNetworkPreferenceList mProfileNetworkPreferences =
6998 new ProfileNetworkPreferenceList();
James Mattis45d81842021-01-10 14:24:24 -08006999
paulhu51f77dc2021-06-07 02:34:20 +00007000 // A set of UIDs that should use mobile data preferentially if available. This object follows
7001 // the same threading rules as the OEM network preferences above.
7002 @NonNull
7003 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7004
James Mattiscb1e0362021-04-06 17:07:42 -07007005 // OemNetworkPreferences activity String log entries.
7006 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7007 @NonNull
7008 private final LocalLog mOemNetworkPreferencesLogs =
7009 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7010
James Mattis02220e22021-03-13 19:27:21 -08007011 /**
7012 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7013 * @param packageName the package name to check existence of a mapping for.
7014 * @return true if a mapping exists, false otherwise
7015 */
7016 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7017 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7018 }
7019
James Mattise3ef1912020-12-20 11:09:58 -08007020 // The always-on request for an Internet-capable network that apps without a specific default
7021 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007022 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007023 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007024 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007025 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007026 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007027 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007028 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007029
James Mattisd31bdfa2020-12-23 16:37:26 -08007030 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7031 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7032 }
7033
7034 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007035 * Return the default network request currently tracking the given uid.
7036 * @param uid the uid to check.
7037 * @return the NetworkRequestInfo tracking the given uid.
7038 */
7039 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007040 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007041 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007042 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007043 // Checking the first request is sufficient as only multilayer requests will have more
7044 // than one request and for multilayer, all requests will track the same uids.
7045 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007046 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007047 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007048 highestPriorityNri = nri;
7049 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007050 }
7051 }
paulhuaa0743d2021-05-26 21:56:03 +08007052 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007053 }
7054
7055 /**
7056 * Get a copy of the network requests of the default request that is currently tracking the
7057 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007058 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7059 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007060 * @param requestorUid the uid to check the default for.
7061 * @param requestorPackageName the requestor's package name.
7062 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7063 */
7064 @NonNull
7065 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007066 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007067 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007068 getDefaultRequestTrackingUid(asUid).mRequests,
7069 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007070 }
7071
7072 /**
7073 * Copy the given nri's NetworkRequest collection.
7074 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007075 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7076 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007077 * @param requestorUid the uid to set on the copied collection.
7078 * @param requestorPackageName the package name to set on the copied collection.
7079 * @return the copied NetworkRequest collection.
7080 */
7081 @NonNull
7082 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007083 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7084 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007085 final List<NetworkRequest> requests = new ArrayList<>();
7086 for (final NetworkRequest nr : requestsToCopy) {
7087 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007088 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007089 nr.legacyType, nextNetworkRequestId(), nr.type));
7090 }
7091 return requests;
7092 }
7093
7094 @NonNull
7095 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007096 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7097 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007098 // These capabilities are for a TRACK_DEFAULT callback, so:
7099 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7100 // mDefaultRequest and a per-UID default request.
7101 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007102 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007103 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007104 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7105 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007106 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007107 restrictRequestUidsForCallerAndSetRequestorInfo(
7108 netCap, requestorUid, requestorPackageName);
7109 return netCap;
7110 }
7111
7112 /**
7113 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7114 * @param nr the network request to check for equality against.
7115 * @return the nri if one exists, null otherwise.
7116 */
7117 @Nullable
7118 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7119 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7120 if (nri.getNetworkRequestForCallback().equals(nr)) {
7121 return nri;
7122 }
7123 }
7124 return null;
7125 }
7126
7127 /**
7128 * Check if an nri is currently being managed by per-app default networking.
7129 * @param nri the nri to check.
7130 * @return true if this nri is currently being managed by per-app default networking.
7131 */
7132 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7133 // nri.mRequests.get(0) is only different from the original request filed in
7134 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7135 // functionality therefore if these two don't match, it means this particular nri is
7136 // currently being managed by a per-app default.
7137 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7138 }
7139
7140 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007141 * Determine if an nri is a managed default request that disallows default networking.
7142 * @param nri the request to evaluate
7143 * @return true if device-default networking is disallowed
7144 */
7145 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7146 // Check if this nri is a managed default that supports the default network at its
7147 // lowest priority request.
7148 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7149 final NetworkCapabilities lowestPriorityNetCap =
7150 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7151 return isPerAppDefaultRequest(nri)
7152 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7153 lowestPriorityNetCap));
7154 }
7155
Erik Kline05f2b402015-04-30 12:58:40 +09007156 // Request used to optionally keep mobile data active even when higher
7157 // priority networks like Wi-Fi are active.
7158 private final NetworkRequest mDefaultMobileDataRequest;
7159
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007160 // Request used to optionally keep wifi data active even when higher
7161 // priority networks like ethernet are active.
7162 private final NetworkRequest mDefaultWifiRequest;
7163
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007164 // Request used to optionally keep vehicle internal network always active
7165 private final NetworkRequest mDefaultVehicleRequest;
7166
James Mattisd31bdfa2020-12-23 16:37:26 -08007167 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7168 // network with no service. This NAI should never be matched against, nor should any public API
7169 // ever return the associated network. For this reason, this NAI is not in the list of available
7170 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7171 // default requests that don't support using the device default network which will ultimately
7172 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7173 @VisibleForTesting
7174 final NetworkAgentInfo mNoServiceNetwork;
7175
Chalard Jean5b409c72021-02-04 13:12:59 +09007176 // The NetworkAgentInfo currently satisfying the default request, if any.
7177 private NetworkAgentInfo getDefaultNetwork() {
7178 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09007179 }
7180
James Mattis2516da32021-01-31 17:06:19 -08007181 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007182 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08007183 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7184 // Currently, all network requests will have the same uids therefore checking the first
7185 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007186 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08007187 if (null == uids) {
7188 continue;
7189 }
7190 for (final UidRange range : uids) {
7191 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08007192 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007193 highestPriorityNri = nri;
7194 }
James Mattis2516da32021-01-31 17:06:19 -08007195 }
7196 }
7197 }
paulhuaa0743d2021-05-26 21:56:03 +08007198 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08007199 }
7200
Varun Ananddf569952019-02-06 10:13:38 -08007201 @Nullable
7202 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
7203 return nai != null ? nai.network : null;
7204 }
7205
7206 private void ensureRunningOnConnectivityServiceThread() {
7207 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
7208 throw new IllegalStateException(
7209 "Not running on ConnectivityService thread: "
7210 + Thread.currentThread().getName());
7211 }
7212 }
7213
Chalard Jean3a3f5f22019-04-10 23:07:55 +09007214 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09007215 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
7216 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007217 }
7218
Chalard Jean29d06db2018-05-02 21:14:54 +09007219 /**
7220 * Register a new agent with ConnectivityService to handle a network.
7221 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007222 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09007223 * @param networkInfo the initial info associated with this network. It can be updated later :
7224 * see {@link #updateNetworkInfo}.
7225 * @param linkProperties the initial link properties of this network. They can be updated
7226 * later : see {@link #updateLinkProperties}.
7227 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007228 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007229 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007230 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007231 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007232 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007233 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007234 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007235 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007236 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7237 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007238 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7239 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7240 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007241 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007242 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007243 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08007244 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007245 } else {
7246 enforceNetworkFactoryPermission();
7247 }
7248
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007249 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007250 final long token = Binder.clearCallingIdentity();
7251 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007252 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007253 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007254 } finally {
7255 Binder.restoreCallingIdentity(token);
7256 }
7257 }
7258
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007259 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007260 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007261 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7262 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007263
Chalard Jeandbc46952022-02-02 00:14:18 +09007264 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
7265 // and mutate them at any time.
7266 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
7267 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
7268 final LinkProperties lpCopy = new LinkProperties(linkProperties);
7269
Chalard Jean366c5252022-01-25 18:27:53 +09007270 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09007271 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09007272 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7273 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007274 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09007275 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007276 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007277 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7278 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007279
Chalard Jeandbc46952022-02-02 00:14:18 +09007280 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09007281 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007282 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007283 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007284 mDeps.getNetworkStack().makeNetworkMonitor(
7285 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007286 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7287 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007288 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007289 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007290 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007291 }
7292
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007293 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007294 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007295 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09007296 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007297 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09007298 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
7299 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
7300 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09007301
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007302 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007303
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007304 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007305 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007306 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007307 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007308
7309 try {
7310 networkMonitor.start();
7311 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007312 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007313 }
Chalard Jean366c5252022-01-25 18:27:53 +09007314
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007315 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007316 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007317 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007318 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007319 }
7320
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007321 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7322 @NonNull public final NetworkOffer offer;
7323
7324 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7325 this.offer = offer;
7326 }
7327
7328 @Override
7329 public void binderDied() {
7330 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7331 }
7332 }
7333
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007334 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7335 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7336 if (npi.providerId == providerId) return true;
7337 }
7338 return false;
7339 }
7340
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007341 /**
7342 * Register or update a network offer.
7343 * @param newOffer The new offer. If the callback member is the same as an existing
7344 * offer, it is an update of that offer.
7345 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007346 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007347 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7348 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007349 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007350 // This may actually happen if a provider updates its score or registers and then
7351 // immediately unregisters. The offer would still be in the handler queue, but the
7352 // provider would have been removed.
7353 if (DBG) log("Received offer from an unregistered provider");
7354 return;
7355 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007356 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7357 if (null != existingOffer) {
7358 handleUnregisterNetworkOffer(existingOffer);
7359 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007360 if (DBG) {
7361 // handleUnregisterNetworkOffer has already logged the old offer
7362 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7363 }
7364 } else {
7365 if (DBG) {
7366 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7367 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007368 }
7369 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7370 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007371 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007372 } catch (RemoteException e) {
7373 noi.binderDied();
7374 return;
7375 }
7376 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007377 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007378 }
7379
7380 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7381 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007382 if (DBG) {
7383 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7384 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007385
7386 // If the provider removes the offer and dies immediately afterwards this
7387 // function may be called twice in a row, but the array will no longer contain
7388 // the offer.
7389 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007390 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007391 }
7392
7393 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7394 @NonNull final INetworkOfferCallback callback) {
7395 ensureRunningOnConnectivityServiceThread();
7396 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007397 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007398 }
7399 return null;
7400 }
7401
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007402 /**
7403 * Called when receiving LinkProperties directly from a NetworkAgent.
7404 * Stores into |nai| any data coming from the agent that might also be written to the network's
7405 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7406 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007407 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007408 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007409 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7410 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007411 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007412 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007413 }
7414
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007415 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007416 @NonNull LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007417 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007418
Lorenzo Colittid523d142020-04-01 20:16:30 +09007419 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7420 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7421 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007422 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007423
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007424 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007425
7426 // update filtering rules, need to happen after the interface update so netd knows about the
7427 // new interface (the interface name -> index map becomes initialized)
7428 updateVpnFiltering(newLp, oldLp, networkAgent);
7429
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007430 updateMtu(newLp, oldLp);
7431 // TODO - figure out what to do for clat
7432// for (LinkProperties lp : newLp.getStackedLinks()) {
7433// updateMtu(lp, null);
7434// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007435 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007436 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7437 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007438
Erik Klineb9888902016-04-05 13:30:49 +09007439 updateRoutes(newLp, oldLp, netId);
7440 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007441 // Make sure LinkProperties represents the latest private DNS status.
7442 // This does not need to be done before updateDnses because the
7443 // LinkProperties are not the source of the private DNS configuration.
7444 // updateDnses will fetch the private DNS configuration from DnsManager.
7445 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007446
Chalard Jean5b409c72021-02-04 13:12:59 +09007447 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007448 handleApplyDefaultProxy(newLp.getHttpProxy());
7449 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007450 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007451 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007452
7453 updateWakeOnLan(newLp);
7454
Hai Shalome58bdc62021-01-11 18:45:34 -08007455 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7456 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7457 // does, it needs to be merged here.
7458 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7459 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007460
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007461 // TODO - move this check to cover the whole function
7462 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007463 synchronized (networkAgent) {
7464 networkAgent.linkProperties = newLp;
7465 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007466 // Start or stop DNS64 detection and 464xlat according to network state.
7467 networkAgent.clatd.update();
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08007468 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007469 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7470 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09007471 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007472 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007473
7474 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007475 }
7476
Hai Shalome58bdc62021-01-11 18:45:34 -08007477 /**
7478 * @param naData captive portal data from NetworkAgent
7479 * @param apiData captive portal data from capport API
7480 */
7481 @Nullable
7482 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7483 CaptivePortalData apiData) {
7484 if (naData == null || apiData == null) {
7485 return naData == null ? apiData : naData;
7486 }
7487 final CaptivePortalData.Builder captivePortalBuilder =
7488 new CaptivePortalData.Builder(naData);
7489
7490 if (apiData.isCaptive()) {
7491 captivePortalBuilder.setCaptive(true);
7492 }
7493 if (apiData.isSessionExtendable()) {
7494 captivePortalBuilder.setSessionExtendable(true);
7495 }
7496 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7497 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7498 // otherwise data would be inconsistent. Prefer the capport API info if present,
7499 // as it can generally be refreshed more often.
7500 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7501 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7502 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7503 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7504 // No source has time / bytes remaining information: surface the newest refresh time
7505 // for other fields
7506 captivePortalBuilder.setRefreshTime(
7507 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7508 }
7509
Hai Shalom7c6ab402021-02-04 19:34:06 -08007510 // Prioritize the user portal URL from the network agent if the source is authenticated.
7511 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7512 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7513 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7514 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007515 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007516 // Prioritize the venue information URL from the network agent if the source is
7517 // authenticated.
7518 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7519 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7520 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7521 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007522 }
7523 return captivePortalBuilder.build();
7524 }
7525
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007526 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007527 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007528 // marks on unsupported interfaces is harmless.
7529 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7530 return;
7531 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007532
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007533 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7534 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7535
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007536 // Mask/mark of zero will not detect anything interesting.
7537 // Don't install rules unless both values are nonzero.
7538 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007539 return;
7540 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007541
7542 final String prefix = "iface:" + iface;
7543 try {
7544 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007545 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007546 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007547 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007548 }
7549 } catch (Exception e) {
7550 loge("Exception modifying wakeup packet monitoring: " + e);
7551 }
7552
Joel Scherpelza235a812017-05-22 13:47:41 +09007553 }
7554
Chalard Jean9589e722019-11-19 19:03:53 +09007555 private void updateInterfaces(final @Nullable LinkProperties newLp,
7556 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007557 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09007558 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fa7d9e2017-08-22 16:35:52 +01007559 oldLp != null ? oldLp.getAllInterfaceNames() : null,
7560 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jean9589e722019-11-19 19:03:53 +09007561 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007562 for (final String iface : interfaceDiff.added) {
7563 try {
7564 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007565 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09007566 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007567 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7568 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007569 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007570 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007571 }
Paul Jensenbff73492014-04-28 10:33:11 -04007572 }
7573 }
Chalard Jean9589e722019-11-19 19:03:53 +09007574 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007575 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007576 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007577 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007578 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007579 } catch (Exception e) {
7580 loge("Exception removing interface: " + e);
7581 }
7582 }
7583 }
7584
Tyler Weare4314862019-12-05 14:55:30 -08007585 // TODO: move to frameworks/libs/net.
7586 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7587 final String nextHop;
7588
7589 switch (route.getType()) {
7590 case RouteInfo.RTN_UNICAST:
7591 if (route.hasGateway()) {
7592 nextHop = route.getGateway().getHostAddress();
7593 } else {
7594 nextHop = INetd.NEXTHOP_NONE;
7595 }
7596 break;
7597 case RouteInfo.RTN_UNREACHABLE:
7598 nextHop = INetd.NEXTHOP_UNREACHABLE;
7599 break;
7600 case RouteInfo.RTN_THROW:
7601 nextHop = INetd.NEXTHOP_THROW;
7602 break;
7603 default:
7604 nextHop = INetd.NEXTHOP_NONE;
7605 break;
7606 }
7607
7608 final RouteInfoParcel rip = new RouteInfoParcel();
7609 rip.ifName = route.getInterface();
7610 rip.destination = route.getDestination().toString();
7611 rip.nextHop = nextHop;
7612 rip.mtu = route.getMtu();
7613
7614 return rip;
7615 }
7616
Paul Jensene0fd4a82014-08-06 15:51:33 -04007617 /**
7618 * Have netd update routes from oldLp to newLp.
7619 * @return true if routes changed between oldLp and newLp
7620 */
7621 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007622 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007623 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7624 new CompareOrUpdateResult<>(
7625 oldLp != null ? oldLp.getAllRoutes() : null,
7626 newLp != null ? newLp.getAllRoutes() : null,
7627 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007628
7629 // add routes before removing old in case it helps with continuous connectivity
7630
Chalard Jean9dd11612018-06-04 16:52:49 +09007631 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007632 for (RouteInfo route : routeDiff.added) {
7633 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007634 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007635 try {
Tyler Weare4314862019-12-05 14:55:30 -08007636 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007637 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007638 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007639 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007640 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007641 }
7642 }
7643 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007644 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007645 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007646 try {
Tyler Weare4314862019-12-05 14:55:30 -08007647 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007648 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007649 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007650 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007651 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007652 }
7653 }
7654
7655 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007656 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007657 try {
Tyler Weare4314862019-12-05 14:55:30 -08007658 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007659 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007660 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007661 }
7662 }
Tyler Weare4314862019-12-05 14:55:30 -08007663
7664 for (RouteInfo route : routeDiff.updated) {
7665 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7666 try {
7667 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7668 } catch (Exception e) {
7669 loge("Exception in networkUpdateRouteParcel: " + e);
7670 }
7671 }
7672 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7673 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007674 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007675
Erik Klineb9888902016-04-05 13:30:49 +09007676 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7677 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7678 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007679 }
Erik Klineb9888902016-04-05 13:30:49 +09007680
Erik Kline31b4a9e2018-01-11 21:07:29 +09007681 if (DBG) {
7682 final Collection<InetAddress> dnses = newLp.getDnsServers();
7683 log("Setting DNS servers for network " + netId + " to " + dnses);
7684 }
Erik Klineb9888902016-04-05 13:30:49 +09007685 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007686 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007687 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007688 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007689 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007690 }
Erik Kline54e35c02017-04-07 15:29:29 +09007691 }
7692
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007693 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7694 NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00007695 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
7696 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00007697 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
7698 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007699
7700 if (!wasFiltering && !needsFiltering) {
7701 // Nothing to do.
7702 return;
7703 }
7704
7705 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7706 // Nothing changed.
7707 return;
7708 }
7709
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007710 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00007711 if (ranges == null || ranges.isEmpty()) {
7712 return;
7713 }
7714
Qingxi Libb8da982020-01-17 17:54:27 -08007715 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007716 // TODO: this create a window of opportunity for apps to receive traffic between the time
7717 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007718 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007719 // old rules are being removed.
7720 if (wasFiltering) {
7721 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7722 }
7723 if (needsFiltering) {
7724 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7725 }
7726 }
7727
Valentin Iftime9fa35092019-09-24 13:32:13 +02007728 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007729 if (mWolSupportedInterfaces == null) {
7730 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007731 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007732 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007733 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7734 }
7735
Luke Huangb913c812018-08-24 20:33:16 +08007736 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007737 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007738 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007739 }
7740 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007741 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007742 }
Luke Huangb913c812018-08-24 20:33:16 +08007743 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007744 }
7745
Chalard Jean62edfd82019-12-02 18:39:29 +09007746 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7747 @NonNull final NetworkCapabilities newNc) {
7748 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7749 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09007750 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09007751 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007752 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08007753 } catch (RemoteException | ServiceSpecificException e) {
7754 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09007755 }
7756 }
7757 }
7758
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007759 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007760 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09007761 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007762 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08007763 underlyingNetworks = underlyingNetworksOrDefault(
7764 agentCaps.getOwnerUid(), underlyingNetworks);
lifrade6c2a2021-03-04 14:08:08 +08007765 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007766 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7767 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007768 // metered if any underlying is metered, or originally declared metered by the agent.
7769 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007770 boolean roaming = false; // roaming if any underlying is roaming
7771 boolean congested = false; // congested if any underlying is congested
7772 boolean suspended = true; // suspended if all underlying are suspended
7773
7774 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08007775 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007776 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08007777 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007778 for (Network underlyingNetwork : underlyingNetworks) {
7779 final NetworkAgentInfo underlying =
7780 getNetworkAgentInfoForNetwork(underlyingNetwork);
7781 if (underlying == null) continue;
7782
7783 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7784 hadUnderlyingNetworks = true;
7785 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007786 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007787 }
7788
7789 // Merge capabilities of this underlying network. For bandwidth, assume the
7790 // worst case.
7791 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7792 underlyingCaps.getLinkDownstreamBandwidthKbps());
7793 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7794 underlyingCaps.getLinkUpstreamBandwidthKbps());
7795 // If this underlying network is metered, the VPN is metered (it may cost money
7796 // to send packets on this network).
7797 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7798 // If this underlying network is roaming, the VPN is roaming (the billing structure
7799 // is different than the usual, local one).
7800 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7801 // If this underlying network is congested, the VPN is congested (the current
7802 // condition of the network affects the performance of this network).
7803 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7804 // If this network is not suspended, the VPN is not suspended (the VPN
7805 // is able to transfer some data).
7806 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08007807 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007808 }
7809 }
7810 if (!hadUnderlyingNetworks) {
7811 // No idea what the underlying networks are; assume reasonable defaults
7812 metered = true;
7813 roaming = false;
7814 congested = false;
7815 suspended = false;
7816 }
7817
lifrade6c2a2021-03-04 14:08:08 +08007818 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007819 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7820 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7821 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7822 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7823 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7824 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08007825 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007826 }
7827
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007828 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007829 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7830 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7831 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04007832 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007833 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007834 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09007835 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007836 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7837 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007838 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007839 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09007840 if (nai.everConnected()
7841 && !nai.isVPN()
7842 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007843 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09007844 // does not cause any request (that is not a listen) currently matching that agent to
7845 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007846 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09007847 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007848 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09007849 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007850 }
7851
Paul Jensen53f08952015-06-16 14:27:36 -04007852 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007853 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09007854 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007855 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007856 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007857 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007858 }
Chalard Jean254bd162022-08-25 13:04:51 +09007859 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007860 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007861 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007862 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007863 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007864 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007865 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007866 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007867 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007868 }
Chalard Jean254bd162022-08-25 13:04:51 +09007869 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08007870 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7871 } else {
7872 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7873 }
lucasline117e2e2019-10-22 18:27:33 +08007874 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007875
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007876 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09007877 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7878 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007879 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09007880 }
7881
Lorenzo Colittibd079452021-07-02 11:47:57 +09007882 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09007883 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09007884 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007885 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007886 }
7887
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007888 return newNc;
7889 }
7890
Lorenzo Colitti44840702021-01-11 22:27:57 +09007891 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7892 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7893 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7894 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7895 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7896 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7897 if (prevSuspended != suspended) {
7898 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7899 // onResumed have been removed.
7900 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7901 : ConnectivityManager.CALLBACK_RESUMED);
7902 }
7903 if (prevSuspended != suspended || prevRoaming != roaming) {
7904 // updateNetworkInfo will mix in the suspended info from the capabilities and
7905 // take appropriate action for the network having possibly changed state.
7906 updateNetworkInfo(nai, nai.networkInfo);
7907 }
7908 }
7909
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007910 /**
7911 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7912 *
7913 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7914 * capabilities we manage and store in {@code nai}, such as validated status and captive
7915 * portal status)
7916 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7917 * potentially triggers rematches.
7918 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7919 * change.)
7920 *
7921 * @param oldScore score of the network before any of the changes that prompted us
7922 * to call this function.
7923 * @param nai the network having its capabilities updated.
7924 * @param nc the new network capabilities.
7925 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007926 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09007927 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007928 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007929 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean62edfd82019-12-02 18:39:29 +09007930 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09007931 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007932
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007933 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09007934 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09007935 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007936
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007937 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007938 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7939 // the change we're processing can't affect any requests, it can only affect the listens
7940 // on this network. We might have been called by rematchNetworkAndRequests when a
7941 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09007942 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007943 } else {
7944 // If the requestable capabilities have changed or the score changed, we can't have been
7945 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09007946 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04007947 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07007948 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09007949 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007950
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007951 final boolean oldMetered = prevNc.isMetered();
7952 final boolean newMetered = newNc.isMetered();
7953 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08007954
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007955 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00007956 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7957 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007958 }
junyulaif2c67e42018-08-07 19:50:45 +08007959
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007960 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7961 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08007962
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007963 // Report changes that are interesting for network statistics tracking.
7964 if (meteredChanged || roamingChanged) {
7965 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06007966 }
7967
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007968 // This network might have been underlying another network. Propagate its capabilities.
7969 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08007970
7971 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007972 mDnsManager.updateTransportsForNetwork(
7973 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08007974 }
lucaslin53e8a262021-06-08 01:43:59 +08007975
7976 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007977 }
7978
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007979 /** Convenience method to update the capabilities for a given network. */
7980 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007981 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007982 }
7983
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007984 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00007985 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007986 *
7987 * Ingress interface filtering enforces that all apps under the given network can only receive
7988 * packets from the network's interface (and loopback). This is important for VPNs because
7989 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7990 * non-VPN interfaces.
7991 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00007992 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007993 * 1. the network is an app VPN (not legacy VPN)
7994 * 2. the VPN does not allow bypass
7995 * 3. the VPN is fully-routed
7996 * 4. the VPN interface is non-null
7997 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007998 * @see INetd#firewallAddUidInterfaceRules
7999 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008000 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008001 @Nullable
8002 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008003 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008004 if (nc == null || lp == null) return null;
8005 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008006 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008007 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008008 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008009 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008010 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008011 && !lp.hasExcludeRoute()) {
8012 return lp.getInterfaceName();
8013 }
8014 return null;
8015 }
8016
8017 /**
8018 * Returns whether we need to set interface filtering rule or not
8019 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008020 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008021 String isolationIface) {
8022 // Allow rules are always needed if VPN isolation is enabled.
8023 if (isolationIface != null) return true;
8024
8025 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8026 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8027 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
8028 return SdkLevel.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008029 }
8030
Chiachang Wang28afaff2020-12-10 22:24:47 +08008031 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8032 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8033 int index = 0;
8034 for (UidRange range : ranges) {
8035 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8036 index++;
8037 }
8038 return stableRanges;
8039 }
8040
Chalard Jeane6c95272022-01-25 21:04:21 +09008041 private static UidRangeParcel[] intsToUidRangeStableParcels(
8042 final @NonNull ArraySet<Integer> uids) {
8043 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8044 int index = 0;
8045 for (int uid : uids) {
8046 stableRanges[index] = new UidRangeParcel(uid, uid);
8047 index++;
8048 }
8049 return stableRanges;
8050 }
8051
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008052 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8053 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8054 for (int i = 0; i < ranges.length; i++) {
8055 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8056 }
8057 return stableRanges;
8058 }
8059
Ken Chen5e65a852020-12-24 12:59:10 +08008060 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
8061 int[] exemptUids) {
8062 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8063 try {
8064 mNetd.socketDestroy(ranges, exemptUids);
8065 } catch (Exception e) {
8066 loge("Exception in socket destroy: ", e);
8067 }
8068 }
8069 }
8070
paulhuaa0743d2021-05-26 21:56:03 +08008071 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08008072 int[] exemptUids = new int[2];
8073 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8074 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8075 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
8076 exemptUids[0] = VPN_UID;
8077 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
8078 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8079
8080 maybeCloseSockets(nai, ranges, exemptUids);
8081 try {
8082 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008083 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008084 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008085 } else {
paulhu0e79d952021-06-09 16:11:35 +08008086 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008087 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008088 }
8089 } catch (Exception e) {
8090 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8091 " on netId " + nai.network.netId + ". " + e);
8092 }
8093 maybeCloseSockets(nai, ranges, exemptUids);
8094 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008095
lucaslin53e8a262021-06-08 01:43:59 +08008096 private boolean isProxySetOnAnyDefaultNetwork() {
8097 ensureRunningOnConnectivityServiceThread();
8098 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8099 final NetworkAgentInfo nai = nri.getSatisfier();
8100 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8101 return true;
8102 }
8103 }
8104 return false;
8105 }
8106
8107 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8108 NetworkCapabilities newNc) {
8109 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8110 // the proxy might be changed since the default network satisfied by the apps might also
8111 // changed.
8112 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
8113 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09008114 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
8115 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09008116 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08008117 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
8118 mProxyTracker.sendProxyBroadcast();
8119 }
8120 }
8121
Chalard Jeane6c95272022-01-25 21:04:21 +09008122 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
8123 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008124 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
8125 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008126 if (null == prevRanges) prevRanges = new ArraySet<>();
8127 if (null == newRanges) newRanges = new ArraySet<>();
8128 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
8129
8130 prevRanges.removeAll(newRanges);
8131 newRanges.removeAll(prevRangesCopy);
8132
8133 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008134 // When updating the VPN uid routing rules, add the new range first then remove the old
8135 // range. If old range were removed first, there would be a window between the old
8136 // range being removed and the new range being added, during which UIDs contained
8137 // in both ranges are not subject to any VPN routing rules. Adding new range before
8138 // removing old range works because, unlike the filtering rules below, it's possible to
8139 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08008140 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
8141 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
8142 // [1-5] & [1-2],[4-5] == [3]
8143 // Then we can do:
8144 // maybeCloseSockets([3])
8145 // mNetd.networkAddUidRanges([1-2],[4-5])
8146 // mNetd.networkRemoveUidRanges([1-5])
8147 // maybeCloseSockets([3])
8148 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
8149 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09008150 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008151 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008152 }
8153 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008154 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008155 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00008156 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
8157 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008158 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
8159 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008160 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09008161 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008162 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
8163 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
8164 // were added first and then newRanges got removed later, there would be only one uid
8165 // 10013 left. A consequence of removing old ranges before adding new ranges is that
8166 // there is now a window of opportunity when the UIDs are not subject to any filtering.
8167 // Note that this is in contrast with the (more robust) update of VPN routing rules
8168 // above, where the addition of new ranges happens before the removal of old ranges.
8169 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
8170 // to be removed will never overlap with the new range to be added.
8171 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008172 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
8173 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008174 }
8175 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008176 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008177 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09008178 } catch (Exception e) {
8179 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008180 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008181 }
8182 }
8183
Chalard Jeande665262022-02-25 16:12:12 +09008184 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09008185 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
8186 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09008187 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
8188 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09008189 if (prevEmpty && newEmpty) return;
8190
8191 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09008192 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008193 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09008194 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008195
8196 if (prevUids.equals(newUids)) return;
8197
8198 // This implementation is very simple and vastly faster for sets of Integers than
8199 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
8200 // a key computed from the value and has storage for that.
8201 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
8202 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
8203 toRemove.removeAll(newUids);
8204 toAdd.removeAll(prevUids);
8205
8206 try {
8207 if (!toAdd.isEmpty()) {
8208 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
8209 nai.network.netId,
8210 intsToUidRangeStableParcels(toAdd),
8211 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8212 }
8213 if (!toRemove.isEmpty()) {
8214 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
8215 nai.network.netId,
8216 intsToUidRangeStableParcels(toRemove),
8217 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8218 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008219 } catch (ServiceSpecificException e) {
8220 // Has the interface disappeared since the network was built ?
8221 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09008222 } catch (RemoteException e) {
8223 // Netd died. This usually causes a runtime restart anyway.
8224 }
8225 }
8226
Hugo Benichi9d35b752017-09-01 01:23:32 +00008227 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008228 ensureRunningOnConnectivityServiceThread();
8229
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008230 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008231 // Ignore updates for disconnected networks
8232 return;
8233 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008234 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008235 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09008236 + "; created=" + nai.getCreatedTime()
8237 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00008238 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008239 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8240 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008241 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008242 }
8243
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008244 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8245 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008246 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008247 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008248 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008249 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8250 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8251 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008252 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8253 // need to be sent as a separate extra.
8254 final NetworkRequest req = nri.isMultilayerRequest()
8255 ? nri.getActiveRequest()
8256 // Non-multilayer listen requests do not have an active request
8257 : nri.mRequests.get(0);
8258 if (req == null) {
8259 Log.wtf(TAG, "No request in NRI " + nri);
8260 }
8261 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008262 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008263 sendIntent(nri.mPendingIntent, intent);
8264 }
8265 // else not handled
8266 }
8267
8268 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8269 mPendingIntentWakeLock.acquire();
8270 try {
8271 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00008272 final BroadcastOptions options = BroadcastOptions.makeBasic();
8273 if (SdkLevel.isAtLeastT()) {
8274 // Explicitly disallow the receiver from starting activities, to prevent apps from
8275 // utilizing the PendingIntent as a backdoor to do this.
8276 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
8277 }
8278 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
8279 null /* requiredPermission */,
8280 SdkLevel.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008281 } catch (PendingIntent.CanceledException e) {
8282 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8283 mPendingIntentWakeLock.release();
8284 releasePendingNetworkRequest(pendingIntent);
8285 }
8286 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8287 }
8288
8289 @Override
8290 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8291 String resultData, Bundle resultExtras) {
8292 if (DBG) log("Finished sending " + pendingIntent);
8293 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008294 // Release with a delay so the receiving client has an opportunity to put in its
8295 // own request.
8296 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008297 }
8298
Chalard Jean46bfbf02022-02-02 00:56:25 +09008299 // networkAgent is only allowed to be null if notificationType is
8300 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
8301 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08008302 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09008303 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08008304 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008305 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008306 // Default request has no msgr. Also prevents callbacks from being invoked for
8307 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8308 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8309 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008310 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008311 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008312 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008313 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008314 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008315 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008316 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008317 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8318 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008319 }
Roshan Pius951c0032020-12-22 15:10:42 -08008320 final boolean includeLocationSensitiveInfo =
8321 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008322 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008323 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008324 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08008325 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09008326 networkCapabilitiesRestrictedForCallerPermissions(
8327 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
8328 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008329 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09008330 nri.mCallingAttributionTag);
8331 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008332 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8333 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008334 // For this notification, arg1 contains the blocked status.
8335 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008336 break;
8337 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008338 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008339 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008340 break;
8341 }
8342 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008343 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008344 final NetworkCapabilities netCap =
8345 networkCapabilitiesRestrictedForCallerPermissions(
8346 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8347 putParcelable(
8348 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008349 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008350 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008351 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008352 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008353 break;
8354 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008355 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008356 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8357 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008358 break;
8359 }
junyulaif2c67e42018-08-07 19:50:45 +08008360 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008361 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008362 msg.arg1 = arg1;
8363 break;
8364 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008365 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008366 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008367 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008368 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008369 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008370 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008371 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008372 }
James Mattis45d81842021-01-10 14:24:24 -08008373 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008374 } catch (RemoteException e) {
8375 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008376 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008377 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008378 }
8379
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008380 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8381 bundle.putParcelable(t.getClass().getSimpleName(), t);
8382 }
8383
Chalard Jean0702f982021-09-16 21:50:07 +09008384 /**
8385 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8386 *
8387 * When a request should be assigned to a new network, it is normally lingered to give
8388 * time for apps to gracefully migrate their connections. When both networks are on the same
8389 * radio, but that radio can't do time-sharing efficiently, this may end up being
8390 * counter-productive because any traffic on the old network may drastically reduce the
8391 * performance of the new network.
8392 * The stack supports a configuration to let modem vendors state that their radio can't
8393 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8394 * from one cell network to another can't be done gracefully.
8395 *
8396 * @param oldNai the old network serving the request
8397 * @param newNai the new network serving the request
8398 * @return whether the switch can be graceful
8399 */
8400 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8401 @NonNull final NetworkAgentInfo newSatisfier) {
8402 if (mCellularRadioTimesharingCapable) return true;
8403 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8404 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8405 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8406 }
8407
Paul Jensenaf94b982014-09-30 15:37:41 -04008408 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008409 if (nai.numRequestNetworkRequests() != 0) {
8410 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8411 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008412 // Ignore listening and track default requests.
8413 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008414 loge("Dead network still had at least " + nr);
8415 break;
8416 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008417 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008418 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008419 }
8420
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008421 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8422 if (oldNetwork == null) {
8423 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8424 return;
8425 }
Chalard Jean49707572019-12-10 21:07:02 +09008426 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008427
8428 // If we get here it means that the last linger timeout for this network expired. So there
8429 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008430 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008431
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008432 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008433 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008434 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008435 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008436 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008437 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008438 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008439 }
8440
James Mattise3ef1912020-12-20 11:09:58 -08008441 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8442 boolean isDefaultChanged = false;
8443 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8444 final NetworkReassignment.RequestReassignment reassignment =
8445 changes.getReassignment(defaultRequestInfo);
8446 if (null == reassignment) {
8447 continue;
8448 }
8449 // reassignment only contains those instances where the satisfying network changed.
8450 isDefaultChanged = true;
8451 // Notify system services of the new default.
8452 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8453 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008454
James Mattise3ef1912020-12-20 11:09:58 -08008455 if (isDefaultChanged) {
8456 // Hold a wakelock for a short time to help apps in migrating to a new default.
8457 scheduleReleaseNetworkTransitionWakelock();
8458 }
8459 }
8460
8461 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8462 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8463 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8464 if (DBG) {
8465 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8466 }
Chalard Jean8e382112019-12-03 20:45:30 +09008467
James Mattisd31bdfa2020-12-23 16:37:26 -08008468 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8469 if (newDefaultNetwork != null) {
8470 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008471 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008472
James Mattisd31bdfa2020-12-23 16:37:26 -08008473 // Set an app level managed default and return since further processing only applies to the
8474 // default network.
8475 if (mDefaultRequest != nri) {
8476 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8477 return;
8478 }
8479
8480 makeDefaultNetwork(newDefaultNetwork);
8481
James Mattise3ef1912020-12-20 11:09:58 -08008482 if (oldDefaultNetwork != null) {
8483 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8484 }
8485 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008486 handleApplyDefaultProxy(null != newDefaultNetwork
8487 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8488 updateTcpBufferSizes(null != newDefaultNetwork
8489 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008490 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008491 }
8492
James Mattisd31bdfa2020-12-23 16:37:26 -08008493 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8494 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8495 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8496 try {
8497 if (VDBG) {
8498 log("Setting default network for " + nri
8499 + " using UIDs " + nri.getUids()
8500 + " with old network " + (oldDefaultNetwork != null
8501 ? oldDefaultNetwork.network().getNetId() : "null")
8502 + " and new network " + (newDefaultNetwork != null
8503 ? newDefaultNetwork.network().getNetId() : "null"));
8504 }
8505 if (nri.getUids().isEmpty()) {
8506 throw new IllegalStateException("makeDefaultForApps called without specifying"
8507 + " any applications to set as the default." + nri);
8508 }
8509 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008510 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008511 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008512 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008513 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008514 }
8515 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008516 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008517 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008518 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008519 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008520 }
8521 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008522 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008523 }
8524 }
8525
8526 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8527 try {
8528 if (null != newDefaultNetwork) {
8529 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8530 } else {
8531 mNetd.networkClearDefault();
8532 }
8533 } catch (RemoteException | ServiceSpecificException e) {
8534 loge("Exception setting default network :" + e);
8535 }
8536 }
8537
Chalard Jean05cbe972019-12-09 11:50:38 +09008538 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008539 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09008540 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09008541 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09008542 processNewlySatisfiedListenRequests(nai);
8543 }
8544
8545 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008546 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8547 if (nri.isMultilayerRequest()) {
8548 continue;
8549 }
8550 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008551 if (!nr.isListen()) continue;
8552 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08008553 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008554 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
8555 }
8556 }
Chalard Jeancd397a22019-11-22 22:33:33 +09008557 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008558
Chalard Jeancd397a22019-11-22 22:33:33 +09008559 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008560 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8561 if (nri.isMultilayerRequest()) {
8562 continue;
8563 }
8564 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008565 if (!nr.isListen()) continue;
8566 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
8567 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09008568 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008569 }
8570 }
8571 }
8572
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008573 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008574 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008575 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08008576 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09008577 @Nullable public final NetworkRequest mOldNetworkRequest;
8578 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008579 @Nullable public final NetworkAgentInfo mOldNetwork;
8580 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08008581 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008582 @Nullable final NetworkRequest oldNetworkRequest,
8583 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008584 @Nullable final NetworkAgentInfo oldNetwork,
8585 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008586 mNetworkRequestInfo = networkRequestInfo;
8587 mOldNetworkRequest = oldNetworkRequest;
8588 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008589 mOldNetwork = oldNetwork;
8590 mNewNetwork = newNetwork;
8591 }
Chalard Jean49707572019-12-10 21:07:02 +09008592
8593 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09008594 final NetworkRequest requestToShow = null != mNewNetworkRequest
8595 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
8596 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08008597 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
8598 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09008599 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008600 }
8601
Chalard Jean46a62372019-12-10 21:25:24 +09008602 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008603
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008604 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09008605 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008606 }
8607
8608 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09008609 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09008610 // The code is never supposed to add two reassignments of the same request. Make
8611 // sure this stays true, but without imposing this expensive check on all
8612 // reassignments on all user devices.
8613 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08008614 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09008615 throw new IllegalStateException("Trying to reassign ["
8616 + reassignment + "] but already have ["
8617 + existing + "]");
8618 }
8619 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09008620 }
Chalard Jean46a62372019-12-10 21:25:24 +09008621 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008622 }
8623
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008624 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09008625 // the passed request.
8626 @Nullable
8627 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008628 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008629 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008630 }
8631 return null;
8632 }
Chalard Jean49707572019-12-10 21:07:02 +09008633
8634 public String toString() {
8635 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8636 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09008637 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008638 for (final RequestReassignment rr : getRequestReassignments()) {
8639 sj.add(rr.toString());
8640 }
8641 return sj.toString();
8642 }
8643
8644 public String debugString() {
8645 final StringBuilder sb = new StringBuilder();
8646 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09008647 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008648 for (final RequestReassignment rr : getRequestReassignments()) {
8649 sb.append("\n ").append(rr);
8650 }
8651 return sb.append("\n").toString();
8652 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008653 }
8654
Chalard Jean24344d72019-12-04 13:32:31 +09008655 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008656 @Nullable final NetworkRequest previousRequest,
8657 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09008658 @Nullable final NetworkAgentInfo previousSatisfier,
8659 @Nullable final NetworkAgentInfo newSatisfier,
8660 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08008661 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09008662 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09008663 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008664 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008665 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09008666 }
James Mattisa076c532020-12-02 14:12:41 -08008667 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09008668 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09008669 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09008670 // If this network switch can't be supported gracefully, the request is not
8671 // lingered. This allows letting go of the network sooner to reclaim some
8672 // performance on the new network, since the radio can't do both at the same
8673 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09008674 //
8675 // Also don't linger the request if the old network has been destroyed.
8676 // A destroyed network does not provide actual network connectivity, so
8677 // lingering it is not useful. In particular this ensures that a destroyed
8678 // network is outscored by its replacement,
8679 // then it is torn down immediately instead of being lingered, and any apps that
8680 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09008681 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8682 }
Chalard Jean24344d72019-12-04 13:32:31 +09008683 } else {
8684 if (VDBG || DDBG) log(" accepting network in place of null");
8685 }
junyulai0ac374f2020-12-14 18:41:52 +08008686
8687 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8688 // and immediately satisfies a request then remove the timer. This will happen for
8689 // all networks except in the case of an underlying network for a VCN.
8690 if (newSatisfier.isNascent()) {
8691 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08008692 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008693 }
8694
Chalard Jean5d6e23b2021-03-01 22:00:20 +09008695 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08008696 newSatisfier.unlingerRequest(newRequest.requestId);
8697 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008698 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08008699 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008700 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09008701 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008702 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008703 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08008704 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008705 }
James Mattisa076c532020-12-02 14:12:41 -08008706 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008707 }
James Mattisa076c532020-12-02 14:12:41 -08008708 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008709 }
8710
James Mattisa076c532020-12-02 14:12:41 -08008711 /**
8712 * This function is triggered when something can affect what network should satisfy what
8713 * request, and it computes the network reassignment from the passed collection of requests to
8714 * network match to the one that the system should now have. That data is encoded in an
8715 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8716 * satisfier.
8717 *
8718 * After the reassignment is computed, it is applied to the state objects.
8719 *
8720 * @param networkRequests the nri objects to evaluate for possible network reassignment
8721 * @return NetworkReassignment listing of proposed network assignment changes
8722 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008723 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08008724 private NetworkReassignment computeNetworkReassignment(
8725 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09008726 final NetworkReassignment changes = new NetworkReassignment();
8727
Chalard Jeanc81d4c32021-04-07 17:06:19 +09008728 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09008729 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008730 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09008731 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09008732 }
Chalard Jean857a1712019-12-10 21:08:07 +09008733
James Mattisa076c532020-12-02 14:12:41 -08008734 for (final NetworkRequestInfo nri : networkRequests) {
8735 // Non-multilayer listen requests can be ignored.
8736 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8737 continue;
8738 }
8739 NetworkAgentInfo bestNetwork = null;
8740 NetworkRequest bestRequest = null;
8741 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09008742 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08008743 // Stop evaluating as the highest possible priority request is satisfied.
8744 if (null != bestNetwork) {
8745 bestRequest = req;
8746 break;
8747 }
8748 }
James Mattisd31bdfa2020-12-23 16:37:26 -08008749 if (null == bestNetwork && isDefaultBlocked(nri)) {
8750 // Remove default networking if disallowed for managed default requests.
8751 bestNetwork = mNoServiceNetwork;
8752 }
8753 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09008754 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09008755 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08008756 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09008757 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008758 }
8759 return changes;
8760 }
8761
James Mattisa076c532020-12-02 14:12:41 -08008762 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8763 return new HashSet<>(mNetworkRequests.values());
8764 }
8765
Paul Jensenc88b39b2015-06-16 14:27:36 -04008766 /**
James Mattisa076c532020-12-02 14:12:41 -08008767 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04008768 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04008769 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008770 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08008771 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8772 }
8773
8774 /**
8775 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8776 * being disconnected.
8777 */
8778 private void rematchNetworksAndRequests(
8779 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8780 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09008781 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09008782 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08008783 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09008784 final long computed = SystemClock.elapsedRealtime();
8785 applyNetworkReassignment(changes, start);
8786 final long applied = SystemClock.elapsedRealtime();
8787 issueNetworkNeeds();
8788 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09008789 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09008790 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
8791 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09008792 log(changes.debugString());
8793 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09008794 // Shorter form, only one line of log
8795 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
8796 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09008797 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09008798 }
Chalard Jean64520dc2019-12-04 19:55:32 +09008799
Chalard Jeand7f762d2019-12-10 19:01:29 +09008800 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008801 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008802 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09008803
8804 // Since most of the time there are only 0 or 1 background networks, it would probably
8805 // be more efficient to just use an ArrayList here. TODO : measure performance
8806 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8807 for (final NetworkAgentInfo nai : nais) {
8808 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8809 }
8810
Chalard Jeand7f762d2019-12-10 19:01:29 +09008811 // First, update the lists of satisfied requests in the network agents. This is necessary
8812 // because some code later depends on this state to be correct, most prominently computing
8813 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09008814 for (final NetworkReassignment.RequestReassignment event :
8815 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008816 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8817 event.mOldNetworkRequest, event.mNewNetworkRequest,
8818 event.mOldNetwork, event.mNewNetwork,
8819 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09008820 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008821
James Mattise3ef1912020-12-20 11:09:58 -08008822 // Process default network changes if applicable.
8823 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008824
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008825 // Notify requested networks are available after the default net is switched, but
8826 // before LegacyTypeTracker sends legacy broadcasts
8827 for (final NetworkReassignment.RequestReassignment event :
8828 changes.getRequestReassignments()) {
8829 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008830 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008831 } else {
James Mattisa076c532020-12-02 14:12:41 -08008832 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008833 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008834 }
8835 }
8836
junyulai0ac374f2020-12-14 18:41:52 +08008837 // Update the inactivity state before processing listen callbacks, because the background
8838 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008839 // just yet though, because they have to be sent after the listens are processed to keep
8840 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08008841 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09008842 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08008843 // Rematching may have altered the inactivity state of some networks, so update all
8844 // inactivity timers. updateInactivityState reads the state from the network agent
8845 // and does nothing if the state has not changed : the source of truth is controlled
8846 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8847 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08008848 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08008849 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008850 }
8851 }
8852
Chalard Jeanb10ab412019-12-11 14:12:30 +09008853 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008854 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008855 // Process listen requests and update capabilities if the background state has
8856 // changed for this network. For consistency with previous behavior, send onLost
8857 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09008858 processNewlyLostListenRequests(nai);
8859 if (oldBackground != nai.isBackgroundNetwork()) {
8860 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008861 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09008862 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008863 }
8864
junyulai0ac374f2020-12-14 18:41:52 +08008865 for (final NetworkAgentInfo nai : inactiveNetworks) {
8866 // For nascent networks, if connecting with no foreground request, skip broadcasting
8867 // LOSING for backward compatibility. This is typical when mobile data connected while
8868 // wifi connected with mobile data always-on enabled.
8869 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008870 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008871 }
8872
James Mattise3ef1912020-12-20 11:09:58 -08008873 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09008874
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008875 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008876 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008877 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08008878 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008879 // This network has active linger timers and no requests, but is not
8880 // lingering. Linger it.
8881 //
8882 // One way (the only way?) this can happen if this network is unvalidated
8883 // and became unneeded due to another network improving its score to the
8884 // point where this network will no longer be able to satisfy any requests
8885 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08008886 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008887 notifyNetworkLosing(nai, now);
8888 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09008889 } else {
Chalard Jean49707572019-12-10 21:07:02 +09008890 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09008891 teardownUnneededNetwork(nai);
8892 }
8893 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04008894 }
8895 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008896
Chalard Jean62edfd82019-12-02 18:39:29 +09008897 /**
8898 * Apply a change in background state resulting from rematching networks with requests.
8899 *
8900 * During rematch, a network may change background states by starting to satisfy or stopping
8901 * to satisfy a foreground request. Listens don't count for this. When a network changes
8902 * background states, its capabilities need to be updated and callbacks fired for the
8903 * capability change.
8904 *
8905 * @param nai The network that changed background states
8906 */
8907 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8908 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8909 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8910 updateNetworkPermissions(nai, newNc);
8911 nai.getAndSetNetworkCapabilities(newNc);
8912 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8913 }
8914
Chalard Jeanf0344532019-11-19 19:23:38 +09008915 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08008916 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008917 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09008918 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8919 changes.getReassignment(mDefaultRequest);
8920 final NetworkAgentInfo oldDefaultNetwork =
8921 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8922 final NetworkAgentInfo newDefaultNetwork =
8923 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08008924
Chalard Jean5b409c72021-02-04 13:12:59 +09008925 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008926 // Maintain the illusion : since the legacy API only understands one network at a time,
8927 // if the default network changed, apps should see a disconnected broadcast for the
8928 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09008929 if (oldDefaultNetwork != null) {
8930 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8931 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008932 }
Chalard Jean5b409c72021-02-04 13:12:59 +09008933 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008934 // The new default network can be newly null if and only if the old default
8935 // network doesn't satisfy the default request any more because it lost a
8936 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09008937 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08008938 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09008939 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008940 }
8941 }
8942
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008943 // Now that all the callbacks have been sent, send the legacy network broadcasts
8944 // as needed. This is necessary so that legacy requests correctly bind dns
8945 // requests to this network. The legacy users are listening for this broadcast
8946 // and will generally do a dns request so they can ensureRouteToHost and if
8947 // they do that before the callbacks happen they'll use the default network.
8948 //
8949 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8950 // callbacks, but if apps can receive the broadcast before the callback, they still might
8951 // have an inconsistent view of networking.
8952 //
8953 // This *does* introduce a race where if the user uses the new api
8954 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8955 // they may get old info. Reverse this after the old startUsing api is removed.
8956 // This is on top of the multiple intent sequencing referenced in the todo above.
8957 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09008958 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008959 addNetworkToLegacyTypeTracker(nai);
8960 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08008961 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008962 }
8963
Chalard Jean0354d8c2021-01-12 10:58:56 +09008964 private void issueNetworkNeeds() {
8965 ensureRunningOnConnectivityServiceThread();
8966 for (final NetworkOfferInfo noi : mNetworkOffers) {
8967 issueNetworkNeeds(noi);
8968 }
8969 }
8970
8971 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8972 ensureRunningOnConnectivityServiceThread();
8973 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8974 informOffer(nri, noi.offer, mNetworkRanker);
8975 }
8976 }
8977
8978 /**
8979 * Inform a NetworkOffer about any new situation of a request.
8980 *
8981 * This function handles updates to offers. A number of events may happen that require
8982 * updating the registrant for this offer about the situation :
8983 * • The offer itself was updated. This may lead the offer to no longer being able
8984 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8985 * or conversely being strengthened enough to beat the satisfier (and therefore
8986 * start being needed)
8987 * • The network satisfying a request changed (including cases where the request
8988 * starts or stops being satisfied). The new network may be a stronger or weaker
8989 * match than the old one, possibly affecting whether the offer is needed.
8990 * • The network satisfying a request updated their score. This may lead the offer
8991 * to no longer be able to beat it if the current satisfier got better, or
8992 * conversely start being a good choice if the current satisfier got weaker.
8993 *
8994 * @param nri The request
8995 * @param offer The offer. This may be an updated offer.
8996 */
8997 private static void informOffer(@NonNull NetworkRequestInfo nri,
8998 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
8999 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9000 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009001
9002 // Multi-layer requests have a currently active request, the one being satisfied.
9003 // Since the system will try to bring up a better network than is currently satisfying
9004 // the request, NetworkProviders need to be told the offers matching the requests *above*
9005 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9006 // not needed, and the offer is needed for the active request iff the offer can beat
9007 // the satisfier.
9008 // For non-multilayer requests, the logic above gracefully degenerates to only the
9009 // last case.
9010 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9011 // providers that the offer is needed for this request, until the active request is found.
9012 // In a second phase, deal with the currently active request. In a third phase, inform
9013 // the providers that offer is unneeded for the remaining requests.
9014
9015 // First phase : inform providers of all requests above the active request.
9016 int i;
9017 for (i = 0; nri.mRequests.size() > i; ++i) {
9018 final NetworkRequest request = nri.mRequests.get(i);
9019 if (activeRequest == request) break; // Found the active request : go to phase 2
9020 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9021 // Since this request is higher-priority than the one currently satisfied, if the
9022 // offer can satisfy it, the provider should try and bring up the network for sure ;
9023 // no need to even ask the ranker – an offer that can satisfy is always better than
9024 // no network. Hence tell the provider so unless it already knew.
9025 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
9026 offer.onNetworkNeeded(request);
9027 }
9028 }
9029
9030 // Second phase : deal with the active request (if any)
9031 if (null != activeRequest && activeRequest.isRequest()) {
9032 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00009033 // If an offer can satisfy the request, it is considered needed if it is currently
9034 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09009035 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00009036 && satisfier.factorySerialNumber == offer.providerId
9037 && activeRequest.canBeSatisfiedBy(offer.caps);
9038 final boolean newNeeded = currentlyServing
9039 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09009040 if (newNeeded != oldNeeded) {
9041 if (newNeeded) {
9042 offer.onNetworkNeeded(activeRequest);
9043 } else {
9044 // The offer used to be able to beat the satisfier. Now it can't.
9045 offer.onNetworkUnneeded(activeRequest);
9046 }
9047 }
9048 }
9049
9050 // Third phase : inform the providers that the offer isn't needed for any request
9051 // below the active one.
9052 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
9053 final NetworkRequest request = nri.mRequests.get(i);
9054 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9055 // Since this request is lower-priority than the one currently satisfied, if the
9056 // offer can satisfy it, the provider should not try and bring up the network.
9057 // Hence tell the provider so unless it already knew.
9058 if (offer.neededFor(request)) {
9059 offer.onNetworkUnneeded(request);
9060 }
9061 }
9062 }
9063
Chalard Jean61c79252019-11-07 23:07:32 +09009064 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
9065 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9066 NetworkRequest nr = nai.requestAt(i);
9067 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
9068 // legacy type tracker filters out repeat adds
9069 mLegacyTypeTracker.add(nr.legacyType, nai);
9070 }
9071 }
9072
9073 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09009074 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09009075 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
9076 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
9077 if (nai.isVPN()) {
9078 mLegacyTypeTracker.add(TYPE_VPN, nai);
9079 }
9080 }
9081
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09009082 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04009083 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +09009084 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09009085 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04009086 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09009087 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009088
Chalard Jean254bd162022-08-25 13:04:51 +09009089 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009090 // Don't repeat publish.
9091 if (newInetCondition == mDefaultInetConditionPublished) return;
9092
9093 mDefaultInetConditionPublished = newInetCondition;
9094 sendInetConditionBroadcast(nai.networkInfo);
9095 }
9096
Chalard Jeand61375d2020-01-14 22:46:36 +09009097 @NonNull
9098 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
9099 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009100 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09009101 final boolean suspended =
9102 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9103 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
9104 // Only override the state with SUSPENDED if the network is currently in CONNECTED
9105 // state. This is because the network could have been suspended before connecting,
9106 // or it could be disconnecting while being suspended, and in both these cases
9107 // the state should not be overridden. Note that the only detailed state that
9108 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
9109 // worry about multiple different substates of CONNECTED.
9110 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
9111 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009112 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
9113 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
9114 // network agent is created, then goes to suspended, then goes out of suspended without
9115 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +09009116 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009117 ? NetworkInfo.DetailedState.CONNECTED
9118 : NetworkInfo.DetailedState.CONNECTING,
9119 info.getReason(),
9120 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09009121 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009122 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09009123 return newInfo;
9124 }
9125
9126 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
9127 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
9128
Erik Kline99f301b2017-02-15 19:59:17 +09009129 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009130 NetworkInfo oldInfo = null;
9131 synchronized (networkAgent) {
9132 oldInfo = networkAgent.networkInfo;
9133 networkAgent.networkInfo = newInfo;
9134 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009135
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009136 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009137 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
9138 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009139 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009140
Chalard Jean254bd162022-08-25 13:04:51 +09009141 if (!networkAgent.isCreated()
Robin Leea8c0b6e2016-05-01 23:00:00 +01009142 && (state == NetworkInfo.State.CONNECTED
9143 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009144
9145 // A network that has just connected has zero requests and is thus a foreground network.
9146 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
9147
Luke Huangfdd11f82019-04-09 18:41:49 +08009148 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09009149 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009150 // Initialize the network's capabilities to their starting values according to the
9151 // underlying networks. This ensures that the capabilities are correct before
9152 // anything happens to the network.
9153 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09009154 }
Chalard Jean254bd162022-08-25 13:04:51 +09009155 networkAgent.setCreated();
Chiachang Wang3f6cc072021-03-24 18:39:17 +08009156 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +09009157 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Robin Leea8c0b6e2016-05-01 23:00:00 +01009158 }
9159
Chalard Jean254bd162022-08-25 13:04:51 +09009160 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
9161 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009162
lucaslin45e639b2019-04-03 17:09:28 +08009163 // NetworkCapabilities need to be set before sending the private DNS config to
9164 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09009165 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
9166
Erik Kline9a62f012018-03-21 07:18:33 -07009167 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08009168 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
9169 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009170
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +01009171 // If a rate limit has been configured and is applicable to this network (network
9172 // provides internet connectivity), apply it. The tc police filter cannot be attached
9173 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
9174 // updateInterfaces -> INetd#networkAddInterface.
9175 // Note: in case of a system server crash, the NetworkController constructor in netd
9176 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
9177 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
9178 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
9179 mIngressRateLimit);
9180 }
9181
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009182 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
9183 // command must be sent after updating LinkProperties to maximize chances of
9184 // NetworkMonitor seeing the correct LinkProperties when starting.
9185 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009186 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09009187 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009188 }
Chalard Jeand4900722022-02-06 12:25:38 +09009189 final NetworkMonitorParameters params = new NetworkMonitorParameters();
9190 params.networkAgentConfig = networkAgent.networkAgentConfig;
9191 params.networkCapabilities = networkAgent.networkCapabilities;
9192 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
9193 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +09009194 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
9195 // newer callback even before T. However getInterfaceVersion is a synchronized binder
9196 // call that would cause a Log.wtf to be emitted from the system_server process, and
9197 // in the absence of a satisfactory, scalable solution which follows an easy/standard
9198 // process to check the interface version, just use an SDK check. NetworkStack will
9199 // always be new enough when running on T+.
9200 if (SdkLevel.isAtLeastT()) {
9201 networkAgent.networkMonitor().notifyNetworkConnected(params);
9202 } else {
9203 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
9204 params.networkCapabilities);
9205 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09009206 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009207
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009208 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
9209 // be communicated to a particular NetworkAgent depends only on the network's immutable,
9210 // capabilities, so it only needs to be done once on initial connect, not every time the
9211 // network's capabilities change. Note that we do this before rematching the network,
9212 // so we could decide to tear it down immediately afterwards. That's fine though - on
9213 // disconnection NetworkAgents should stop any signal strength monitoring they have been
9214 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09009215 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009216
junyulai0ac374f2020-12-14 18:41:52 +08009217 // Before first rematching networks, put an inactivity timer without any request, this
9218 // allows {@code updateInactivityState} to update the state accordingly and prevent
9219 // tearing down for any {@code unneeded} evaluation in this period.
9220 // Note that the timer will not be rescheduled since the expiry time is
9221 // fixed after connection regardless of the network satisfying other requests or not.
9222 // But it will be removed as soon as the network satisfies a request for the first time.
9223 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
9224 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08009225 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009226
Paul Jensen05e85ee2014-09-11 11:00:39 -04009227 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009228 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009229
9230 // This has to happen after matching the requests, because callbacks are just requests.
9231 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009232 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009233 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04009234 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009235 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04009236 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09009237 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00009238 if (networkAgent.isVPN()) {
9239 // As the active or bound network changes for apps, broadcast the default proxy, as
9240 // apps may need to update their proxy data. This is called after disconnecting from
9241 // VPN to make sure we do not broadcast the old proxy data.
9242 // TODO(b/122649188): send the broadcast only to VPN users.
9243 mProxyTracker.sendProxyBroadcast();
9244 }
Chalard Jean254bd162022-08-25 13:04:51 +09009245 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
9246 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009247 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009248 }
9249 }
9250
Chalard Jean28018572020-12-21 18:36:52 +09009251 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09009252 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
9253 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009254 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07009255 }
9256
Erik Kline99f301b2017-02-15 19:59:17 +09009257 // Notify only this one new request of the current state. Transfer all the
9258 // current state by calling NetworkCapabilities and LinkProperties callbacks
9259 // so that callers can be guaranteed to have as close to atomicity in state
9260 // transfer as can be supported by this current API.
9261 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07009262 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09009263 if (nri.mPendingIntent != null) {
9264 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
9265 // Attempt no subsequent state pushes where intents are involved.
9266 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009267 }
Erik Kline99f301b2017-02-15 19:59:17 +09009268
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009269 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08009270 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009271 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
9272 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
9273 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08009274 }
9275
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009276 // Notify the requests on this NAI that the network is now lingered.
9277 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08009278 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009279 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
9280 }
9281
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009282 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
9283 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
9284 return vpnBlocked
9285 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
9286 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
9287 }
9288
9289 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
9290 if (blockedReasons == BLOCKED_REASON_NONE) {
9291 mUidBlockedReasons.delete(uid);
9292 } else {
9293 mUidBlockedReasons.put(uid, blockedReasons);
9294 }
9295 }
9296
junyulaif2c67e42018-08-07 19:50:45 +08009297 /**
9298 * Notify of the blocked state apps with a registered callback matching a given NAI.
9299 *
9300 * Unlike other callbacks, blocked status is different between each individual uid. So for
9301 * any given nai, all requests need to be considered according to the uid who filed it.
9302 *
9303 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009304 * @param oldMetered True if the previous network capabilities were metered.
9305 * @param newMetered True if the current network capabilities are metered.
9306 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
9307 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08009308 */
9309 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00009310 boolean newMetered, List<UidRange> oldBlockedUidRanges,
9311 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08009312
9313 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9314 NetworkRequest nr = nai.requestAt(i);
9315 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009316
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009317 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9318 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9319 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009320 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009321 : oldVpnBlocked;
9322
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009323 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9324 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9325 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009326 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009327 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009328 }
9329 }
9330 }
9331
9332 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009333 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009334 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009335 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009336 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009337 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009338 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009339 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009340 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009341
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009342 final int oldBlockedState = getBlockedState(
9343 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9344 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9345 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009346 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009347 }
junyulaif2c67e42018-08-07 19:50:45 +08009348 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9349 NetworkRequest nr = nai.requestAt(i);
9350 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009351 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009352 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
9353 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009354 }
9355 }
9356 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009357 }
9358
Chalard Jean3a3f5f22019-04-10 23:07:55 +09009359 @VisibleForTesting
9360 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09009361 // The NetworkInfo we actually send out has no bearing on the real
9362 // state of affairs. For example, if the default connection is mobile,
9363 // and a request for HIPRI has just gone away, we need to pretend that
9364 // HIPRI has just disconnected. So we need to set the type to HIPRI and
9365 // the state to DISCONNECTED, even though the network is of type MOBILE
9366 // and is still connected.
9367 NetworkInfo info = new NetworkInfo(nai.networkInfo);
9368 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09009369 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009370 if (state != DetailedState.DISCONNECTED) {
9371 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09009372 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009373 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009374 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07009375 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
9376 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
9377 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
9378 if (info.isFailover()) {
9379 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
9380 nai.networkInfo.setFailover(false);
9381 }
9382 if (info.getReason() != null) {
9383 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
9384 }
9385 if (info.getExtraInfo() != null) {
9386 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
9387 }
9388 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09009389 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08009390 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07009391 if (newDefaultAgent != null) {
9392 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
9393 newDefaultAgent.networkInfo);
9394 } else {
9395 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
9396 }
9397 }
9398 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
9399 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09009400 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009401 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09009402 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009403 }
9404 }
9405 }
9406
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009407 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009408 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009409 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09009410 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09009411 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009412 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
9413 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009414 NetworkRequestInfo nri = mNetworkRequests.get(nr);
9415 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009416 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009417 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009418 } else {
9419 sendPendingIntentForRequest(nri, networkAgent, notifyType);
9420 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009421 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009422 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009423
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009424 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
9425 notifyNetworkCallbacks(networkAgent, notifyType, 0);
9426 }
9427
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009428 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09009429 * Returns the list of all interfaces that could be used by network traffic that does not
9430 * explicitly specify a network. This includes the default network, but also all VPNs that are
9431 * currently connected.
9432 *
9433 * Must be called on the handler thread.
9434 */
junyulaie7c7d2a2021-01-26 15:29:15 +08009435 @NonNull
9436 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009437 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08009438 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08009439 final Set<Integer> activeNetIds = new ArraySet<>();
9440 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9441 if (nri.isBeingSatisfied()) {
9442 activeNetIds.add(nri.getSatisfier().network().netId);
9443 }
9444 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009445 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +09009446 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09009447 defaultNetworks.add(nai.network);
9448 }
9449 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009450 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09009451 }
9452
9453 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09009454 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
9455 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009456 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08009457 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009458 ensureRunningOnConnectivityServiceThread();
9459 String activeIface = null;
9460 LinkProperties activeLinkProperties = getActiveLinkProperties();
9461 if (activeLinkProperties != null) {
9462 activeIface = activeLinkProperties.getInterfaceName();
9463 }
Benedict Wong9308cd32019-06-12 17:46:31 +00009464
junyulai2050bed2021-01-23 09:46:34 +08009465 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009466 try {
junyulaide41fc22021-01-22 22:46:01 +08009467 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +09009468 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +08009469 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
9470 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009471 } catch (Exception ignored) {
9472 }
9473 }
9474
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07009475 @Override
Udam Sainicd645462016-01-04 12:16:14 -08009476 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08009477 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009478 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009479 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009480
9481 if (!TextUtils.isEmpty(settingUrl)) {
9482 return settingUrl;
9483 }
9484
9485 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009486 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009487 if (!TextUtils.isEmpty(settingUrl)) {
9488 return settingUrl;
9489 }
9490
9491 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009492 }
9493
9494 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009495 public void startNattKeepalive(Network network, int intervalSeconds,
9496 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009497 enforceKeepalivePermission();
9498 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009499 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai070f9ff2019-01-16 20:23:34 +08009500 intervalSeconds, cb,
junyulai011b1f12019-01-03 18:50:15 +08009501 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009502 }
9503
9504 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009505 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009506 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulaid05a1922019-01-15 11:32:44 +08009507 String dstAddr) {
Josh Gao461a1222020-06-16 15:58:11 -07009508 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009509 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009510 mKeepaliveTracker.startNattKeepalive(
9511 getNetworkAgentInfoForNetwork(network), fd, resourceId,
9512 intervalSeconds, cb,
9513 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
9514 } finally {
9515 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9516 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009517 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9518 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009519 }
9520 }
junyulaid05a1922019-01-15 11:32:44 +08009521 }
9522
9523 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009524 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009525 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009526 try {
9527 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08009528 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009529 mKeepaliveTracker.startTcpKeepalive(
9530 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
9531 } finally {
9532 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9533 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009534 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9535 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009536 }
9537 }
junyulai0835a1e2019-01-08 20:04:33 +08009538 }
9539
9540 @Override
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009541 public void stopKeepalive(Network network, int slot) {
9542 mHandler.sendMessage(mHandler.obtainMessage(
junyulai011b1f12019-01-03 18:50:15 +08009543 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009544 }
9545
9546 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07009547 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08009548 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07009549
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009550 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08009551 final long token = Binder.clearCallingIdentity();
9552 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009553 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
9554 UserHandle.getUserHandleForUid(uid))) {
9555 return;
9556 }
9557
Heemin Seogdb8489d2019-06-12 09:21:44 -07009558 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
9559 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009560
9561 // Turn airplane mode off
9562 setAirplaneMode(false);
9563
9564 // restore private DNS settings to default mode (opportunistic)
9565 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
9566 UserHandle.getUserHandleForUid(uid))) {
9567 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
9568 PRIVATE_DNS_MODE_OPPORTUNISTIC);
9569 }
9570
9571 Settings.Global.putString(mContext.getContentResolver(),
9572 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08009573 } finally {
9574 Binder.restoreCallingIdentity(token);
9575 }
Stuart Scottd5463642015-04-02 18:00:02 -07009576 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04009577
Ricky Wai7097cc92018-01-23 04:09:45 +00009578 @Override
9579 public byte[] getNetworkWatchlistConfigHash() {
9580 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
9581 if (nwm == null) {
9582 loge("Unable to get NetworkWatchlistManager");
9583 return null;
9584 }
9585 // Redirect it to network watchlist service to access watchlist file and calculate hash.
9586 return nwm.getWatchlistConfigHash();
9587 }
9588
Hugo Benichibe0c7652016-05-31 16:28:06 +09009589 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09009590 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08009591 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09009592 }
Hugo Benichif4210292017-04-21 15:07:12 +09009593
9594 private static boolean toBool(int encodedBoolean) {
9595 return encodedBoolean != 0; // Only 0 means false.
9596 }
9597
9598 private static int encodeBool(boolean b) {
9599 return b ? 1 : 0;
9600 }
mswest4632928412018-03-12 10:34:34 -07009601
9602 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009603 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
9604 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
9605 @NonNull String[] args) {
9606 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
9607 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07009608 }
9609
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009610 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07009611 @Override
9612 public int onCommand(String cmd) {
9613 if (cmd == null) {
9614 return handleDefaultCommands(cmd);
9615 }
9616 final PrintWriter pw = getOutPrintWriter();
9617 try {
9618 switch (cmd) {
9619 case "airplane-mode":
9620 final String action = getNextArg();
9621 if ("enable".equals(action)) {
9622 setAirplaneMode(true);
9623 return 0;
9624 } else if ("disable".equals(action)) {
9625 setAirplaneMode(false);
9626 return 0;
9627 } else if (action == null) {
9628 final ContentResolver cr = mContext.getContentResolver();
9629 final int enabled = Settings.Global.getInt(cr,
9630 Settings.Global.AIRPLANE_MODE_ON);
9631 pw.println(enabled == 0 ? "disabled" : "enabled");
9632 return 0;
9633 } else {
9634 onHelp();
9635 return -1;
9636 }
9637 default:
9638 return handleDefaultCommands(cmd);
9639 }
9640 } catch (Exception e) {
9641 pw.println(e);
9642 }
9643 return -1;
9644 }
9645
9646 @Override
9647 public void onHelp() {
9648 PrintWriter pw = getOutPrintWriter();
9649 pw.println("Connectivity service commands:");
9650 pw.println(" help");
9651 pw.println(" Print this help text.");
9652 pw.println(" airplane-mode [enable|disable]");
9653 pw.println(" Turn airplane mode on or off.");
9654 pw.println(" airplane-mode");
9655 pw.println(" Get airplane mode.");
9656 }
9657 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009658
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09009659 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009660 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
9661 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
9662 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +08009663 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009664 }
9665
he_won.hwang881307a2022-03-15 21:23:52 +09009666 private void maybeUpdateWifiRoamTimestamp(NetworkAgentInfo nai, NetworkCapabilities nc) {
9667 if (nai == null) return;
9668 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
9669 final TransportInfo newInfo = nc.getTransportInfo();
9670 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
9671 return;
9672 }
9673 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +09009674 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +09009675 }
9676 }
9677
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009678 /**
9679 * @param connectionInfo the connection to resolve.
9680 * @return {@code uid} if the connection is found and the app has permission to observe it
9681 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
9682 * connection is not found.
9683 */
9684 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009685 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
9686 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
9687 }
9688
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09009689 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009690 connectionInfo.local, connectionInfo.remote);
9691
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009692 if (uid == INVALID_UID) return uid; // Not found.
9693
9694 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
9695 // VPN, if any, that applies to the UID that owns the connection.
9696 if (checkNetworkStackPermission()) return uid;
9697
9698 final NetworkAgentInfo vpn = getVpnForUid(uid);
9699 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09009700 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009701 return INVALID_UID;
9702 }
9703
9704 return uid;
9705 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +00009706
Benedict Wong493e04b2018-11-09 14:45:34 -08009707 /**
9708 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
9709 *
9710 * <p>The TestNetworkService must be run in the system server due to TUN creation.
9711 */
9712 @Override
9713 public IBinder startOrGetTestNetworkService() {
9714 synchronized (mTNSLock) {
9715 TestNetworkService.enforceTestNetworkPermissions(mContext);
9716
9717 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +08009718 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -08009719 }
9720
9721 return mTNS;
9722 }
9723 }
Cody Kestingd199a9d2019-12-17 12:55:28 -08009724
Cody Kesting73708bf2019-12-18 10:57:50 -08009725 /**
9726 * Handler used for managing all Connectivity Diagnostics related functions.
9727 *
9728 * @see android.net.ConnectivityDiagnosticsManager
9729 *
9730 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9731 */
9732 @VisibleForTesting
9733 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009734 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9735
Cody Kesting73708bf2019-12-18 10:57:50 -08009736 /**
9737 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9738 * android.net.ConnectivityDiagnosticsManager}.
9739 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9740 * NetworkRequestInfo to be registered
9741 */
9742 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9743
9744 /**
9745 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9746 * android.net.ConnectivityDiagnosticsManager}.
9747 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9748 * arg1 = the uid of the caller
9749 */
9750 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9751
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009752 /**
9753 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009754 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009755 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9756 * NetworkMonitor.
9757 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009758 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009759 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009760
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009761 /**
9762 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9763 * been detected on the network.
9764 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9765 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9766 * arg2 = NetID.
9767 * data = PersistableBundle of extras passed from NetworkMonitor.
9768 */
9769 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9770
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009771 /**
9772 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9773 * the platform. This event will invoke {@link
9774 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9775 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -07009776 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009777 */
9778 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9779
Cody Kesting73708bf2019-12-18 10:57:50 -08009780 private ConnectivityDiagnosticsHandler(Looper looper) {
9781 super(looper);
9782 }
9783
9784 @Override
9785 public void handleMessage(Message msg) {
9786 switch (msg.what) {
9787 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9788 handleRegisterConnectivityDiagnosticsCallback(
9789 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9790 break;
9791 }
9792 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9793 handleUnregisterConnectivityDiagnosticsCallback(
9794 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9795 break;
9796 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009797 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009798 final ConnectivityReportEvent reportEvent =
9799 (ConnectivityReportEvent) msg.obj;
9800
Aaron Huang959d3642021-01-21 15:47:41 +08009801 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009802 break;
9803 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009804 case EVENT_DATA_STALL_SUSPECTED: {
9805 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +08009806 final Pair<Long, PersistableBundle> arg =
9807 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009808 if (nai == null) break;
9809
Aaron Huang959d3642021-01-21 15:47:41 +08009810 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009811 break;
9812 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009813 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -07009814 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009815 break;
9816 }
9817 default: {
9818 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9819 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009820 }
9821 }
9822 }
9823
9824 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9825 @VisibleForTesting
9826 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9827 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9828 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009829 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009830
9831 @VisibleForTesting
9832 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009833 @NonNull IConnectivityDiagnosticsCallback cb,
9834 @NonNull NetworkRequestInfo nri,
9835 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009836 mCb = cb;
9837 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009838 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009839 }
9840
9841 @Override
9842 public void binderDied() {
9843 log("ConnectivityDiagnosticsCallback IBinder died.");
9844 unregisterConnectivityDiagnosticsCallback(mCb);
9845 }
9846 }
9847
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009848 /**
9849 * Class used for sending information from {@link
9850 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9851 */
9852 private static class NetworkTestedResults {
9853 private final int mNetId;
9854 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009855 @Nullable private final String mRedirectUrl;
9856
9857 private NetworkTestedResults(
9858 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9859 mNetId = netId;
9860 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009861 mRedirectUrl = redirectUrl;
9862 }
9863 }
9864
9865 /**
9866 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9867 * ConnectivityDiagnosticsHandler}.
9868 */
9869 private static class ConnectivityReportEvent {
9870 private final long mTimestampMillis;
9871 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +08009872 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009873
Aaron Huang959d3642021-01-21 15:47:41 +08009874 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9875 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009876 mTimestampMillis = timestampMillis;
9877 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +08009878 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009879 }
9880 }
9881
Cody Kestingf1120be2020-08-03 18:01:40 -07009882 /**
9883 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
9884 * ConnectivityDiagnosticsHandler}.
9885 */
9886 private static class ReportedNetworkConnectivityInfo {
9887 public final boolean hasConnectivity;
9888 public final boolean isNetworkRevalidating;
9889 public final int reporterUid;
9890 @NonNull public final NetworkAgentInfo nai;
9891
9892 private ReportedNetworkConnectivityInfo(
9893 boolean hasConnectivity,
9894 boolean isNetworkRevalidating,
9895 int reporterUid,
9896 @NonNull NetworkAgentInfo nai) {
9897 this.hasConnectivity = hasConnectivity;
9898 this.isNetworkRevalidating = isNetworkRevalidating;
9899 this.reporterUid = reporterUid;
9900 this.nai = nai;
9901 }
9902 }
9903
Cody Kesting73708bf2019-12-18 10:57:50 -08009904 private void handleRegisterConnectivityDiagnosticsCallback(
9905 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9906 ensureRunningOnConnectivityServiceThread();
9907
9908 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -08009909 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009910 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9911
James Mattis64b8b0f2020-11-24 17:40:49 -08009912 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9913 // confusing for these networks to change when an NRI is satisfied in another layer.
9914 if (nri.isMultilayerRequest()) {
9915 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9916 + "network requests.");
9917 }
9918
Cody Kesting73708bf2019-12-18 10:57:50 -08009919 // This means that the client registered the same callback multiple times. Do
9920 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -08009921 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009922 if (VDBG) log("Diagnostics callback is already registered");
9923
9924 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9925 // incremented when the NetworkRequestInfo is created as part of
9926 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +08009927 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -08009928 return;
9929 }
9930
Cody Kesting31f1ff62020-03-05 10:46:02 -08009931 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -08009932
9933 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -08009934 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009935 } catch (RemoteException e) {
9936 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -08009937 return;
9938 }
9939
9940 // Once registered, provide ConnectivityReports for matching Networks
9941 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9942 synchronized (mNetworkForNetId) {
9943 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9944 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -08009945 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9946 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -08009947 matchingNetworks.add(nai);
9948 }
9949 }
9950 }
9951 for (final NetworkAgentInfo nai : matchingNetworks) {
9952 final ConnectivityReport report = nai.getConnectivityReport();
9953 if (report == null) {
9954 continue;
9955 }
9956 if (!checkConnectivityDiagnosticsPermissions(
9957 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9958 continue;
9959 }
9960
9961 try {
9962 cb.onConnectivityReportAvailable(report);
9963 } catch (RemoteException e) {
9964 // Exception while sending the ConnectivityReport. Move on to the next network.
9965 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009966 }
9967 }
9968
9969 private void handleUnregisterConnectivityDiagnosticsCallback(
9970 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9971 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009972 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009973
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009974 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9975 mConnectivityDiagnosticsCallbacks.remove(iCb);
9976 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009977 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9978 return;
9979 }
9980
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009981 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -08009982
Cody Kesting70fa2b22020-12-02 12:16:56 -08009983 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9984 // (if the Binder died)
9985 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9986 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -08009987 return;
9988 }
9989
Cody Kesting46cb1672020-03-04 13:35:20 -08009990 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9991 // incremented when the NetworkRequestInfo is created as part of
9992 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +08009993 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -08009994
Cody Kesting31f1ff62020-03-05 10:46:02 -08009995 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009996 }
9997
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009998 private void handleNetworkTestedWithExtras(
9999 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
10000 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080010001 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010002 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010003 final ConnectivityReport report =
10004 new ConnectivityReport(
10005 reportEvent.mNai.network,
10006 reportEvent.mTimestampMillis,
10007 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010008 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010009 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080010010 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070010011
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010012 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010013 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010014 for (final IConnectivityDiagnosticsCallback cb : results) {
10015 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080010016 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010017 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070010018 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010019 }
10020 }
10021 }
10022
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010023 private void handleDataStallSuspected(
10024 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
10025 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080010026 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010027 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010028 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080010029 new DataStallReport(
10030 nai.network,
10031 timestampMillis,
10032 detectionMethod,
10033 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010034 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080010035 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010036 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010037 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010038 for (final IConnectivityDiagnosticsCallback cb : results) {
10039 try {
10040 cb.onDataStallSuspected(report);
10041 } catch (RemoteException ex) {
10042 loge("Error invoking onDataStallSuspected", ex);
10043 }
10044 }
10045 }
10046
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010047 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070010048 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
10049 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
10050 final ConnectivityReport cachedReport = nai.getConnectivityReport();
10051
10052 // If the Network is being re-validated as a result of this call to
10053 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
10054 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010055 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010056 getMatchingPermissionedCallbacks(
10057 nai,
10058 reportedNetworkConnectivityInfo.isNetworkRevalidating
10059 ? Process.INVALID_UID
10060 : reportedNetworkConnectivityInfo.reporterUid);
10061
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010062 for (final IConnectivityDiagnosticsCallback cb : results) {
10063 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070010064 cb.onNetworkConnectivityReported(
10065 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010066 } catch (RemoteException ex) {
10067 loge("Error invoking onNetworkConnectivityReported", ex);
10068 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010069
10070 // If the Network isn't re-validating, also provide the cached report. If there is no
10071 // cached report, the Network is still being validated and a report will be sent once
10072 // validation is complete. Note that networks which never undergo validation will still
10073 // have a cached ConnectivityReport with RESULT_SKIPPED.
10074 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
10075 try {
10076 cb.onConnectivityReportAvailable(cachedReport);
10077 } catch (RemoteException ex) {
10078 loge("Error invoking onConnectivityReportAvailable", ex);
10079 }
10080 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010081 }
10082 }
10083
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010084 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090010085 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
10086 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010087 sanitized.setUids(null);
10088 sanitized.setAdministratorUids(new int[0]);
10089 sanitized.setOwnerUid(Process.INVALID_UID);
10090 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080010091 }
10092
Cody Kestingf1120be2020-08-03 18:01:40 -070010093 /**
10094 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
10095 *
10096 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
10097 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010098 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070010099 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010100 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010101 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010102 mConnectivityDiagnosticsCallbacks.entrySet()) {
10103 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
10104 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070010105
James Mattis64b8b0f2020-11-24 17:40:49 -080010106 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070010107 if (!nai.satisfies(nri.mRequests.get(0))) {
10108 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010109 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010110
10111 // UID for this callback must either be:
10112 // - INVALID_UID (which sends callbacks to all UIDs), or
10113 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
10114 // notified as a result)
10115 if (uid != Process.INVALID_UID && uid != nri.mUid) {
10116 continue;
10117 }
10118
10119 if (!checkConnectivityDiagnosticsPermissions(
10120 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10121 continue;
10122 }
10123
10124 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010125 }
10126 return results;
10127 }
10128
Cody Kesting7474f672021-05-11 14:22:40 -070010129 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
10130 @NonNull NetworkAgentInfo nai) {
10131 // TODO(b/188483916): replace with a transport-agnostic location-aware check
10132 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
10133 }
10134
Cody Kesting160ef392021-05-05 13:17:22 -070010135 private boolean hasLocationPermission(String packageName, int uid) {
10136 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
10137 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
10138 // call in a try-catch.
10139 try {
10140 if (!mLocationPermissionChecker.checkLocationPermission(
10141 packageName, null /* featureId */, uid, null /* message */)) {
10142 return false;
10143 }
10144 } catch (SecurityException e) {
10145 return false;
10146 }
10147
10148 return true;
10149 }
10150
10151 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
10152 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090010153 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070010154 && virtual.networkCapabilities.getOwnerUid() == uid
10155 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
10156 return true;
10157 }
10158 }
10159
10160 return false;
10161 }
10162
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010163 @VisibleForTesting
10164 boolean checkConnectivityDiagnosticsPermissions(
10165 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
10166 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
10167 return true;
10168 }
10169
Cody Kesting160ef392021-05-05 13:17:22 -070010170 // Administrator UIDs also contains the Owner UID
10171 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
10172 if (!CollectionUtils.contains(administratorUids, callbackUid)
10173 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010174 return false;
10175 }
10176
Cody Kesting7474f672021-05-11 14:22:40 -070010177 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
10178 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010179 }
10180
Cody Kestingd199a9d2019-12-17 12:55:28 -080010181 @Override
10182 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010183 @NonNull IConnectivityDiagnosticsCallback callback,
10184 @NonNull NetworkRequest request,
10185 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010186 Objects.requireNonNull(callback, "callback must not be null");
10187 Objects.requireNonNull(request, "request must not be null");
10188 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
10189
Cody Kesting73708bf2019-12-18 10:57:50 -080010190 if (request.legacyType != TYPE_NONE) {
10191 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
10192 + " Please use NetworkCapabilities instead.");
10193 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010194 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080010195 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010196
10197 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
10198 // and administrator uids to be safe.
10199 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080010200 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010201
10202 final NetworkRequest requestWithId =
10203 new NetworkRequest(
10204 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
10205
10206 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
10207 //
10208 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
10209 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
10210 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010211 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080010212 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010213 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010214
10215 mConnectivityDiagnosticsHandler.sendMessage(
10216 mConnectivityDiagnosticsHandler.obtainMessage(
10217 ConnectivityDiagnosticsHandler
10218 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
10219 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010220 }
10221
10222 @Override
10223 public void unregisterConnectivityDiagnosticsCallback(
10224 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010225 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080010226 mConnectivityDiagnosticsHandler.sendMessage(
10227 mConnectivityDiagnosticsHandler.obtainMessage(
10228 ConnectivityDiagnosticsHandler
10229 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010230 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080010231 0,
10232 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010233 }
Cody Kestingf53a0752020-04-15 12:33:28 -070010234
10235 @Override
10236 public void simulateDataStall(int detectionMethod, long timestampMillis,
10237 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010238 Objects.requireNonNull(network, "network must not be null");
10239 Objects.requireNonNull(extras, "extras must not be null");
10240
paulhu3ffffe72021-09-16 10:15:22 +080010241 enforceAnyPermissionOf(mContext,
10242 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070010243 android.Manifest.permission.NETWORK_STACK);
10244 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
10245 if (!nc.hasTransport(TRANSPORT_TEST)) {
Chalard Jean15228572022-01-28 19:29:12 +090010246 throw new SecurityException("Data Stall simulation is only possible for test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070010247 }
10248
10249 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010250 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -070010251 throw new SecurityException("Data Stall simulation is only possible for network "
10252 + "creators");
10253 }
10254
Cody Kesting652e3ec2020-05-21 12:08:21 -070010255 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
10256 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
10257 // Data Stall information as a DataStallReportParcelable and passing to
10258 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
10259 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070010260 final DataStallReportParcelable p = new DataStallReportParcelable();
10261 p.timestampMillis = timestampMillis;
10262 p.detectionMethod = detectionMethod;
10263
10264 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
10265 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
10266 }
10267 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
10268 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
10269 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
10270 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
10271 }
10272
Serik Beketayevec8ad212020-12-07 22:43:07 -080010273 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070010274 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010275
lucaslin66f44212021-02-23 01:12:55 +080010276 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
10277 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080010278 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080010279 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080010280 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080010281 }
lucaslin37a16d92021-01-21 19:48:09 +080010282
10283 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010284 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080010285 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010286 nai.clatd.interfaceLinkStateChanged(iface, up);
10287 }
10288 }
10289
10290 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010291 public void onInterfaceRemoved(@NonNull String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080010292 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010293 nai.clatd.interfaceRemoved(iface);
10294 }
lucaslin66f44212021-02-23 01:12:55 +080010295 }
10296 }
10297
lucaslin1a8b4c62021-01-21 02:02:55 +080010298 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
10299
10300 /**
10301 * Class used for updating network activity tracking with netd and notify network activity
10302 * changes.
10303 */
10304 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080010305 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080010306 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080010307 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080010308 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
10309 new RemoteCallbackList<>();
10310 // Indicate the current system default network activity is active or not.
10311 @GuardedBy("mActiveIdleTimers")
10312 private boolean mNetworkActive;
10313 @GuardedBy("mActiveIdleTimers")
Chalard Jean46bfbf02022-02-02 00:56:25 +090010314 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1193a5d2021-01-21 02:04:15 +080010315 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010316
Chalard Jean46bfbf02022-02-02 00:56:25 +090010317 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080010318 public final int timeout;
10319 public final int transportType;
10320
10321 IdleTimerParams(int timeout, int transport) {
10322 this.timeout = timeout;
10323 this.transportType = transport;
10324 }
10325 }
10326
10327 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080010328 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080010329 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080010330 mNetd = netd;
10331 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010332 }
10333
lucaslin66f44212021-02-23 01:12:55 +080010334 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
10335 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
10336 synchronized (mActiveIdleTimers) {
10337 mNetworkActive = active;
10338 // If there are no idle timers, it means that system is not monitoring
10339 // activity, so the system default network for those default network
10340 // unspecified apps is always considered active.
10341 //
10342 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
10343 // any network activity change event. Whenever this event is received,
10344 // the mActiveIdleTimers should be always not empty. The legacy behavior
10345 // is no-op. Remove to refer to mNetworkActive only.
10346 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
10347 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
10348 }
10349 }
10350 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010351
lucaslin1193a5d2021-01-21 02:04:15 +080010352 // The network activity should only be updated from ConnectivityService handler thread
10353 // when mActiveIdleTimers lock is held.
10354 @GuardedBy("mActiveIdleTimers")
10355 private void reportNetworkActive() {
10356 final int length = mNetworkActivityListeners.beginBroadcast();
10357 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
10358 try {
10359 for (int i = 0; i < length; i++) {
10360 try {
10361 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
10362 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010363 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080010364 }
10365 }
10366 } finally {
10367 mNetworkActivityListeners.finishBroadcast();
10368 }
10369 }
10370
10371 @GuardedBy("mActiveIdleTimers")
10372 public void handleReportNetworkActivity() {
10373 synchronized (mActiveIdleTimers) {
10374 reportNetworkActive();
10375 }
10376 }
10377
lucaslin1a8b4c62021-01-21 02:02:55 +080010378 // This is deprecated and only to support legacy use cases.
10379 private int transportTypeToLegacyType(int type) {
10380 switch (type) {
10381 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010382 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080010383 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010384 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080010385 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010386 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080010387 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010388 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080010389 default:
10390 loge("Unexpected transport in transportTypeToLegacyType: " + type);
10391 }
10392 return ConnectivityManager.TYPE_NONE;
10393 }
10394
10395 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
10396 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
10397 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
10398 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
10399 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
10400 final long ident = Binder.clearCallingIdentity();
10401 try {
10402 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
10403 RECEIVE_DATA_ACTIVITY_CHANGE,
10404 null /* resultReceiver */,
10405 null /* scheduler */,
10406 0 /* initialCode */,
10407 null /* initialData */,
10408 null /* initialExtra */);
10409 } finally {
10410 Binder.restoreCallingIdentity(ident);
10411 }
10412 }
10413
10414 /**
10415 * Setup data activity tracking for the given network.
10416 *
10417 * Every {@code setupDataActivityTracking} should be paired with a
10418 * {@link #removeDataActivityTracking} for cleanup.
10419 */
10420 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
10421 final String iface = networkAgent.linkProperties.getInterfaceName();
10422
10423 final int timeout;
10424 final int type;
10425
10426 if (networkAgent.networkCapabilities.hasTransport(
10427 NetworkCapabilities.TRANSPORT_CELLULAR)) {
10428 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010429 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080010430 10);
10431 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10432 } else if (networkAgent.networkCapabilities.hasTransport(
10433 NetworkCapabilities.TRANSPORT_WIFI)) {
10434 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010435 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080010436 15);
10437 type = NetworkCapabilities.TRANSPORT_WIFI;
10438 } else {
10439 return; // do not track any other networks
10440 }
10441
lucaslinb961efc2021-01-21 02:03:17 +080010442 updateRadioPowerState(true /* isActive */, type);
10443
lucaslin1a8b4c62021-01-21 02:02:55 +080010444 if (timeout > 0 && iface != null) {
10445 try {
lucaslin1193a5d2021-01-21 02:04:15 +080010446 synchronized (mActiveIdleTimers) {
10447 // Networks start up.
10448 mNetworkActive = true;
10449 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
10450 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
10451 reportNetworkActive();
10452 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010453 } catch (Exception e) {
10454 // You shall not crash!
10455 loge("Exception in setupDataActivityTracking " + e);
10456 }
10457 }
10458 }
10459
10460 /**
10461 * Remove data activity tracking when network disconnects.
10462 */
10463 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
10464 final String iface = networkAgent.linkProperties.getInterfaceName();
10465 final NetworkCapabilities caps = networkAgent.networkCapabilities;
10466
lucaslinb961efc2021-01-21 02:03:17 +080010467 if (iface == null) return;
10468
10469 final int type;
10470 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
10471 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10472 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
10473 type = NetworkCapabilities.TRANSPORT_WIFI;
10474 } else {
10475 return; // do not track any other networks
10476 }
10477
10478 try {
10479 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080010480 synchronized (mActiveIdleTimers) {
10481 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
10482 // The call fails silently if no idle timer setup for this interface
10483 mNetd.idletimerRemoveInterface(iface, params.timeout,
10484 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080010485 }
lucaslinb961efc2021-01-21 02:03:17 +080010486 } catch (Exception e) {
10487 // You shall not crash!
10488 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080010489 }
10490 }
10491
10492 /**
10493 * Update data activity tracking when network state is updated.
10494 */
10495 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
10496 NetworkAgentInfo oldNetwork) {
10497 if (newNetwork != null) {
10498 setupDataActivityTracking(newNetwork);
10499 }
10500 if (oldNetwork != null) {
10501 removeDataActivityTracking(oldNetwork);
10502 }
10503 }
lucaslinb961efc2021-01-21 02:03:17 +080010504
10505 private void updateRadioPowerState(boolean isActive, int transportType) {
10506 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
10507 switch (transportType) {
10508 case NetworkCapabilities.TRANSPORT_CELLULAR:
10509 bs.reportMobileRadioPowerState(isActive, NO_UID);
10510 break;
10511 case NetworkCapabilities.TRANSPORT_WIFI:
10512 bs.reportWifiRadioPowerState(isActive, NO_UID);
10513 break;
10514 default:
10515 logw("Untracked transport type:" + transportType);
10516 }
10517 }
lucaslin1193a5d2021-01-21 02:04:15 +080010518
10519 public boolean isDefaultNetworkActive() {
10520 synchronized (mActiveIdleTimers) {
10521 // If there are no idle timers, it means that system is not monitoring activity,
10522 // so the default network is always considered active.
10523 //
10524 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
10525 // tracking is disabled (negative idle timer value configured), or no active default
10526 // network. In the latter case, this reports active but it should report inactive.
10527 return mNetworkActive || mActiveIdleTimers.isEmpty();
10528 }
10529 }
10530
10531 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
10532 mNetworkActivityListeners.register(l);
10533 }
10534
10535 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
10536 mNetworkActivityListeners.unregister(l);
10537 }
lucaslin012f7a12021-01-21 02:04:35 +080010538
10539 public void dump(IndentingPrintWriter pw) {
10540 synchronized (mActiveIdleTimers) {
10541 pw.print("mNetworkActive="); pw.println(mNetworkActive);
10542 pw.println("Idle timers:");
10543 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
10544 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
10545 final IdleTimerParams params = ent.getValue();
10546 pw.print(" timeout="); pw.print(params.timeout);
10547 pw.print(" type="); pw.println(params.transportType);
10548 }
10549 }
10550 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010551 }
James Mattis47db0582021-01-01 14:13:35 -080010552
Daniel Brightf9e945b2020-06-15 16:10:01 -070010553 /**
10554 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
10555 *
10556 * @param socketInfo the socket information
10557 * @param callback the callback to register
10558 */
10559 @Override
10560 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
10561 @NonNull final IQosCallback callback) {
10562 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
10563 if (nai == null || nai.networkCapabilities == null) {
10564 try {
10565 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
10566 } catch (final RemoteException ex) {
10567 loge("registerQosCallbackInternal: RemoteException", ex);
10568 }
10569 return;
10570 }
10571 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
10572 }
10573
10574 /**
10575 * Register a {@link IQosCallback} with base {@link QosFilter}.
10576 *
10577 * @param filter the filter to register
10578 * @param callback the callback to register
10579 * @param nai the agent information related to the filter's network
10580 */
10581 @VisibleForTesting
10582 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
10583 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010584 Objects.requireNonNull(filter, "filter must be non-null");
10585 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010586
10587 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080010588 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
10589 // on this network is unregistered when the app loses permission or b) no QoS
10590 // callbacks are sent for restricted networks unless the app currently has permission
10591 // to access restricted networks.
10592 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070010593 }
10594 mQosCallbackTracker.registerCallback(callback, filter, nai);
10595 }
10596
10597 /**
10598 * Unregisters the given callback.
10599 *
10600 * @param callback the callback to unregister
10601 */
10602 @Override
10603 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010604 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010605 mQosCallbackTracker.unregisterCallback(callback);
10606 }
James Mattis47db0582021-01-01 14:13:35 -080010607
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010608 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
10609 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
10610 // Enterprise device can be fully managed like device owner and such use case
10611 // also should be supported. Calling app check for work profile and fully managed device
10612 // is already done in DevicePolicyManager.
10613 // This check is an extra caution to be sure device is fully managed or not.
10614 final UserManager um = mContext.getSystemService(UserManager.class);
10615 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
10616 if (um.isManagedProfile(profile.getIdentifier())) {
10617 return true;
10618 }
10619 if (SdkLevel.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
10620 return false;
10621 }
10622
James Mattis45d81842021-01-10 14:24:24 -080010623 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010624 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010625 *
10626 * See the documentation for the individual preferences for a description of the supported
10627 * behaviors.
10628 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010629 * @param profile If the device owner is set, any profile is allowed.
10630 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010631 * @param preferences the list of profile network preferences for the
10632 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010633 * @param listener an optional listener to listen for completion of the operation.
10634 */
10635 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010636 public void setProfileNetworkPreferences(
10637 @NonNull final UserHandle profile,
10638 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090010639 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010640 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010641 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010642
10643 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010644 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
10645 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
10646 .build();
10647 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010648 }
10649
paulhu3ffffe72021-09-16 10:15:22 +080010650 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010651 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010652 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010653 }
10654 if (profile.getIdentifier() < 0) {
10655 throw new IllegalArgumentException("Must explicitly specify a user handle ("
10656 + "UserHandle.CURRENT not supported)");
10657 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010658 if (!isNetworkPreferenceAllowedForProfile(profile)) {
10659 throw new IllegalArgumentException("Profile must be a managed profile "
10660 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010661 }
paulhuaa0743d2021-05-26 21:56:03 +080010662
Chalard Jean46bfbf02022-02-02 00:56:25 +090010663 final List<ProfileNetworkPreferenceList.Preference> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010664 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010665 for (final ProfileNetworkPreference preference : preferences) {
10666 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010667 boolean allowFallback = true;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010668 switch (preference.getPreference()) {
10669 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
10670 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010671 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010672 if (preference.getPreferenceEnterpriseId() != 0) {
10673 throw new IllegalArgumentException(
10674 "Invalid enterprise identifier in setProfileNetworkPreferences");
10675 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010676 break;
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010677 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
10678 allowFallback = false;
10679 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010680 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010681 // This code is needed even though there is a check later on,
10682 // because isRangeAlreadyInPreferenceList assumes that every preference
10683 // has a UID list.
10684 if (hasDefaultPreference) {
10685 throw new IllegalArgumentException(
10686 "Default profile preference should not be set along with other "
10687 + "preference");
10688 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010689 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
10690 throw new IllegalArgumentException(
10691 "Invalid enterprise identifier in setProfileNetworkPreferences");
10692 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010693 final Set<UidRange> uidRangeSet =
10694 getUidListToBeAppliedForNetworkPreference(profile, preference);
10695 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
10696 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
10697 } else {
10698 throw new IllegalArgumentException(
10699 "Overlapping uid range in setProfileNetworkPreferences");
10700 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010701 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010702 nc.addEnterpriseId(
10703 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010704 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10705 break;
10706 default:
10707 throw new IllegalArgumentException(
10708 "Invalid preference in setProfileNetworkPreferences");
10709 }
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010710 preferenceList.add(new ProfileNetworkPreferenceList.Preference(
10711 profile, nc, allowFallback));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010712 if (hasDefaultPreference && preferenceList.size() > 1) {
10713 throw new IllegalArgumentException(
10714 "Default profile preference should not be set along with other preference");
10715 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010716 }
10717 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010718 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010719 }
10720
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010721 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
10722 @NonNull final UserHandle profile,
10723 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
10724 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080010725 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
10726 profileNetworkPreference.getIncludedUids());
10727
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010728 if (uidRangeSet.size() > 0) {
10729 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
10730 throw new IllegalArgumentException(
10731 "Allow uid range is outside the uid range of profile.");
10732 }
10733 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080010734 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010735 profileNetworkPreference.getExcludedUids());
10736 if (disallowUidRangeSet.size() > 0) {
10737 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
10738 throw new IllegalArgumentException(
10739 "disallow uid range is outside the uid range of profile.");
10740 }
10741 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
10742 disallowUidRangeSet);
10743 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010744 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010745 uidRangeSet.add(profileUids);
10746 }
10747 }
10748 return uidRangeSet;
10749 }
10750
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010751 private boolean isEnterpriseIdentifierValid(
10752 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010753 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010754 return true;
10755 }
10756 return false;
10757 }
10758
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010759 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010760 @NonNull final ProfileNetworkPreferenceList prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010761 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010762 for (final ProfileNetworkPreferenceList.Preference pref : prefs.preferences) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010763 // The NRI for a user should contain the request for capabilities.
10764 // If fallback to default network is needed then NRI should include
10765 // the request for the default network. Create an image of it to
10766 // have the correct UIDs in it (also a request can only be part of one NRI, because
10767 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010768 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
10769 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010770 if (pref.allowFallback) {
10771 nrs.add(createDefaultInternetRequestForTransport(
10772 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10773 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010774 if (VDBG) {
10775 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
10776 pref.capabilities.getUids()));
10777 }
10778
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010779 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080010780 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080010781 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010782 result.add(nri);
10783 }
10784 return result;
10785 }
10786
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010787 /**
10788 * Compare if the given UID range sets have the same UIDs.
10789 *
10790 */
10791 private boolean isRangeAlreadyInPreferenceList(
10792 @NonNull List<ProfileNetworkPreferenceList.Preference> preferenceList,
10793 @NonNull Set<UidRange> uidRangeSet) {
10794 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
10795 return false;
10796 }
10797 for (ProfileNetworkPreferenceList.Preference pref : preferenceList) {
10798 if (UidRangeUtils.doesRangeSetOverlap(
10799 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
10800 return true;
10801 }
10802 }
10803 return false;
10804 }
10805
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010806 private void handleSetProfileNetworkPreference(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010807 @NonNull final List<ProfileNetworkPreferenceList.Preference> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010808 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010809 /*
10810 * handleSetProfileNetworkPreference is always called for single user.
10811 * preferenceList only contains preferences for different uids within the same user
10812 * (enforced by getUidListToBeAppliedForNetworkPreference).
10813 * Clear all the existing preferences for the user before applying new preferences.
10814 *
10815 */
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010816 mProfileNetworkPreferences = mProfileNetworkPreferences.withoutUser(
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010817 preferenceList.get(0).user);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010818 for (final ProfileNetworkPreferenceList.Preference preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010819 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
10820 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010821
paulhu74128522021-09-28 02:29:03 +000010822 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
10823 addPerAppDefaultNetworkRequests(
10824 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai31d38bf2022-07-04 17:28:39 +080010825
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010826 // Finally, rematch.
10827 rematchAllNetworksAndRequests();
10828
10829 if (null != listener) {
10830 try {
10831 listener.onComplete();
10832 } catch (RemoteException e) {
10833 loge("Listener for setProfileNetworkPreference has died");
10834 }
10835 }
10836 }
10837
paulhu51f77dc2021-06-07 02:34:20 +000010838 @VisibleForTesting
10839 @NonNull
10840 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
10841 @NonNull final Set<Integer> uids) {
10842 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10843 if (uids.size() == 0) {
10844 // Should not create NetworkRequestInfo if no preferences. Without uid range in
10845 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
10846 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
10847 return nris;
10848 }
10849
10850 final List<NetworkRequest> requests = new ArrayList<>();
10851 // The NRI should be comprised of two layers:
10852 // - The request for the mobile network preferred.
10853 // - The request for the default network, for fallback.
10854 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090010855 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000010856 requests.add(createDefaultInternetRequestForTransport(
10857 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10858 final Set<UidRange> ranges = new ArraySet<>();
10859 for (final int uid : uids) {
10860 ranges.add(new UidRange(uid, uid));
10861 }
10862 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080010863 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080010864 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000010865 return nris;
10866 }
10867
10868 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000010869 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000010870 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
10871 addPerAppDefaultNetworkRequests(
10872 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000010873 // Finally, rematch.
10874 rematchAllNetworksAndRequests();
10875 }
10876
Patrick Rohr2857ac42022-01-21 14:58:16 +010010877 private void handleIngressRateLimitChanged() {
10878 final long oldIngressRateLimit = mIngressRateLimit;
10879 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
10880 mContext);
10881 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
10882 if (canNetworkBeRateLimited(networkAgent)) {
10883 // If rate limit has previously been enabled, remove the old limit first.
10884 if (oldIngressRateLimit >= 0) {
10885 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
10886 }
10887 if (mIngressRateLimit >= 0) {
10888 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10889 mIngressRateLimit);
10890 }
10891 }
10892 }
10893 }
10894
10895 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090010896 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
10897 if (!SdkLevel.isAtLeastT()) return false;
10898
Patrick Rohrff3b3f82022-02-09 15:15:52 +010010899 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
10900 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
10901 // internet connectivity can be rate limited.
10902 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
10903 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010010904 return false;
10905 }
10906
10907 final String iface = networkAgent.linkProperties.getInterfaceName();
10908 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010010909 // This may happen in tests, but if there is no interface then there is nothing that
10910 // can be rate limited.
10911 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010010912 return false;
10913 }
10914 return true;
10915 }
10916
James Mattis45d81842021-01-10 14:24:24 -080010917 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080010918 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
10919 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080010920 }
10921
10922 /**
10923 * Used by automotive devices to set the network preferences used to direct traffic at an
10924 * application level as per the given OemNetworkPreferences. An example use-case would be an
10925 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
10926 * vehicle via a particular network.
10927 *
10928 * Calling this will overwrite the existing preference.
10929 *
James Mattisda32cfe2021-01-26 16:23:52 -080010930 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090010931 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080010932 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080010933 */
James Mattis47db0582021-01-01 14:13:35 -080010934 @Override
James Mattis45d81842021-01-10 14:24:24 -080010935 public void setOemNetworkPreference(
10936 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010937 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080010938
James Mattisfa270db2021-05-31 17:11:10 -070010939 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10940 // Only bypass the permission/device checks if this is a valid test request.
10941 if (isValidTestOemNetworkPreference(preference)) {
10942 enforceManageTestNetworksPermission();
10943 } else {
10944 enforceAutomotiveDevice();
10945 enforceOemNetworkPreferencesPermission();
10946 validateOemNetworkPreferences(preference);
10947 }
James Mattis45d81842021-01-10 14:24:24 -080010948
James Mattis45d81842021-01-10 14:24:24 -080010949 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
10950 new Pair<>(preference, listener)));
10951 }
10952
James Mattisfa270db2021-05-31 17:11:10 -070010953 /**
10954 * Check the validity of an OEM network preference to be used for testing purposes.
10955 * @param preference the preference to validate
10956 * @return true if this is a valid OEM network preference test request.
10957 */
10958 private boolean isValidTestOemNetworkPreference(
10959 @NonNull final OemNetworkPreferences preference) {
10960 // Allow for clearing of an existing OemNetworkPreference used for testing.
10961 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
10962 // changes after this check is complete. This is an unlikely scenario as calling of this API
10963 // is controlled by the OEM therefore the added complexity is not worth adding given those
10964 // circumstances. That said, it is an edge case to be aware of hence this comment.
10965 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
10966 && isTestOemNetworkPreference(mOemNetworkPreferences);
10967 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
10968 }
10969
10970 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
10971 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
10972 return prefMap.size() == 1
10973 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
10974 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
10975 }
10976
James Mattis45d81842021-01-10 14:24:24 -080010977 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
10978 for (@OemNetworkPreferences.OemNetworkPreference final int pref
10979 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070010980 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
10981 throw new IllegalArgumentException(
10982 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
10983 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080010984 }
10985 }
10986 }
10987
10988 private void handleSetOemNetworkPreference(
10989 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010990 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080010991 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10992 if (DBG) {
10993 log("set OEM network preferences :" + preference.toString());
10994 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010995
James Mattiscb1e0362021-04-06 17:07:42 -070010996 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000010997 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
10998 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
10999 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080011000 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080011001
11002 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011003 try {
11004 listener.onComplete();
11005 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080011006 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011007 }
James Mattis45d81842021-01-10 14:24:24 -080011008 }
11009 }
11010
paulhu74128522021-09-28 02:29:03 +000011011 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080011012 // Skip the requests which are set by other network preference. Because the uid range rules
11013 // should stay in netd.
11014 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080011015 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080011016 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080011017 }
11018
James Mattis3ce3d3c2021-02-09 18:18:28 -080011019 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
11020 ensureRunningOnConnectivityServiceThread();
11021 mDefaultNetworkRequests.addAll(nris);
11022 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
11023 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080011024 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000011025 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
11026 nrisToRegister.addAll(
11027 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
11028 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011029 }
11030
11031 /**
11032 * All current requests that are tracking the default network need to be assessed as to whether
11033 * or not the current set of per-application default requests will be changing their default
11034 * network. If so, those requests will need to be updated so that they will send callbacks for
11035 * default network changes at the appropriate time. Additionally, those requests tracking the
11036 * default that were previously updated by this flow will need to be reassessed.
11037 * @return the nris which will need to be updated.
11038 */
11039 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
11040 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
11041 // Get the distinct nris to check since for multilayer requests, it is possible to have the
11042 // same nri in the map's values for each of its NetworkRequest objects.
11043 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080011044 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011045 // Include this nri if it is currently being tracked.
11046 if (isPerAppTrackedNri(nri)) {
11047 defaultCallbackRequests.add(nri);
11048 continue;
11049 }
11050 // We only track callbacks for requests tracking the default.
11051 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
11052 continue;
11053 }
11054 // Include this nri if it will be tracked by the new per-app default requests.
11055 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011056 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080011057 if (isNriGoingToBeTracked) {
11058 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080011059 }
11060 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080011061 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080011062 }
11063
James Mattis3ce3d3c2021-02-09 18:18:28 -080011064 /**
11065 * Create nris for those network requests that are currently tracking the default network that
11066 * are being controlled by a per-application default.
11067 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
11068 * foundation when creating the nri. Important items include the calling uid's original
11069 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
11070 * requests are assumed to have already been validated as needing to be updated.
11071 * @return the Set of nris to use when registering network requests.
11072 */
11073 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
11074 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
11075 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
11076 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
11077 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011078 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011079
Chalard Jean9473c982021-07-29 20:03:04 +090011080 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080011081 if (trackingNri == mDefaultRequest) {
11082 callbackRequestsToRegister.add(new NetworkRequestInfo(
11083 callbackRequest,
11084 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
11085 continue;
11086 }
11087
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011088 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011089 callbackRequestsToRegister.add(new NetworkRequestInfo(
11090 callbackRequest,
11091 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011092 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090011093 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080011094 }
11095 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080011096 }
11097
Chalard Jean17215832021-03-01 14:06:28 +090011098 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
11099 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090011100 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011101 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090011102 }
11103 }
11104
James Mattis45d81842021-01-10 14:24:24 -080011105 /**
11106 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
11107 */
11108 @VisibleForTesting
11109 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011110 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080011111 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011112 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080011113 final SparseArray<Set<Integer>> uids =
11114 createUidsFromOemNetworkPreferences(preference);
11115 for (int i = 0; i < uids.size(); i++) {
11116 final int key = uids.keyAt(i);
11117 final Set<Integer> value = uids.valueAt(i);
11118 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
11119 // No need to add an nri without any requests.
11120 if (0 == nri.mRequests.size()) {
11121 continue;
11122 }
11123 nris.add(nri);
11124 }
11125
11126 return nris;
11127 }
11128
11129 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
11130 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070011131 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080011132 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080011133 final List<UserHandle> users =
11134 mContext.getSystemService(UserManager.class).getUserHandles(true);
11135 if (null == users || users.size() == 0) {
11136 if (VDBG || DDBG) {
11137 log("No users currently available for setting the OEM network preference.");
11138 }
James Mattisb6b6a432021-06-01 22:30:36 -070011139 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080011140 }
James Mattis45d81842021-01-10 14:24:24 -080011141 for (final Map.Entry<String, Integer> entry :
11142 preference.getNetworkPreferences().entrySet()) {
11143 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070011144 // Add the rules for all users as this policy is device wide.
11145 for (final UserHandle user : users) {
11146 try {
11147 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
11148 if (!prefToUids.contains(pref)) {
11149 prefToUids.put(pref, new ArraySet<>());
11150 }
11151 prefToUids.get(pref).add(uid);
11152 } catch (PackageManager.NameNotFoundException e) {
11153 // Although this may seem like an error scenario, it is ok that uninstalled
11154 // packages are sent on a network preference as the system will watch for
11155 // package installations associated with this network preference and update
11156 // accordingly. This is done to minimize race conditions on app install.
11157 continue;
James Mattis45d81842021-01-10 14:24:24 -080011158 }
James Mattis45d81842021-01-10 14:24:24 -080011159 }
11160 }
James Mattisb6b6a432021-06-01 22:30:36 -070011161 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080011162 }
11163
11164 private NetworkRequestInfo createNriFromOemNetworkPreferences(
11165 @OemNetworkPreferences.OemNetworkPreference final int preference,
11166 @NonNull final Set<Integer> uids) {
11167 final List<NetworkRequest> requests = new ArrayList<>();
11168 // Requests will ultimately be evaluated by order of insertion therefore it matters.
11169 switch (preference) {
11170 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
11171 requests.add(createUnmeteredNetworkRequest());
11172 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070011173 requests.add(createDefaultInternetRequestForTransport(
11174 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080011175 break;
11176 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
11177 requests.add(createUnmeteredNetworkRequest());
11178 requests.add(createOemPaidNetworkRequest());
11179 break;
11180 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
11181 requests.add(createOemPaidNetworkRequest());
11182 break;
11183 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
11184 requests.add(createOemPrivateNetworkRequest());
11185 break;
James Mattisfa270db2021-05-31 17:11:10 -070011186 case OEM_NETWORK_PREFERENCE_TEST:
11187 requests.add(createUnmeteredNetworkRequest());
11188 requests.add(createTestNetworkRequest());
11189 requests.add(createDefaultRequest());
11190 break;
11191 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
11192 requests.add(createTestNetworkRequest());
11193 break;
James Mattis45d81842021-01-10 14:24:24 -080011194 default:
11195 // This should never happen.
11196 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
11197 + " called with invalid preference of " + preference);
11198 }
11199
James Mattisfa270db2021-05-31 17:11:10 -070011200 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090011201 for (final int uid : uids) {
11202 ranges.add(new UidRange(uid, uid));
11203 }
11204 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080011205 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080011206 }
11207
11208 private NetworkRequest createUnmeteredNetworkRequest() {
11209 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11210 .addCapability(NET_CAPABILITY_NOT_METERED)
11211 .addCapability(NET_CAPABILITY_VALIDATED);
11212 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
11213 }
11214
11215 private NetworkRequest createOemPaidNetworkRequest() {
11216 // NET_CAPABILITY_OEM_PAID is a restricted capability.
11217 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11218 .addCapability(NET_CAPABILITY_OEM_PAID)
11219 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11220 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11221 }
11222
11223 private NetworkRequest createOemPrivateNetworkRequest() {
11224 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
11225 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11226 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
11227 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11228 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11229 }
11230
11231 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070011232 final NetworkCapabilities netcap = new NetworkCapabilities();
11233 netcap.addCapability(NET_CAPABILITY_INTERNET);
11234 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
11235 return netcap;
11236 }
11237
11238 private NetworkRequest createTestNetworkRequest() {
11239 final NetworkCapabilities netcap = new NetworkCapabilities();
11240 netcap.clearAll();
11241 netcap.addTransportType(TRANSPORT_TEST);
11242 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080011243 }
James Mattis47db0582021-01-01 14:13:35 -080011244 }
markchien738ad912021-12-09 18:15:45 +080011245
11246 @Override
11247 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
11248 enforceNetworkStackOrSettingsPermission();
11249
11250 try {
11251 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011252 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011253 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011254 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011255 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011256 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011257 throw new IllegalStateException(e);
11258 }
11259 }
11260
11261 @Override
11262 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
11263 enforceNetworkStackOrSettingsPermission();
11264
11265 try {
11266 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011267 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011268 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011269 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011270 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011271 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011272 throw new IllegalStateException(e);
11273 }
11274 }
markchiene1561fa2021-12-09 22:00:56 +080011275
11276 @Override
markchien3c04e662022-03-22 16:29:56 +080011277 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080011278 enforceNetworkStackOrSettingsPermission();
11279
markchien3c04e662022-03-22 16:29:56 +080011280 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
11281 int firewallRule = getFirewallRuleType(chain, rule);
11282
11283 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
11284 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
11285 }
11286
markchiene1561fa2021-12-09 22:00:56 +080011287 try {
markchien3c04e662022-03-22 16:29:56 +080011288 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011289 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080011290 throw new IllegalStateException(e);
11291 }
11292 }
markchien98a6f952022-01-13 23:43:53 +080011293
markchien3c04e662022-03-22 16:29:56 +080011294 private int getFirewallRuleType(int chain, int rule) {
11295 final int defaultRule;
11296 switch (chain) {
11297 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000011298 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
11299 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000011300 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080011301 defaultRule = FIREWALL_RULE_ALLOW;
11302 break;
11303 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
11304 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
11305 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
11306 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
11307 defaultRule = FIREWALL_RULE_DENY;
11308 break;
11309 default:
11310 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
11311 }
11312 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
11313
11314 return rule;
11315 }
11316
markchien98a6f952022-01-13 23:43:53 +080011317 @Override
11318 public void setFirewallChainEnabled(final int chain, final boolean enable) {
11319 enforceNetworkStackOrSettingsPermission();
11320
11321 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011322 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011323 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080011324 throw new IllegalStateException(e);
11325 }
11326 }
11327
markchien00a0bed2022-01-13 23:46:13 +080011328 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011329 public boolean getFirewallChainEnabled(final int chain) {
11330 enforceNetworkStackOrSettingsPermission();
11331
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000011332 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011333 }
11334
11335 @Override
markchien00a0bed2022-01-13 23:46:13 +080011336 public void replaceFirewallChain(final int chain, final int[] uids) {
11337 enforceNetworkStackOrSettingsPermission();
11338
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000011339 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080011340 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070011341}