blob: 394292e22dd0636dbb6575e239261e242117d01a [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;
Michael Groover73f69482023-01-27 11:01:25 -0600110import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800111import android.annotation.TargetApi;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800112import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800113import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700114import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700115import android.app.admin.DevicePolicyManager;
junyulaie7c7d2a2021-01-26 15:29:15 +0800116import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700117import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800118import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800119import android.content.ContentResolver;
120import android.content.Context;
121import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700122import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800123import android.content.pm.PackageManager;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700124import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900125import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900126import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700127import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800128import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800129import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800130import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900131import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800132import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900133import android.net.ConnectivityManager.RestrictBackgroundStatus;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900134import android.net.ConnectivityResources;
paulhu90a7a512021-03-17 17:19:09 +0800135import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900136import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800137import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700138import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900139import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800140import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800141import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800142import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800143import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800144import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900145import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900146import android.net.INetworkMonitor;
147import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900148import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900149import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700150import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800151import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900152import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900153import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900154import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800155import android.net.LinkProperties;
Charles He9369e612017-05-15 17:07:18 +0100156import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800157import android.net.NativeNetworkConfig;
158import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800159import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700160import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700161import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900162import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700163import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800164import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700165import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900166import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900167import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000168import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900169import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700170import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900171import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700172import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900173import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700174import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800175import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900176import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700177import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000178import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800179import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900180import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800181import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400182import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700183import android.net.QosCallbackException;
184import android.net.QosFilter;
185import android.net.QosSocketFilter;
186import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700187import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800188import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800189import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800190import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900191import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400192import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800193import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800194import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400195import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800196import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900197import android.net.VpnTransportInfo;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900198import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900199import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800200import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900201import android.net.networkstack.ModuleNetworkStackClient;
202import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900203import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800204import android.net.resolv.aidl.DnsHealthEventParcel;
205import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
206import android.net.resolv.aidl.Nat64PrefixEventParcel;
207import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900208import android.net.shared.PrivateDnsConfig;
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;
Paul Hu3c8c8102022-08-25 07:06:16 +0000214import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800215import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700216import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700217import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800218import android.os.Looper;
219import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700220import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700221import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900222import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800223import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700224import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700225import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800226import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700227import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900228import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900229import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700230import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700231import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400232import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800233import android.provider.Settings;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900234import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700235import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700236import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700237import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800238import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900239import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000240import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600241import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900242import android.util.Pair;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700243import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700244import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800245
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800246import androidx.annotation.RequiresApi;
247
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900248import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400249import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400250import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700251import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900252import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800253import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900254import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800255import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000256import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900257import com.android.net.module.util.BitUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900258import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900259import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100260import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900261import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
262import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900263import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800264import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800265import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100266import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000267import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800268import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
269import com.android.networkstack.apishim.ConstantsShim;
270import com.android.networkstack.apishim.common.BroadcastOptionsShim;
271import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Chalard Jean7284daa2019-05-30 14:58:29 +0900272import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000273import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900274import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800275import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800276import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900277import com.android.server.connectivity.ConnectivityFlags;
Erik Kline32120082017-12-13 19:40:49 +0900278import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500279import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700280import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900281import com.android.server.connectivity.FullScore;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000282import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100283import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700284import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900285import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700286import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600287import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900288import com.android.server.connectivity.NetworkNotificationManager;
289import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900290import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900291import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900292import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700293import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900294import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900295import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700296import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800297import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000298import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800299import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600300
Josh Gao461a1222020-06-16 15:58:11 -0700301import libcore.io.IoUtils;
302
The Android Open Source Project28527d22009-03-03 19:31:44 -0800303import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100304import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800305import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900306import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700307import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700308import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900309import java.net.InetSocketAddress;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700310import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700311import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700312import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700313import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800314import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900315import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800316import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700317import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700318import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700319import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700320import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900321import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700322import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900323import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600324import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900325import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600326import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900327import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800328
329/**
330 * @hide
331 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800332public class ConnectivityService extends IConnectivityManager.Stub
333 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900334 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800335
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900336 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900337 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900338 private static final String NETWORK_ARG = "networks";
339 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800340 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900341
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900342 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900343 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
344 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800345
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900346 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700347
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100348 /**
349 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
350 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800351 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100352 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
353 * (preferably via runtime resource overlays).
354 */
355 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
356 "http://connectivitycheck.gstatic.com/generate_204";
357
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700358 // TODO: create better separation between radio types and network types
359
Robert Greenwalt2034b912009-08-12 16:08:25 -0700360 // how long to wait before switching back to a radio's default network
361 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
362 // system property that can override the above value
363 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
364 "android.telephony.apn-restore";
365
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900366 // How long to wait before putting up a "This network doesn't have an Internet connection,
367 // connect anyway?" dialog after the user selects a network that doesn't validate.
368 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
369
Chalard Jean5fb43c72022-09-08 19:03:14 +0900370 // How long to wait before considering that a network is bad in the absence of any form
371 // of connectivity (valid, partial, captive portal). If none has been detected after this
372 // delay, the stack considers this network bad, which may affect how it's handled in ranking
373 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900374 // Timeout in case the "actively prefer bad wifi" feature is on
375 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
376 // Timeout in case the "actively prefer bad wifi" feature is off
377 private static final int DONT_ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900378
junyulai0ac374f2020-12-14 18:41:52 +0800379 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900380 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
381 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800382 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700383
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800384 // Delimiter used when creating the broadcast delivery group for sending
385 // CONNECTIVITY_ACTION broadcast.
386 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
387
he_won.hwang881307a2022-03-15 21:23:52 +0900388 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900389 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900390
Daniel Brightf9e945b2020-06-15 16:10:01 -0700391 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900392 @VisibleForTesting
393 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700394
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900395 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700396 @VisibleForTesting
397 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900398
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900399 @VisibleForTesting
400 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800401 @VisibleForTesting
402 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900403 // True if the cell radio of the device is capable of time-sharing.
404 @VisibleForTesting
405 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900406
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800407 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800408 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800409 private final int mReleasePendingIntentDelayMs;
410
Chalard Jean46bfbf02022-02-02 00:56:25 +0900411 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900412
Motomu Utsumif360aa62023-01-30 17:52:20 +0900413 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700414
Chalard Jean9473c982021-07-29 20:03:04 +0900415 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800416 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700417 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800418 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700419
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900420 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700421
junyulaif2c67e42018-08-07 19:50:45 +0800422 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000423 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
424 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800425 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900426 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800427
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900428 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900429 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000430 // The Context is created for UserHandle.ALL.
431 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900432 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900433 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700434 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700435 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800436
Chenbo Feng15416292018-11-08 17:36:21 -0800437 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800438 protected IDnsResolver mDnsResolver;
439 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800440 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700441 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900442 private final NetworkStatsManager mStatsManager;
443 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800444 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700445
Benedict Wong493e04b2018-11-09 14:45:34 -0800446 /**
447 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
448 * instances.
449 */
450 @GuardedBy("mTNSLock")
451 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800452 private final CompanionDeviceManagerProxyService mCdmps;
Benedict Wong493e04b2018-11-09 14:45:34 -0800453
454 private final Object mTNSLock = new Object();
455
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700456 private String mCurrentTcpBufferSizes;
457
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900458 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
lifraf3a3492021-03-10 13:58:14 +0800459 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900460
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500461 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400462 // Tear down networks that have no chance (e.g. even if validated) of becoming
463 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500464 // all networks have been rematched against all NetworkRequests.
465 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400466 // Don't reap networks. This should be passed when some networks have not yet been
467 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500468 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900469 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500470
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900471 private enum UnneededFor {
472 LINGER, // Determine whether this network is unneeded and should be lingered.
473 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
474 }
475
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700476 /**
paulhuaa0743d2021-05-26 21:56:03 +0800477 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800478 * should have priority. The order is passed to netd which will use it together
479 * with UID ranges to generate the corresponding IP rule. This serves to
480 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800481 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800482 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000483 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800484 *
paulhu48291862021-07-14 14:53:57 +0800485 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
486 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800487 */
paulhu48291862021-07-14 14:53:57 +0800488 // Used when sending to netd to code for "no order".
489 static final int PREFERENCE_ORDER_NONE = 0;
490 // Order for requests that don't code for a per-app preference. As it is
491 // out of the valid range, the corresponding order should be
492 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800493 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800494 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800495 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800496 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
497 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800498 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800499 static final int PREFERENCE_ORDER_OEM = 10;
500 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800501 // See {@link #setProfileNetworkPreference}.
502 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800503 static final int PREFERENCE_ORDER_PROFILE = 20;
504 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800505 // better scores are connected.
506 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800507 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800508 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900509 // Preference order that signifies the network shouldn't be set as a default network for
510 // the UIDs, only give them access to it. TODO : replace this with a boolean
511 // in NativeUidRangeConfig
512 @VisibleForTesting
513 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
514 // Bound for the lowest valid preference order.
515 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800516
517 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700518 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700519 * from one net to another. Clear happens when we get a new
520 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
521 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700522 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700523 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700524
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700525 /**
526 * used internally to reload global proxy settings
527 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700528 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700529
Robert Greenwalt34848c02011-03-25 13:09:25 -0700530 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400531 * PAC manager has received new port.
532 */
533 private static final int EVENT_PROXY_HAS_CHANGED = 16;
534
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700535 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900536 * used internally when registering NetworkProviders
537 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700538 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900539 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700540
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700541 /**
542 * used internally when registering NetworkAgents
543 * obj = Messenger
544 */
545 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
546
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700547 /**
548 * used to add a network request
549 * includes a NetworkRequestInfo
550 */
551 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
552
553 /**
554 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900555 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700556 * cancel it.
557 * includes a NetworkRequestInfo
558 */
559 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
560
561 /**
562 * used to add a network listener - no request
563 * includes a NetworkRequestInfo
564 */
565 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
566
567 /**
568 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400569 * arg1 = UID of caller
570 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700571 */
572 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
573
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700574 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900575 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700576 * obj = Messenger
577 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900578 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700579
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700580 /**
581 * used internally to expire a wakelock when transitioning
582 * from one net to another. Expire happens when we fail to find
583 * a new network (typically after 1 minute) -
584 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
585 * a replacement network.
586 */
587 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
588
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700589 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800590 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400591 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800592 */
593 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
594
595 /**
596 * used to remove a pending intent and its associated network request.
597 * arg1 = UID of caller
598 * obj = PendingIntent
599 */
600 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
601
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900602 /**
603 * used to specify whether a network should be used even if unvalidated.
604 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
605 * arg2 = whether to remember this choice in the future (1 or 0)
606 * obj = network
607 */
608 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
609
610 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700611 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900612 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700613 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900614
Paul Jensenc8873fc2015-06-17 14:15:39 -0400615 /**
616 * used to add a network listener with a pending intent
617 * obj = NetworkRequestInfo
618 */
619 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
620
Hugo Benichid6b510a2017-04-06 17:22:18 +0900621 /**
622 * used to specify whether a network should not be penalized when it becomes unvalidated.
623 */
624 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
625
626 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700627 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900628 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700629 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900630
Erik Kline31b4a9e2018-01-11 21:07:29 +0900631 // Handle changes in Private DNS settings.
632 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
633
dalyk1720e542018-03-05 12:42:22 -0500634 // Handle private DNS validation status updates.
635 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
636
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900637 /**
638 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
639 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800640 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
641 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
642 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900643 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900644 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900645
646 /**
647 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
648 * config was resolved.
649 * obj = PrivateDnsConfig
650 * arg2 = netid
651 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900652 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900653
654 /**
655 * Request ConnectivityService display provisioning notification.
656 * arg1 = Whether to make the notification visible.
657 * arg2 = NetID.
658 * obj = Intent to be launched when notification selected by user, null if !arg1.
659 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900660 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900661
662 /**
lucaslin2240ef62019-03-12 13:08:03 +0800663 * Used to specify whether a network should be used even if connectivity is partial.
664 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
665 * false)
666 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
667 * obj = network
668 */
lucaslin444d43a2020-02-20 16:56:59 +0800669 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800670
671 /**
lucasline117e2e2019-10-22 18:27:33 +0800672 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
673 * Both of the arguments are bitmasks, and the value of bits come from
674 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900675 * arg1 = unused
676 * arg2 = netId
677 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800678 */
lucaslin444d43a2020-02-20 16:56:59 +0800679 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800680
681 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900682 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
683 * arg1 = unused
684 * arg2 = netId
685 * obj = captive portal data
686 */
lucaslin444d43a2020-02-20 16:56:59 +0800687 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900688
689 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900690 * Used by setRequireVpnForUids.
691 * arg1 = whether the specified UID ranges are required to use a VPN.
692 * obj = Array of UidRange objects.
693 */
694 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
695
696 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900697 * Used internally when setting the default networks for OemNetworkPreferences.
698 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800699 */
700 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
701
702 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800703 * Used to indicate the system default network becomes active.
704 */
705 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
706
707 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900708 * Used internally when setting a network preference for a user profile.
709 * obj = Pair<ProfileNetworkPreference, Listener>
710 */
711 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
712
713 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000714 * Event to specify that reasons for why an uid is blocked changed.
715 * arg1 = uid
716 * arg2 = blockedReasons
717 */
718 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
719
720 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900721 * Event to register a new network offer
722 * obj = NetworkOffer
723 */
724 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
725
726 /**
727 * Event to unregister an existing network offer
728 * obj = INetworkOfferCallback
729 */
730 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
731
732 /**
paulhu51f77dc2021-06-07 02:34:20 +0000733 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
734 */
735 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
736
737 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800738 * Event to set temporary allow bad wifi within a limited time to override
739 * {@code config_networkAvoidBadWifi}.
740 */
741 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
742
743 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100744 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
745 */
746 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
747
748 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900749 * The initial evaluation period is over for this network.
750 *
751 * If no form of connectivity has been found on this network (valid, partial, captive portal)
752 * then the stack will now consider it to have been determined bad.
753 */
754 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
755
756 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000757 * Used internally when the user does not want the network from captive portal app.
758 * obj = Network
759 */
760 private static final int EVENT_USER_DOES_NOT_WANT = 58;
761
762 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000763 * Event to set VPN as preferred network for specific apps.
764 * obj = VpnNetworkPreferenceInfo
765 */
766 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
767
768 /**
chiachangwange0192a72023-02-06 13:25:01 +0000769 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
770 */
771 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
772
773 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900774 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
775 * should be shown.
776 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900777 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900778
779 /**
780 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
781 * should be hidden.
782 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900783 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900784
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800785 /**
786 * The maximum alive time to allow bad wifi configuration for testing.
787 */
788 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
789
Patrick Rohr2857ac42022-01-21 14:58:16 +0100790 /**
chiachangwange0192a72023-02-06 13:25:01 +0000791 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
792 * testing.
793 */
794 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
795
796 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100797 * The priority of the tc police rate limiter -- smaller value is higher priority.
798 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
799 */
800 private static final short TC_PRIO_POLICE = 1;
801
802 /**
803 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
804 */
805 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700806 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100807
Hugo Benichi47011212017-03-30 10:46:05 +0900808 private static String eventName(int what) {
809 return sMagicDecoderRing.get(what, Integer.toString(what));
810 }
811
paulhua10d8212020-11-10 15:32:56 +0800812 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900813 final DnsResolverServiceManager dsm = context.getSystemService(
814 DnsResolverServiceManager.class);
815 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800816 }
817
Cody Kesting73708bf2019-12-18 10:57:50 -0800818 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900819 @VisibleForTesting
820 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700821 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700822 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700823 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700824 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800825 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
826 @VisibleForTesting
827 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
828
Erik Kline32120082017-12-13 19:40:49 +0900829 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900830 @VisibleForTesting
831 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700832
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400833 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800834 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400835
Chalard Jean46bfbf02022-02-02 00:56:25 +0900836 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800837 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700838
Chalard Jean5d70ba42018-06-07 16:44:04 +0900839 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
840 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000841 @VisibleForTesting
842 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400843
Erik Kline05f2b402015-04-30 12:58:40 +0900844 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700845
Chalard Jean46bfbf02022-02-02 00:56:25 +0900846 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400847
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700848 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900849 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700850
Valentin Iftime9fa35092019-09-24 13:32:13 +0200851 private Set<String> mWolSupportedInterfaces;
852
Roshan Pius08c94fb2020-01-16 12:17:17 -0800853 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800854 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800855 private final AppOpsManager mAppOpsManager;
856
857 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400858
chiachangwang3d60bac2023-01-17 14:38:08 +0000859 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900860 private final QosCallbackTracker mQosCallbackTracker;
861 private final NetworkNotificationManager mNotifier;
862 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900863
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700864 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800865 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700866
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900867 // Sequence number for NetworkProvider IDs.
868 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
869 NetworkProvider.FIRST_PROVIDER_ID);
870
Erik Klineedf878b2015-07-09 18:24:03 +0900871 // NetworkRequest activity String log entries.
872 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
873 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
874
Hugo Benichid159fdd2016-07-11 11:05:12 +0900875 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900876 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900877 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
878
Hugo Benichi47011212017-03-30 10:46:05 +0900879 private static final int MAX_WAKELOCK_LOGS = 20;
880 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900881 private int mTotalWakelockAcquisitions = 0;
882 private int mTotalWakelockReleases = 0;
883 private long mTotalWakelockDurationMs = 0;
884 private long mMaxWakelockDurationMs = 0;
885 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900886
Hugo Benichi208c0102016-07-28 17:53:06 +0900887 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900888
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700889 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900890 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700891
Erik Kline95ecfee2016-10-02 18:02:14 +0900892 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900893 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900894
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900895 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800896 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
897 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800898
Patrick Rohr2857ac42022-01-21 14:58:16 +0100899 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
900 // configured via {@link
901 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
902 // Only the handler thread is allowed to access this field.
903 private long mIngressRateLimit = -1;
904
Robert Greenwalt802c1102014-06-02 15:32:02 -0700905 /**
906 * Implements support for the legacy "one network per network type" model.
907 *
908 * We used to have a static array of NetworkStateTrackers, one for each
909 * network type, but that doesn't work any more now that we can have,
910 * for example, more that one wifi network. This class stores all the
911 * NetworkAgentInfo objects that support a given type, but the legacy
912 * API will only see the first one.
913 *
914 * It serves two main purposes:
915 *
916 * 1. Provide information about "the network for a given type" (since this
917 * API only supports one).
918 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
919 * the first network for a given type changes, or if the default network
920 * changes.
921 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900922 @VisibleForTesting
923 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900924
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900925 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900926 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900927
Robert Greenwalt802c1102014-06-02 15:32:02 -0700928 /**
929 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
930 * Each list holds references to all NetworkAgentInfos that are used to
931 * satisfy requests for that network type.
932 *
933 * This array is built out at startup such that an unsupported network
934 * doesn't get an ArrayList instance, making this a tristate:
935 * unsupported, supported but not active and active.
936 *
937 * The actual lists are populated when we scan the network types that
938 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900939 *
940 * Threading model:
941 * - addSupportedType() is only called in the constructor
942 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
943 * They are therefore not thread-safe with respect to each other.
944 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
945 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900946 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900947 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700948 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900949 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900950 @NonNull
951 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700952
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900953 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
954 // an entry have no timer (equivalent to -1). Lazily loaded.
955 @NonNull
956 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
957
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900958 LegacyTypeTracker(@NonNull ConnectivityService service) {
959 mService = service;
960 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700961 }
962
Chiachang Wang3bc52762021-11-25 14:17:57 +0800963 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
964 // addressed.
965 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900966 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
967 final PackageManager pm = ctx.getPackageManager();
968 if (pm.hasSystemFeature(FEATURE_WIFI)) {
969 addSupportedType(TYPE_WIFI);
970 }
971 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
972 addSupportedType(TYPE_WIFI_P2P);
973 }
974 if (tm.isDataCapable()) {
975 // Telephony does not have granular support for these types: they are either all
976 // supported, or none is supported
977 addSupportedType(TYPE_MOBILE);
978 addSupportedType(TYPE_MOBILE_MMS);
979 addSupportedType(TYPE_MOBILE_SUPL);
980 addSupportedType(TYPE_MOBILE_DUN);
981 addSupportedType(TYPE_MOBILE_HIPRI);
982 addSupportedType(TYPE_MOBILE_FOTA);
983 addSupportedType(TYPE_MOBILE_IMS);
984 addSupportedType(TYPE_MOBILE_CBS);
985 addSupportedType(TYPE_MOBILE_IA);
986 addSupportedType(TYPE_MOBILE_EMERGENCY);
987 }
988 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
989 addSupportedType(TYPE_BLUETOOTH);
990 }
991 if (pm.hasSystemFeature(FEATURE_WATCH)) {
992 // TYPE_PROXY is only used on Wear
993 addSupportedType(TYPE_PROXY);
994 }
995 // Ethernet is often not specified in the configs, although many devices can use it via
996 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +0000997 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900998 addSupportedType(TYPE_ETHERNET);
999 }
1000
1001 // Always add TYPE_VPN as a supported type
1002 addSupportedType(TYPE_VPN);
1003 }
1004
1005 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001006 if (mTypeLists[type] != null) {
1007 throw new IllegalStateException(
1008 "legacy list for type " + type + "already initialized");
1009 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001010 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001011 }
1012
Robert Greenwalt802c1102014-06-02 15:32:02 -07001013 public boolean isTypeSupported(int type) {
1014 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1015 }
1016
1017 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001018 synchronized (mTypeLists) {
1019 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1020 return mTypeLists[type].get(0);
1021 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001022 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001023 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001024 }
1025
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001026 public int getRestoreTimerForType(int type) {
1027 synchronized (mTypeLists) {
1028 if (mRestoreTimers == null) {
1029 mRestoreTimers = loadRestoreTimers();
1030 }
1031 return mRestoreTimers.getOrDefault(type, -1);
1032 }
1033 }
1034
1035 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1036 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001037 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001038 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1039 for (final String config : configs) {
1040 final String[] splits = TextUtils.split(config, ",");
1041 if (splits.length != 2) {
1042 logwtf("Invalid restore timer token count: " + config);
1043 continue;
1044 }
1045 try {
1046 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1047 } catch (NumberFormatException e) {
1048 logwtf("Invalid restore timer number format: " + config, e);
1049 }
1050 }
1051 return ret;
1052 }
1053
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001054 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001055 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001056 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001057 log("Sending " + state
1058 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001059 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001060 }
1061 }
1062
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001063 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1064 // network type, to preserve previous behaviour.
1065 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1066 if (vpnNai != mService.getLegacyLockdownNai()) return;
1067
1068 if (vpnNai.declaredUnderlyingNetworks == null
1069 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1070 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1071 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1072 return;
1073 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001074 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001075 vpnNai.declaredUnderlyingNetworks[0]);
1076 if (underlyingNai == null) return;
1077
1078 final int type = underlyingNai.networkInfo.getType();
1079 final DetailedState state = DetailedState.CONNECTED;
1080 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1081 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1082 }
1083
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001084 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001085 public void add(int type, NetworkAgentInfo nai) {
1086 if (!isTypeSupported(type)) {
1087 return; // Invalid network type.
1088 }
1089 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1090
1091 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1092 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001093 return;
1094 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001095 synchronized (mTypeLists) {
1096 list.add(nai);
1097 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001098
Chalard Jean5b409c72021-02-04 13:12:59 +09001099 // Send a broadcast if this is the first network of its type or if it's the default.
1100 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001101
1102 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1103 // to preserve previous behaviour.
1104 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001105 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001106 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1107 mService.sendLegacyNetworkBroadcast(nai, state, type);
1108 }
1109
1110 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1111 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001112 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001113 }
1114
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001115 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001116 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001117 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1118 if (list == null || list.isEmpty()) {
1119 return;
1120 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001121 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001122
Hugo Benichi389633f2016-06-21 09:48:07 +09001123 synchronized (mTypeLists) {
1124 if (!list.remove(nai)) {
1125 return;
1126 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001127 }
1128
Lorenzo Colitti49767722015-05-01 00:30:10 +09001129 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001130 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1131 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001132 }
1133
1134 if (!list.isEmpty() && wasFirstNetwork) {
1135 if (DBG) log("Other network available for type " + type +
1136 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001137 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001138 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001139 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001140 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001141 }
1142 }
1143
1144 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001145 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1146 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001147 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001148 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001149 }
1150 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001151
Chalard Jean46bfbf02022-02-02 00:56:25 +09001152 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001153 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001154 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001155 final DetailedState state = nai.networkInfo.getDetailedState();
1156 for (int type = 0; type < mTypeLists.length; type++) {
1157 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001158 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001159 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001160 if (isFirst || contains && isDefault) {
1161 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001162 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001163 }
1164 }
1165 }
1166
Robert Greenwalt94e22142014-07-30 16:31:24 -07001167 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001168 pw.println("mLegacyTypeTracker:");
1169 pw.increaseIndent();
1170 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001171 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001172 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001173 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001174 pw.println();
1175 pw.println("Current state:");
1176 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001177 synchronized (mTypeLists) {
1178 for (int type = 0; type < mTypeLists.length; type++) {
1179 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1180 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001181 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001182 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001183 }
1184 }
1185 pw.decreaseIndent();
1186 pw.decreaseIndent();
1187 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001188 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001189 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001190 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001191
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001192 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001193 /**
1194 * Helper class which parses out priority arguments and dumps sections according to their
1195 * priority. If priority arguments are omitted, function calls the legacy dump command.
1196 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001197 private class LocalPriorityDump {
1198 private static final String PRIORITY_ARG = "--dump-priority";
1199 private static final String PRIORITY_ARG_HIGH = "HIGH";
1200 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1201
1202 LocalPriorityDump() {}
1203
1204 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1205 doDump(fd, pw, new String[] {DIAG_ARG});
1206 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001207 }
1208
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001209 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1210 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001211 }
1212
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001213 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1214 if (args == null) {
1215 dumpNormal(fd, pw, args);
1216 return;
1217 }
1218
1219 String priority = null;
1220 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1221 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1222 argIndex++;
1223 priority = args[argIndex];
1224 }
1225 }
1226
1227 if (PRIORITY_ARG_HIGH.equals(priority)) {
1228 dumpHigh(fd, pw);
1229 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1230 dumpNormal(fd, pw, args);
1231 } else {
1232 // ConnectivityService publishes binder service using publishBinderService() with
1233 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001234 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1235 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001236 // TODO: Integrate into signal dump.
1237 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001238 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001239 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001240 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001241
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001242 /**
1243 * Dependencies of ConnectivityService, for injection in tests.
1244 */
1245 @VisibleForTesting
1246 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001247 public int getCallingUid() {
1248 return Binder.getCallingUid();
1249 }
1250
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001251 /**
1252 * Get system properties to use in ConnectivityService.
1253 */
1254 public MockableSystemProperties getSystemProperties() {
1255 return new MockableSystemProperties();
1256 }
1257
1258 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001259 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1260 */
1261 public ConnectivityResources getResources(@NonNull Context ctx) {
1262 return new ConnectivityResources(ctx);
1263 }
1264
1265 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001266 * Create a HandlerThread to use in ConnectivityService.
1267 */
1268 public HandlerThread makeHandlerThread() {
1269 return new HandlerThread("ConnectivityServiceThread");
1270 }
1271
1272 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001273 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001274 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001275 public NetworkStackClientBase getNetworkStack() {
1276 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001277 }
1278
1279 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001280 * @see ProxyTracker
1281 */
1282 public ProxyTracker makeProxyTracker(@NonNull Context context,
1283 @NonNull Handler connServiceHandler) {
1284 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1285 }
1286
1287 /**
1288 * @see NetIdManager
1289 */
1290 public NetIdManager makeNetIdManager() {
1291 return new NetIdManager();
1292 }
1293
1294 /**
1295 * @see NetworkUtils#queryUserAccess(int, int)
1296 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001297 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1298 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001299 }
1300
1301 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001302 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1303 * requires CAP_NET_ADMIN, which the unit tests do not have.
1304 */
1305 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1306 InetSocketAddress remote) {
1307 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1308 }
1309
1310 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001311 * @see MultinetworkPolicyTracker
1312 */
1313 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1314 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1315 return new MultinetworkPolicyTracker(c, h, r);
1316 }
1317
Aaron Huang330a4c02020-10-27 03:36:19 +08001318 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001319 * @see AutomaticOnOffKeepaliveTracker
1320 */
1321 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1322 @NonNull Context c, @NonNull Handler h) {
1323 return new AutomaticOnOffKeepaliveTracker(c, h);
1324 }
1325
1326 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001327 * @see BatteryStatsManager
1328 */
1329 public void reportNetworkInterfaceForTransports(Context context, String iface,
1330 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001331 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001332 context.getSystemService(BatteryStatsManager.class);
1333 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1334 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001335
1336 public boolean getCellular464XlatEnabled() {
1337 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1338 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001339
1340 /**
1341 * @see PendingIntent#intentFilterEquals
1342 */
1343 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1344 return a.intentFilterEquals(b);
1345 }
1346
1347 /**
1348 * @see LocationPermissionChecker
1349 */
1350 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1351 return new LocationPermissionChecker(context);
1352 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001353
1354 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001355 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001356 *
1357 * This method returns null in versions before T, where carrier privilege
1358 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001359 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001360 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001361 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1362 @NonNull final Context context, @NonNull final TelephonyManager tm) {
1363 if (SdkLevel.isAtLeastT()) {
1364 return new CarrierPrivilegeAuthenticator(context, tm);
1365 } else {
1366 return null;
1367 }
1368 }
1369
1370 /**
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001371 * @see DeviceConfigUtils#isFeatureEnabled
1372 */
1373 public boolean isFeatureEnabled(Context context, String name, boolean defaultEnabled) {
1374 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, name,
1375 TETHERING_MODULE_NAME, defaultEnabled);
1376 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001377
1378 /**
1379 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001380 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001381 * @return BpfNetMaps implementation.
1382 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001383 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1384 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001385 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001386
1387 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001388 * @see ClatCoordinator
1389 */
1390 public ClatCoordinator getClatCoordinator(INetd netd) {
1391 return new ClatCoordinator(
1392 new ClatCoordinator.Dependencies() {
1393 @NonNull
1394 public INetd getNetd() {
1395 return netd;
1396 }
1397 });
1398 }
1399
1400 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001401 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1402 */
1403 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1404 final InterfaceParams params = InterfaceParams.getByName(iface);
1405 if (params == null) {
1406 // the interface might have disappeared.
1407 logw("Failed to get interface params for interface " + iface);
1408 return;
1409 }
1410 try {
1411 // converting rateInBytesPerSecond from long to int is safe here because the
1412 // setting's range is limited to INT_MAX.
1413 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001414 Log.i(TAG,
1415 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001416 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1417 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1418 } catch (IOException e) {
1419 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1420 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1421 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1422 + ") failure: ", e);
1423 }
1424 }
1425
1426 /**
1427 * Wraps {@link TcUtils#tcFilterDelDev}
1428 */
1429 public void disableIngressRateLimit(String iface) {
1430 final InterfaceParams params = InterfaceParams.getByName(iface);
1431 if (params == null) {
1432 // the interface might have disappeared.
1433 logw("Failed to get interface params for interface " + iface);
1434 return;
1435 }
1436 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001437 Log.i(TAG,
1438 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001439 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1440 } catch (IOException e) {
1441 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1442 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1443 }
1444 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001445
1446 /**
1447 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1448 */
1449 // TODO: when available in all active branches:
1450 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1451 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1452 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1453 return BroadcastOptionsShimImpl.newInstance(options);
1454 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001455 }
1456
junyulaie7c7d2a2021-01-26 15:29:15 +08001457 public ConnectivityService(Context context) {
1458 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001459 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1460 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001461 }
1462
1463 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001464 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1465 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001466 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001467
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001468 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001469 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001470 mSystemProperties = mDeps.getSystemProperties();
1471 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001472 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001473 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001474 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1475 // Pass limit - 1 to maintain backward compatibility.
1476 // TODO: Remove the workaround.
1477 mNetworkRequestCounter =
1478 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1479 mSystemNetworkRequestCounter =
1480 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001481
Hugo Benichi208c0102016-07-28 17:53:06 +09001482 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001483 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1484 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001485 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001486 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001487 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001488 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1489 mDefaultNetworkRequests.add(mDefaultRequest);
1490 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001491
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001492 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001493 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001494
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001495 // The default WiFi request is a background request so that apps using WiFi are
1496 // migrated to a better network (typically ethernet) when one comes up, instead
1497 // of staying on WiFi forever.
1498 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1499 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1500
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001501 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1502 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1503 NetworkRequest.Type.BACKGROUND_REQUEST);
1504
Chalard Jean0702f982021-09-16 21:50:07 +09001505 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1506 // TODO: Consider making the timer customizable.
1507 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1508 mCellularRadioTimesharingCapable =
1509 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1510
Paul Hu51f816b2022-08-11 14:43:47 +00001511 mNetd = netd;
1512 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001513 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001514 mPermissionMonitor =
1515 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001516 mHandlerThread.start();
1517 mHandler = new InternalHandler(mHandlerThread.getLooper());
1518 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001519 mConnectivityDiagnosticsHandler =
1520 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001521
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001522 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001523 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001524
junyulaie7c7d2a2021-01-26 15:29:15 +08001525 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001526 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001527 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001528 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001529
Wink Saville32506bc2013-06-29 21:10:57 -07001530 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001531 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001532 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001533 mCarrierPrivilegeAuthenticator =
1534 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001535
Sudheer Shanka9967d462021-03-18 19:09:25 +00001536 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001537 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1538 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001539 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001540
1541 final PowerManager powerManager = (PowerManager) context.getSystemService(
1542 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001543 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001544 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001545
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001546 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1547 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001548 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001549 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001550 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001551 mProtectedNetworks.add(p);
1552 } else {
1553 if (DBG) loge("Ignoring protectedNetwork " + p);
1554 }
1555 }
1556
soma, kawata29444ae2019-05-23 09:30:40 +09001557 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1558
James Mattis02220e22021-03-13 19:27:21 -08001559 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001560 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001561 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001562 final IntentFilter userIntentFilter = new IntentFilter();
1563 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1564 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1565 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1566 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001567
James Mattis02220e22021-03-13 19:27:21 -08001568 // Listen to package add/removes for netd
1569 final IntentFilter packageIntentFilter = new IntentFilter();
1570 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1571 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1572 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1573 packageIntentFilter.addDataScheme("package");
1574 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001575 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001576
lucaslind5c2d072021-02-20 18:59:47 +08001577 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001578
Chalard Jean46bfbf02022-02-02 00:56:25 +09001579 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001580 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001581 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001582 } catch (RemoteException | ServiceSpecificException e) {
1583 loge("Error registering event listener :" + e);
1584 }
1585
Erik Kline05f2b402015-04-30 12:58:40 +09001586 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1587 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001588
chiachangwang7c17c282023-02-02 05:58:59 +00001589 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001590 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001591 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001592
1593 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001594 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001595 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1596 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001597 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001598 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1599 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001600
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001601 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001602 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001603 mNetworkRanker =
1604 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1605
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001606 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001607
Chiachang Wangc1215d32020-10-20 15:38:58 +08001608 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001609 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001610
Chalard Jean28018572020-12-21 18:36:52 +09001611 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1612 // request that doesn't allow fallback to the default network. It should never be visible
1613 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1614 // arguments like the handler or the DnsResolver.
1615 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001616 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001617 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001618 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001619 new LinkProperties(), new NetworkCapabilities(),
1620 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001621 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1622 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001623
1624 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001625 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1626 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1627 // Even if it could, running on S would at least require mocking out the BPF map,
1628 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1629 // the bpf syscall. http://aosp/1907693
1630 if (SdkLevel.isAtLeastT()) {
1631 mDscpPolicyTracker = new DscpPolicyTracker();
1632 }
Tyler Wear72388212021-09-09 14:49:02 -07001633 } catch (ErrnoException e) {
1634 loge("Unable to create DscpPolicyTracker");
1635 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001636
1637 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1638 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001639
1640 if (SdkLevel.isAtLeastT()) {
1641 mCdmps = new CompanionDeviceManagerProxyService(context);
1642 } else {
1643 mCdmps = null;
1644 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001645 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001646
Xiao Ma0a171c02022-01-23 16:14:51 +00001647 /**
1648 * Check whether or not the device supports Ethernet transport.
1649 */
1650 public static boolean deviceSupportsEthernet(final Context context) {
1651 final PackageManager pm = context.getPackageManager();
1652 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1653 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1654 }
1655
Chalard Jean46adcf32018-04-18 20:18:38 +09001656 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001657 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1658 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001659 }
1660
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001661 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1662 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001663 final NetworkCapabilities netCap = new NetworkCapabilities();
1664 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001665 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001666 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001667 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001668 return netCap;
1669 }
1670
James Mattis45d81842021-01-10 14:24:24 -08001671 private NetworkRequest createDefaultRequest() {
1672 return createDefaultInternetRequestForTransport(
1673 TYPE_NONE, NetworkRequest.Type.REQUEST);
1674 }
1675
lucaslin3ba7cc22022-12-19 02:35:33 +00001676 private NetworkRequest createVpnRequest() {
1677 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1678 .withoutDefaultCapabilities()
1679 .addTransportType(TRANSPORT_VPN)
1680 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1681 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1682 .build();
1683 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1684 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1685 }
1686
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001687 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001688 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001689 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001690 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001691 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001692 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001693 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001694 netCap.addTransportType(transportType);
1695 }
James Mattis45d81842021-01-10 14:24:24 -08001696 return createNetworkRequest(type, netCap);
1697 }
1698
1699 private NetworkRequest createNetworkRequest(
1700 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001701 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001702 }
1703
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001704 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1705 NetworkRequest.Type type) {
1706 final NetworkCapabilities netCap = new NetworkCapabilities();
1707 netCap.clearAll();
1708 netCap.addCapability(capability);
1709 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1710 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1711 }
1712
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001713 // Used only for testing.
1714 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001715 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001716 // changing ContentResolver to make registerContentObserver non-final).
1717 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1718 // by subclassing SettingsObserver.
1719 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001720 void updateAlwaysOnNetworks() {
1721 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001722 }
1723
Erik Kline9a62f012018-03-21 07:18:33 -07001724 // See FakeSettingsProvider comment above.
1725 @VisibleForTesting
1726 void updatePrivateDnsSettings() {
1727 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1728 }
1729
paulhu51f77dc2021-06-07 02:34:20 +00001730 @VisibleForTesting
1731 void updateMobileDataPreferredUids() {
1732 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1733 }
1734
Patrick Rohr2857ac42022-01-21 14:58:16 +01001735 @VisibleForTesting
1736 void updateIngressRateLimit() {
1737 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1738 }
1739
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001740 private void handleAlwaysOnNetworkRequest(
1741 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001742 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001743 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001744 handleAlwaysOnNetworkRequest(networkRequest, enable);
1745 }
1746
1747 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001748 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001749 if (enable == isEnabled) {
1750 return; // Nothing to do.
1751 }
1752
1753 if (enable) {
1754 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001755 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001756 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001757 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001758 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001759 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1760 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001761 }
1762 }
1763
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001764 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001765 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1766 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1767 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1768 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001769 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1770 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001771 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001772 }
1773
paulhu51f77dc2021-06-07 02:34:20 +00001774 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001775 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001776 private void registerSettingsCallbacks() {
1777 // Watch for global HTTP proxy changes.
1778 mSettingsObserver.observe(
1779 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1780 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1781
Chalard Jean46bfbf02022-02-02 00:56:25 +09001782 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09001783 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001784 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001785 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1786
Chalard Jean46bfbf02022-02-02 00:56:25 +09001787 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001788 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001789 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001790 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001791
1792 // Watch for mobile data preferred uids changes.
1793 mSettingsObserver.observe(
1794 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1795 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001796
1797 // Watch for ingress rate limit changes.
1798 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01001799 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01001800 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
1801 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001802 }
1803
Erik Kline31b4a9e2018-01-11 21:07:29 +09001804 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001805 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1806 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001807 }
1808 }
1809
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001810 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001811 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1812 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001813 return mNextNetworkRequestId++;
1814 }
1815
junyulai74f9a8b2018-06-13 15:00:37 +08001816 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09001817 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08001818 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001819 if (network == null) {
1820 return null;
1821 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001822 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001823 }
1824
1825 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001826 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001827 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001828 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001829 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001830
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001831 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001832 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001833 private NetworkAgentInfo getVpnForUid(int uid) {
1834 synchronized (mNetworkForNetId) {
1835 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1836 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09001837 if (nai.isVPN() && nai.everConnected()
1838 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001839 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001840 }
1841 }
1842 }
1843 return null;
1844 }
1845
Chalard Jean46bfbf02022-02-02 00:56:25 +09001846 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001847 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001848 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001849 final NetworkAgentInfo nai = getVpnForUid(uid);
1850 if (nai != null) return nai.declaredUnderlyingNetworks;
1851 return null;
1852 }
1853
Lorenzo Colittia7574052021-01-19 01:33:05 +09001854 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001855 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001856
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001857 final Network[] networks = getVpnUnderlyingNetworks(uid);
1858 if (networks != null) {
1859 // getUnderlyingNetworks() returns:
1860 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1861 // empty array => the VPN explicitly said "no default network".
1862 // non-empty array => the VPN specified one or more default networks; we use the
1863 // first one.
1864 if (networks.length > 0) {
1865 nai = getNetworkAgentInfoForNetwork(networks[0]);
1866 } else {
1867 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001868 }
1869 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001870 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001871 }
1872
1873 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001874 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001875 */
paulhu7aeba372020-12-30 00:42:19 +08001876 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1877 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001878 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001879 if (ignoreBlocked) {
1880 return false;
1881 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001882 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001883 final long ident = Binder.clearCallingIdentity();
1884 try {
1885 final boolean metered = nc == null ? true : nc.isMetered();
1886 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1887 } finally {
1888 Binder.restoreCallingIdentity(ident);
1889 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001890 }
1891
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001892 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001893 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1894 return;
1895 }
Hugo Benichi47011212017-03-30 10:46:05 +09001896 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001897 synchronized (mBlockedAppUids) {
1898 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001899 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001900 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001901 blocked = false;
1902 } else {
1903 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001904 }
1905 }
Hugo Benichi47011212017-03-30 10:46:05 +09001906 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1907 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1908 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001909 }
1910
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001911 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001912 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1913 return;
1914 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001915 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001916 final int requestId = nri.getActiveRequest() != null
1917 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001918 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001919 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001920 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001921 }
1922
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001923 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001924 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001925 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001926 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001927 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001928 @NonNull
1929 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1930 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001931 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1932 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1933 // but only exists if an app asks about them or requests them. Ensure the requesting app
1934 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001935 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001936 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1937 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1938 null /* extraInfo */);
1939 }
1940 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001941 return filtered;
1942 }
1943
1944 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1945 boolean ignoreBlocked) {
1946 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1947 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001948 }
1949
1950 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001951 * Return NetworkInfo for the active (i.e., connected) network interface.
1952 * It is assumed that at most one network is active at a time. If more
1953 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001954 * @return the info for the active network, or {@code null} if none is
1955 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001956 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001957 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001958 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001959 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001960 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001961 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001962 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1963 if (nai == null) return null;
1964 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1965 maybeLogBlockedNetworkInfo(networkInfo, uid);
1966 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001967 }
1968
Paul Jensen1f567382015-02-13 14:18:39 -05001969 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001970 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001971 public Network getActiveNetwork() {
1972 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001973 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00001974 }
1975
1976 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001977 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001978 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08001979 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001980 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001981 }
1982
Chalard Jean46bfbf02022-02-02 00:56:25 +09001983 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001984 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001985 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1986 if (vpnNai != null) {
1987 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1988 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1989 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09001990 }
Paul Jensen1f567382015-02-13 14:18:39 -05001991 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001992
James Mattis2516da32021-01-31 17:06:19 -08001993 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001994 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1995 ignoreBlocked)) {
1996 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001997 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001998 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05001999 }
2000
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002001 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002002 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002003 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002004 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002005 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2006 if (nai == null) return null;
2007 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002008 }
2009
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002010 /** Returns a NetworkInfo object for a network that doesn't exist. */
2011 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2012 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2013 getNetworkTypeName(networkType), "" /* subtypeName */);
2014 info.setIsAvailable(true);
2015 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2016 // background data is restricted.
2017 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2018 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2019 ? DetailedState.BLOCKED
2020 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002021 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2022 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002023 return info;
2024 }
2025
Lorenzo Colittia7574052021-01-19 01:33:05 +09002026 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002027 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2028 return null;
2029 }
2030 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002031 if (nai == null) {
2032 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002033 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002034 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2035 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002036 }
2037
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002038 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002039 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002040 public NetworkInfo getNetworkInfo(int networkType) {
2041 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002042 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002043 if (getVpnUnderlyingNetworks(uid) != null) {
2044 // A VPN is active, so we may need to return one of its underlying networks. This
2045 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002046 // getNetworkAgentInfoForUid.
2047 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2048 if (nai == null) return null;
2049 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2050 if (networkInfo.getType() == networkType) {
2051 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002052 }
2053 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002054 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002055 }
2056
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002057 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002058 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002059 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002060 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002061 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002062 if (nai == null) return null;
2063 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002064 }
2065
2066 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002067 public NetworkInfo[] getAllNetworkInfo() {
2068 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002069 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002070 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2071 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002072 NetworkInfo info = getNetworkInfo(networkType);
2073 if (info != null) {
2074 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002075 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002076 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002077 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002078 }
2079
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002080 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002081 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002082 public Network getNetworkForType(int networkType) {
2083 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002084 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2085 return null;
2086 }
2087 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2088 if (nai == null) {
2089 return null;
2090 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002091 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002092 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2093 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002094 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002095 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002096 }
2097
2098 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002099 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002100 public Network[] getAllNetworks() {
2101 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002102 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002103 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002104 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002105 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002106 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002107 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002108 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002109 }
2110
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002111 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002112 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002113 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002114 // The basic principle is: if an app's traffic could possibly go over a
2115 // network, without the app doing anything multinetwork-specific,
2116 // (hence, by "default"), then include that network's capabilities in
2117 // the array.
2118 //
2119 // In the normal case, app traffic only goes over the system's default
2120 // network connection, so that's the only network returned.
2121 //
2122 // With a VPN in force, some app traffic may go into the VPN, and thus
2123 // over whatever underlying networks the VPN specifies, while other app
2124 // traffic may go over the system default network (e.g.: a split-tunnel
2125 // VPN, or an app disallowed by the VPN), so the set of networks
2126 // returned includes the VPN's underlying networks and the system
2127 // default.
2128 enforceAccessPermission();
2129
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002130 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002131
James Mattis2516da32021-01-31 17:06:19 -08002132 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2133 if (!nri.isBeingSatisfied()) {
2134 continue;
2135 }
2136 final NetworkAgentInfo nai = nri.getSatisfier();
2137 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2138 if (null != nc
2139 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2140 && !result.containsKey(nai.network)) {
2141 result.put(
2142 nai.network,
2143 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002144 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002145 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2146 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002147 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002148 }
2149
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002150 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002151 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002152 if (null != networks) {
2153 for (final Network network : networks) {
2154 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2155 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002156 result.put(
2157 network,
2158 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002159 nc,
2160 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002161 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002162 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002163 }
2164 }
2165 }
2166
2167 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2168 out = result.values().toArray(out);
2169 return out;
2170 }
2171
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002172 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002173 public boolean isNetworkSupported(int networkType) {
2174 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002175 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002176 }
2177
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002178 /**
2179 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002180 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002181 * @return the ip properties for the active network, or {@code null} if
2182 * none is active
2183 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002184 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002185 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002186 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002187 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002188 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2189 if (nai == null) return null;
2190 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002191 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002192 }
2193
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002194 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002195 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002196 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002197 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002198 final LinkProperties lp = getLinkProperties(nai);
2199 if (lp == null) return null;
2200 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002201 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002202 }
2203
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002204 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002205 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002206 public LinkProperties getLinkProperties(Network network) {
2207 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002208 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2209 if (lp == null) return null;
2210 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002211 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002212 }
2213
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002214 @Nullable
2215 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002216 if (nai == null) {
2217 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002218 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002219 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002220 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002221 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002222 }
2223
lucaslinc582d502022-01-27 09:07:00 +08002224 @Override
2225 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002226 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002227 @NonNull String packageName, @Nullable String callingAttributionTag) {
2228 Objects.requireNonNull(packageName);
2229 Objects.requireNonNull(lp);
2230 enforceNetworkStackOrSettingsPermission();
2231 if (!checkAccessPermission(-1 /* pid */, uid)) {
2232 return null;
2233 }
2234 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2235 }
2236
Qingxi Lib2748102020-01-08 12:51:49 -08002237 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2238 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2239 }
2240
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002241 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002242 if (nai == null) return null;
2243 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002244 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002245 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002246 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002247 }
2248
2249 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002250 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2251 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002252 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002253 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002254 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002255 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002256 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002257 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002258 }
2259
lucaslinc582d502022-01-27 09:07:00 +08002260 @Override
lucaslind2b06132022-03-02 10:56:57 +08002261 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2262 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2263 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002264 Objects.requireNonNull(nc);
2265 Objects.requireNonNull(packageName);
2266 enforceNetworkStackOrSettingsPermission();
2267 if (!checkAccessPermission(-1 /* pid */, uid)) {
2268 return null;
2269 }
2270 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2271 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2272 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2273 callingAttributionTag);
2274 }
2275
lucaslin69e1aa92022-03-22 18:15:09 +08002276 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2277 if (nc.getUnderlyingNetworks() != null
2278 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2279 nc.setUnderlyingNetworks(null);
2280 }
2281 }
2282
Qingxi Libb8da982020-01-17 17:54:27 -08002283 @VisibleForTesting
2284 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002285 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002286 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2287 // this would be expensive (one more permission check every time any NC callback is
2288 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2289 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2290 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002291 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002292 if (!checkSettingsPermission(callerPid, callerUid)) {
2293 newNc.setUids(null);
2294 newNc.setSSID(null);
2295 }
Etan Cohen107ae952018-12-30 17:59:59 -08002296 if (newNc.getNetworkSpecifier() != null) {
2297 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2298 }
Benedict Wonga5604ea2021-07-09 00:13:45 -07002299 if (!checkAnyPermissionOf(callerPid, callerUid, android.Manifest.permission.NETWORK_STACK,
2300 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2301 newNc.setAdministratorUids(new int[0]);
2302 }
Benedict Wong53de25f2021-03-24 14:01:51 -07002303 if (!checkAnyPermissionOf(
2304 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002305 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002306 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002307 }
lucaslin69e1aa92022-03-22 18:15:09 +08002308 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002309
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002310 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002311 }
2312
Roshan Pius98f59ec2021-02-23 08:47:39 -08002313 /**
2314 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002315 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002316 * NetworkCapabilities.
2317 * Note: This wrapper does not support any sort of invalidation and thus must not be
2318 * persistent or long-lived. It may only be used for the time necessary to
2319 * compute the redactions required by one particular NetworkCallback or
2320 * synchronous call.
2321 */
2322 private class RedactionPermissionChecker {
2323 private final int mCallingPid;
2324 private final int mCallingUid;
2325 @NonNull private final String mCallingPackageName;
2326 @Nullable private final String mCallingAttributionTag;
2327
2328 private Boolean mHasLocationPermission = null;
2329 private Boolean mHasLocalMacAddressPermission = null;
2330 private Boolean mHasSettingsPermission = null;
2331
2332 RedactionPermissionChecker(int callingPid, int callingUid,
2333 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2334 mCallingPid = callingPid;
2335 mCallingUid = callingUid;
2336 mCallingPackageName = callingPackageName;
2337 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002338 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002339
2340 private boolean hasLocationPermissionInternal() {
2341 final long token = Binder.clearCallingIdentity();
2342 try {
2343 return mLocationPermissionChecker.checkLocationPermission(
2344 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2345 null /* message */);
2346 } finally {
2347 Binder.restoreCallingIdentity(token);
2348 }
2349 }
2350
2351 /**
2352 * Returns whether the app holds location permission or not (might return cached result
2353 * if the permission was already checked before).
2354 */
2355 public boolean hasLocationPermission() {
2356 if (mHasLocationPermission == null) {
2357 // If there is no cached result, perform the check now.
2358 mHasLocationPermission = hasLocationPermissionInternal();
2359 }
2360 return mHasLocationPermission;
2361 }
2362
2363 /**
2364 * Returns whether the app holds local mac address permission or not (might return cached
2365 * result if the permission was already checked before).
2366 */
2367 public boolean hasLocalMacAddressPermission() {
2368 if (mHasLocalMacAddressPermission == null) {
2369 // If there is no cached result, perform the check now.
2370 mHasLocalMacAddressPermission =
2371 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2372 }
2373 return mHasLocalMacAddressPermission;
2374 }
2375
2376 /**
2377 * Returns whether the app holds settings permission or not (might return cached
2378 * result if the permission was already checked before).
2379 */
2380 public boolean hasSettingsPermission() {
2381 if (mHasSettingsPermission == null) {
2382 // If there is no cached result, perform the check now.
2383 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2384 }
2385 return mHasSettingsPermission;
2386 }
2387 }
2388
2389 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2390 @NetworkCapabilities.NetCapability long redaction) {
2391 return (redactions & redaction) != 0;
2392 }
2393
2394 /**
2395 * Use the provided |applicableRedactions| to check the receiving app's
2396 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2397 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2398 * before being sent to the corresponding app.
2399 */
2400 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2401 @NetworkCapabilities.RedactionType long applicableRedactions,
2402 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2403 boolean includeLocationSensitiveInfo) {
2404 long redactions = applicableRedactions;
2405 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2406 if (includeLocationSensitiveInfo
2407 && redactionPermissionChecker.hasLocationPermission()) {
2408 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2409 }
2410 }
2411 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2412 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2413 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2414 }
2415 }
2416 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2417 if (redactionPermissionChecker.hasSettingsPermission()) {
2418 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2419 }
2420 }
2421 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002422 }
2423
Qingxi Lib2748102020-01-08 12:51:49 -08002424 @VisibleForTesting
2425 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002426 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002427 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002428 int callingPid, int callingUid, @NonNull String callingPkgName,
2429 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002430 if (nc == null) {
2431 return null;
2432 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002433 // Avoid doing location permission check if the transport info has no location sensitive
2434 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002435 final RedactionPermissionChecker redactionPermissionChecker =
2436 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2437 callingAttributionTag);
2438 final long redactions = retrieveRequiredRedactions(
2439 nc.getApplicableRedactions(), redactionPermissionChecker,
2440 includeLocationSensitiveInfo);
2441 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002442 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002443 // TODO : calling UID is redacted because apps should generally not know what UID is
2444 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002445 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002446 newNc.setOwnerUid(INVALID_UID);
2447 return newNc;
2448 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002449 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2450 if (nc.hasTransport(TRANSPORT_VPN)) {
2451 // Owner UIDs already checked above. No need to re-check.
2452 return newNc;
2453 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002454 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2455 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002456 // compatibility for older apps.
2457 if (!includeLocationSensitiveInfo
2458 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002459 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002460 newNc.setOwnerUid(INVALID_UID);
2461 return newNc;
2462 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002463 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002464 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002465 newNc.setOwnerUid(INVALID_UID);
2466 }
Qingxi Lib2748102020-01-08 12:51:49 -08002467 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002468 }
2469
lucaslinc582d502022-01-27 09:07:00 +08002470 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002471 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2472 LinkProperties lp, int callerPid, int callerUid) {
2473 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002474 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2475 // this would be expensive (one more permission check every time any LP callback is
2476 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2477 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2478 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002479
2480 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2481 final boolean needsSanitization =
2482 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2483 if (!needsSanitization) {
2484 return new LinkProperties(lp);
2485 }
2486
2487 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002488 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002489 }
2490
2491 final LinkProperties newLp = new LinkProperties(lp);
2492 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2493 // object gets parceled.
2494 newLp.setCaptivePortalApiUrl(null);
2495 newLp.setCaptivePortalData(null);
2496 return newLp;
2497 }
2498
Roshan Pius08c94fb2020-01-16 12:17:17 -08002499 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2500 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002501 // There is no need to track the effective UID of the request here. If the caller
2502 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002503 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002504 // Unprivileged apps can only pass in null or their own UID.
2505 if (nc.getUids() == null) {
2506 // If the caller passes in null, the callback will also match networks that do not
2507 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2508 // In this case, redact everything in the request immediately. This ensures that the
2509 // app is not able to get any redacted information by filing an unredacted request
2510 // and observing whether the request matches something.
2511 if (nc.getNetworkSpecifier() != null) {
2512 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2513 }
2514 } else {
2515 nc.setSingleUid(callerUid);
2516 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002517 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002518 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002519 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002520
2521 // Clear owner UID; this can never come from an app.
2522 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002523 }
2524
Chalard Jean38354d12018-03-20 19:13:57 +09002525 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002526 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002527 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2528 }
2529 }
2530
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002531 @Override
2532 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2533 enforceAccessPermission();
2534 final int callerUid = Binder.getCallingUid();
2535 final long token = Binder.clearCallingIdentity();
2536 try {
2537 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2538 } finally {
2539 Binder.restoreCallingIdentity(token);
2540 }
2541 }
2542
junyulaiebd15162021-03-03 12:09:05 +08002543 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002544 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002545 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002546 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002547 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002548
Serik Beketayev05130302021-01-15 16:47:25 -08002549 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002550 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002551 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2552 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002553 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002554 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002555 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002556 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2557 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002558 }
2559 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002560 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002561 }
2562
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002563 @Override
junyulaiebd15162021-03-03 12:09:05 +08002564 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002565 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002566 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002567 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002568
2569 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2570 for (Network network : getAllNetworks()) {
2571 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09002572 if (nai != null && nai.everConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002573 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2574 // NetworkCapabilities, which may contain UIDs of apps to which the
2575 // network applies. Should the UIDs be cleared so as not to leak or
2576 // interfere ?
2577 result.add(nai.getNetworkStateSnapshot());
2578 }
2579 }
2580 return result;
2581 }
2582
2583 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002584 public boolean isActiveNetworkMetered() {
2585 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002586
Qingxi Lib2748102020-01-08 12:51:49 -08002587 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002588 if (caps != null) {
2589 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2590 } else {
2591 // Always return the most conservative value
2592 return true;
2593 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002594 }
2595
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002596 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002597 * Ensures that the system cannot call a particular method.
2598 */
2599 private boolean disallowedBecauseSystemCaller() {
2600 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002601 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2602 // for devices launched with Q and above. However, existing devices upgrading to Q and
2603 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002604 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002605 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002606 log("This method exists only for app backwards compatibility"
2607 + " and must not be called by system services.");
2608 return true;
2609 }
2610 return false;
2611 }
2612
paulhub2c28682021-08-18 18:35:54 +08002613 private int getAppUid(final String app, final UserHandle user) {
2614 final PackageManager pm =
2615 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2616 final long token = Binder.clearCallingIdentity();
2617 try {
2618 return pm.getPackageUid(app, 0 /* flags */);
2619 } catch (PackageManager.NameNotFoundException e) {
2620 return -1;
2621 } finally {
2622 Binder.restoreCallingIdentity(token);
2623 }
2624 }
2625
2626 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2627 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2628 if (getAppUid(packageName, user) != callingUid) {
2629 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2630 }
2631 }
2632
Lorenzo Colitti23862912018-09-28 11:31:55 +09002633 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002634 * Ensure that a network route exists to deliver traffic to the specified
2635 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002636 * @param networkType the type of the network over which traffic to the
2637 * specified host is to be routed
2638 * @param hostAddress the IP address of the host to which the route is
2639 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002640 * @return {@code true} on success, {@code false} on failure
2641 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002642 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002643 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2644 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002645 if (disallowedBecauseSystemCaller()) {
2646 return false;
2647 }
paulhub2c28682021-08-18 18:35:54 +08002648 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002649 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002650 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08002651 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002652 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002653
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002654 InetAddress addr;
2655 try {
2656 addr = InetAddress.getByAddress(hostAddress);
2657 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002658 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002659 return false;
2660 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002661
The Android Open Source Project28527d22009-03-03 19:31:44 -08002662 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002663 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002664 return false;
2665 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002666
2667 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2668 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002669 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002670 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2671 } else {
2672 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2673 }
2674 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002675 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002676
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002677 DetailedState netState;
2678 synchronized (nai) {
2679 netState = nai.networkInfo.getDetailedState();
2680 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002681
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002682 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002683 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002684 log("requestRouteToHostAddress on down network "
2685 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002686 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002687 }
2688 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002689 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002690
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002691 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002692 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002693 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002694 LinkProperties lp;
2695 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002696 synchronized (nai) {
2697 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002698 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002699 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002700 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002701 if (DBG) {
2702 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2703 }
Wink Saville32506bc2013-06-29 21:10:57 -07002704 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002705 } finally {
2706 Binder.restoreCallingIdentity(token);
2707 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002708 }
2709
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002710 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002711 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002712 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002713 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002714 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002715 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002716 if (bestRoute.getGateway().equals(addr)) {
2717 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002718 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002719 } else {
2720 // if we will connect to this through another route, add a direct route
2721 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002722 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002723 }
2724 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002725 if (DBG) log("Adding legacy route " + bestRoute +
2726 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002727
2728 final String dst = bestRoute.getDestinationLinkAddress().toString();
2729 final String nextHop = bestRoute.hasGateway()
2730 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002731 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002732 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2733 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002734 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002735 return false;
2736 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002737 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002738 }
2739
paulhu7c0a2e62021-01-08 00:51:49 +08002740 class DnsResolverUnsolicitedEventCallback extends
2741 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002742 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002743 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002744 try {
2745 mHandler.sendMessage(mHandler.obtainMessage(
2746 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002747 new PrivateDnsValidationUpdate(event.netId,
2748 InetAddresses.parseNumericAddress(event.ipAddress),
2749 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002750 } catch (IllegalArgumentException e) {
2751 loge("Error parsing ip address in validation event");
2752 }
2753 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002754
2755 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002756 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2757 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002758 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2759 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2760 // event callback for certain nai. e.g. cellular. Register here to pass to
2761 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002762 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002763 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2764 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002765 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002766 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002767 }
2768 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002769
2770 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002771 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2772 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2773 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002774 }
dalyk1720e542018-03-05 12:42:22 -05002775
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002776 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002777 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002778 return this.VERSION;
2779 }
2780
2781 @Override
2782 public String getInterfaceHash() {
2783 return this.HASH;
2784 }
paulhu7c0a2e62021-01-08 00:51:49 +08002785 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002786
2787 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002788 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2789 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002790
paulhu7c0a2e62021-01-08 00:51:49 +08002791 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002792 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002793 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002794 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002795 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002796 }
2797 }
2798
Sudheer Shanka9967d462021-03-18 19:09:25 +00002799 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002800 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002801 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002802 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2803 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002804 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002805 };
2806
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002807 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002808 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002809 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002810 }
2811
paulhu1a407652019-03-22 16:35:06 +08002812 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2813 for (String permission : permissions) {
2814 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2815 return true;
2816 }
2817 }
2818 return false;
2819 }
2820
Paul Jensen83f5d572014-08-29 09:54:01 -04002821 private void enforceInternetPermission() {
2822 mContext.enforceCallingOrSelfPermission(
2823 android.Manifest.permission.INTERNET,
2824 "ConnectivityService");
2825 }
2826
The Android Open Source Project28527d22009-03-03 19:31:44 -08002827 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002828 mContext.enforceCallingOrSelfPermission(
2829 android.Manifest.permission.ACCESS_NETWORK_STATE,
2830 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002831 }
2832
lucaslinc582d502022-01-27 09:07:00 +08002833 private boolean checkAccessPermission(int pid, int uid) {
2834 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
2835 == PERMISSION_GRANTED;
2836 }
2837
paulhua6ee2122021-02-22 15:40:43 +08002838 /**
2839 * Performs a strict and comprehensive check of whether a calling package is allowed to
2840 * change the state of network, as the condition differs for pre-M, M+, and
2841 * privileged/preinstalled apps. The caller is expected to have either the
2842 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2843 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2844 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2845 * permission and cannot be revoked. See http://b/23597341
2846 *
2847 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2848 * of this app will be updated to the current time.
2849 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002850 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002851 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2852 == PackageManager.PERMISSION_GRANTED) {
2853 return;
2854 }
2855
2856 if (callingPkg == null) {
2857 throw new SecurityException("Calling package name is null.");
2858 }
2859
2860 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2861 final int uid = mDeps.getCallingUid();
2862 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2863 callingPkg, callingAttributionTag, null /* message */);
2864
2865 if (mode == AppOpsManager.MODE_ALLOWED) {
2866 return;
2867 }
2868
2869 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2870 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2871 return;
2872 }
2873
2874 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2875 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2876 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002877 }
2878
Charles He9369e612017-05-15 17:07:18 +01002879 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002880 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01002881 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002882 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002883 }
2884
Quang Luong98858d62023-02-11 00:25:24 +00002885 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08002886 enforceAnyPermissionOf(mContext,
2887 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00002888 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08002889 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2890 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
2891 }
2892
paulhu8e96a752019-08-12 16:25:11 +08002893 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002894 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002895 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002896 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08002897 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002898 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002899 }
2900
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002901 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002902 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002903 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002904 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002905 android.Manifest.permission.NETWORK_SETTINGS,
2906 android.Manifest.permission.NETWORK_FACTORY,
2907 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2908 }
2909
2910 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002911 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002912 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002913 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002914 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2915 android.Manifest.permission.NETWORK_FACTORY,
2916 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2917 }
2918
lucaslin69e1aa92022-03-22 18:15:09 +08002919 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
2920 return PERMISSION_GRANTED == mContext.checkPermission(
2921 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
2922 || PERMISSION_GRANTED == mContext.checkPermission(
2923 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2924 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002925 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002926 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08002927 }
2928
Chalard Jean9a396cc2018-02-21 18:43:54 +09002929 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002930 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002931 android.Manifest.permission.NETWORK_SETTINGS,
2932 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002933 }
2934
2935 private boolean checkSettingsPermission(int pid, int uid) {
2936 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002937 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2938 || PERMISSION_GRANTED == mContext.checkPermission(
2939 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002940 }
2941
paulhu8e96a752019-08-12 16:25:11 +08002942 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002943 enforceNetworkStackPermissionOr(mContext,
2944 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08002945 }
2946
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002947 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08002948 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002949 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002950 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002951 }
2952
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002953 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002954 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002955 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2956 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002957 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002958 }
2959
James Mattis8378aec2021-01-26 14:05:36 -08002960 private void enforceOemNetworkPreferencesPermission() {
2961 mContext.enforceCallingOrSelfPermission(
2962 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2963 "ConnectivityService");
2964 }
2965
James Mattisfa270db2021-05-31 17:11:10 -07002966 private void enforceManageTestNetworksPermission() {
2967 mContext.enforceCallingOrSelfPermission(
2968 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2969 "ConnectivityService");
2970 }
2971
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002972 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002973 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002974 android.Manifest.permission.NETWORK_STACK,
2975 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002976 }
2977
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002978 private boolean checkNetworkStackPermission(int pid, int uid) {
2979 return checkAnyPermissionOf(pid, uid,
2980 android.Manifest.permission.NETWORK_STACK,
2981 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2982 }
2983
paulhu1a407652019-03-22 16:35:06 +08002984 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2985 return checkAnyPermissionOf(pid, uid,
2986 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002987 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2988 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002989 }
2990
Paul Hu8fc2a552022-05-04 18:44:42 +08002991 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
2992 boolean checkUidsAllowedList) {
2993 if (PermissionUtils.checkAnyPermissionOf(mContext,
2994 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
2995 return true;
2996 }
2997
2998 // fallback to ConnectivityInternalPermission
2999 // TODO: Remove this fallback check after all apps have declared
3000 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3001 if (PermissionUtils.checkAnyPermissionOf(mContext,
3002 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3003 return true;
3004 }
3005
3006 // Check whether uid is in allowed on restricted networks list.
3007 if (checkUidsAllowedList
3008 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3009 return true;
3010 }
3011 return false;
3012 }
3013
3014 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3015 final int callingUid = mDeps.getCallingUid();
3016 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3017 throw new SecurityException("ConnectivityService: user " + callingUid
3018 + " has no permission to access restricted network.");
3019 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003020 }
3021
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003022 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003023 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003024 }
3025
Roshan Pius98f59ec2021-02-23 08:47:39 -08003026 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3027 return PERMISSION_GRANTED == mContext.checkPermission(
3028 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3029 }
3030
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003031 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003032 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003033 }
3034
3035 private void sendInetConditionBroadcast(NetworkInfo info) {
3036 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3037 }
3038
Wink Saville4f0de1e2011-08-04 15:01:58 -07003039 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003040 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003041 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003042 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003043 if (info.isFailover()) {
3044 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3045 info.setFailover(false);
3046 }
3047 if (info.getReason() != null) {
3048 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3049 }
3050 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003051 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3052 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003053 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003054 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003055 return intent;
3056 }
3057
3058 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3059 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3060 }
3061
Michael Groover73f69482023-01-27 11:01:25 -06003062 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3063 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003064 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3065 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003066 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003067 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003068 if (!mSystemReady
3069 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003070 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003071 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003072 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003073 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003074 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003075 }
3076
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003077 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003078 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003079 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003080 final NetworkInfo ni = intent.getParcelableExtra(
3081 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003082 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3083 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003084 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003085 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003086 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003087 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003088 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003089 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003090 } finally {
3091 Binder.restoreCallingIdentity(ident);
3092 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003093 }
3094 }
3095
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003096 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3097 NetworkInfo info) {
3098 // Delivery group policy APIs are only available on U+.
3099 if (!SdkLevel.isAtLeastU()) return;
3100
3101 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3102 try {
3103 // This allows us to discard older broadcasts still waiting to be delivered
3104 // which have the same namespace and key.
3105 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3106 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3107 createDeliveryGroupKeyForConnectivityAction(info));
Sudheer Shanka74fe7172023-01-24 19:33:06 +00003108 optsShim.setDeferUntilActive(true);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003109 } catch (UnsupportedApiLevelException e) {
3110 Log.wtf(TAG, "Using unsupported API" + e);
3111 }
3112 }
3113
3114 @VisibleForTesting
3115 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3116 final StringBuilder sb = new StringBuilder();
3117 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3118 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3119 sb.append(info.getExtraInfo());
3120 return sb.toString();
3121 }
3122
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003123 /**
Aaron Huang96011892020-06-27 07:18:23 +08003124 * Called by SystemServer through ConnectivityManager when the system is ready.
3125 */
3126 @Override
3127 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003128 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003129 throw new SecurityException("Calling Uid is not system uid.");
3130 }
3131 systemReadyInternal();
3132 }
3133
3134 /**
3135 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003136 */
3137 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003138 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003139 // Load flags after PackageManager is ready to query module version
3140 mFlags.loadFlags(mDeps, mContext);
3141
Aaron Huang9a57acf2020-12-08 10:03:29 +08003142 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3143 // listening network request which is sent by MultipathPolicyTracker won't be added
3144 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3145 // be called after PermissionMonitor#startMonitoring().
3146 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3147 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3148 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003149 final ConditionVariable startMonitoringDone = new ConditionVariable();
3150 mHandler.post(() -> {
3151 mPermissionMonitor.startMonitoring();
3152 startMonitoringDone.open();
3153 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003154 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003155 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003156
Hugo Benichie5220992017-04-26 14:53:28 +09003157 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003158 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003159 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003160 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003161 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003162 }
3163 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003164
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003165 // Create network requests for always-on networks.
3166 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003167
3168 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003169 // Note that updating can be skipped here if the list is empty only because no uid
3170 // rules are applied before system ready. Normally, the empty uid list means to clear
3171 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003172 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3173 updateMobileDataPreferredUids();
3174 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003175
3176 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
3177 if (SdkLevel.isAtLeastT()) {
3178 mBpfNetMaps.setPullAtomCallback(mContext);
3179 }
Paul Hu3c8c8102022-08-25 07:06:16 +00003180 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3181 // have permission problem. While CV#block() is unbounded in time and can in principle block
3182 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3183 // could have blocked forever too.
3184 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003185 }
3186
The Android Open Source Project28527d22009-03-03 19:31:44 -08003187 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003188 * Start listening for default data network activity state changes.
3189 */
3190 @Override
3191 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003192 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003193 }
3194
3195 /**
3196 * Stop listening for default data network activity state changes.
3197 */
3198 @Override
3199 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003200 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003201 }
3202
3203 /**
3204 * Check whether the default network radio is currently active.
3205 */
3206 @Override
3207 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003208 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003209 }
3210
3211 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003212 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003213 * and set it on it's iface.
3214 */
Junyu Lai970963e2022-10-25 15:46:47 +08003215 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003216 final String iface = newLp.getInterfaceName();
3217 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003218 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003219 // Silently ignore unset MTU value.
3220 return;
3221 }
Hansen Kurli04252032022-12-07 11:21:49 +00003222 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3223 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3224 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003225 return;
3226 }
Hansen Kurli04252032022-12-07 11:21:49 +00003227 // Cannot set MTU without interface name
3228 if (TextUtils.isEmpty(iface)) {
3229 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003230 return;
3231 }
sy.yun4aa73922013-09-02 05:24:09 +09003232
Hansen Kurli04252032022-12-07 11:21:49 +00003233 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3234 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003235 return;
3236 }
3237
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003238 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003239 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003240 mNetd.interfaceSetMtu(iface, mtu);
3241 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003242 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003243 }
3244 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003245
Chenbo Feng15416292018-11-08 17:36:21 -08003246 @VisibleForTesting
3247 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003248
Junyu Lai970963e2022-10-25 15:46:47 +08003249 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003250 String[] values = null;
3251 if (tcpBufferSizes != null) {
3252 values = tcpBufferSizes.split(",");
3253 }
3254
3255 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003256 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003257 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3258 values = tcpBufferSizes.split(",");
3259 }
3260
3261 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3262
3263 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003264 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003265
Chenbo Feng15416292018-11-08 17:36:21 -08003266 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3267 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3268 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003269 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003270 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003271 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003272 }
3273 }
3274
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003275 @Override
3276 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003277 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003278 NETWORK_RESTORE_DELAY_PROP_NAME);
3279 if(restoreDefaultNetworkDelayStr != null &&
3280 restoreDefaultNetworkDelayStr.length() != 0) {
3281 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003282 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003283 } catch (NumberFormatException e) {
3284 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003285 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003286 // if the system property isn't set, use the value for the apn type
3287 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3288
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003289 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3290 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003291 }
3292 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003293 }
3294
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003295 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003296 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003297 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003298 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003299 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003300 // Start gathering diagnostic information.
3301 netDiags.add(new NetworkDiagnostics(
3302 nai.network,
3303 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003304 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003305 DIAG_TIME_MS));
3306 }
3307
3308 for (NetworkDiagnostics netDiag : netDiags) {
3309 pw.println();
3310 netDiag.waitForMeasurements();
3311 netDiag.dump(pw);
3312 }
3313 }
3314
The Android Open Source Project28527d22009-03-03 19:31:44 -08003315 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003316 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3317 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003318 if (!checkDumpPermission(mContext, TAG, writer)) return;
3319
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003320 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003321 }
3322
lucaslin99473f62020-12-10 15:10:54 +08003323 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3324 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3325 != PackageManager.PERMISSION_GRANTED) {
3326 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003327 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003328 + " due to missing android.permission.DUMP permission");
3329 return false;
3330 } else {
3331 return true;
3332 }
3333 }
3334
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003335 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003336 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003337
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003338 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003339 dumpNetworkDiagnostics(pw);
3340 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003341 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003342 dumpNetworks(pw);
3343 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003344 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003345 dumpNetworkRequests(pw);
3346 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003347 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3348 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3349 dumpTrafficController(pw, fd, verbose);
3350 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003351 }
Erik Kline9647f382015-06-05 17:47:34 +09003352
Junyu Lai0da479b2022-04-20 15:06:29 +08003353 pw.println("NetworkProviders for:");
3354 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003355 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003356 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003357 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003358 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003359 pw.println();
3360
Chalard Jean5b409c72021-02-04 13:12:59 +09003361 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003362 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003363 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003364 pw.println("none");
3365 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003366 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003367 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003368 pw.println();
3369
James Mattis8b298a02021-06-01 22:34:04 -07003370 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003371 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003372 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003373 pw.decreaseIndent();
3374 pw.println();
3375
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003376 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003377 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003378 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003379 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003380 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003381
junyulaif2c67e42018-08-07 19:50:45 +08003382 pw.println("Status for known UIDs:");
3383 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003384 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003385 for (int i = 0; i < size; i++) {
3386 // Don't crash if the array is modified while dumping in bugreports.
3387 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003388 final int uid = mUidBlockedReasons.keyAt(i);
3389 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3390 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003391 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003392 } catch (ArrayIndexOutOfBoundsException e) {
3393 pw.println(" ArrayIndexOutOfBoundsException");
3394 } catch (ConcurrentModificationException e) {
3395 pw.println(" ConcurrentModificationException");
3396 }
3397 }
3398 pw.println();
3399 pw.decreaseIndent();
3400
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003401 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003402 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003403 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003404 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003405 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003406
Junyu Lai0da479b2022-04-20 15:06:29 +08003407 pw.println("Network Offers:");
3408 pw.increaseIndent();
3409 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3410 pw.println(offerInfo.offer);
3411 }
3412 pw.decreaseIndent();
3413 pw.println();
3414
Robert Greenwalt94e22142014-07-30 16:31:24 -07003415 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003416
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003417 pw.println();
markchien5e866652019-09-30 14:40:57 +08003418 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003419
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003420 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003421 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003422
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003423 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003424
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003425 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003426 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003427 pw.println("mNetworkRequestInfoLogs (most recent first):");
3428 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003429 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003430 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003431
3432 pw.println();
3433 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3434 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003435 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003436 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003437
3438 pw.println();
3439 pw.println("NetTransition WakeLock activity (most recent first):");
3440 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003441 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3442 pw.println("total releases: " + mTotalWakelockReleases);
3443 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3444 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3445 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3446 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3447 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3448 }
James Mattiscb1e0362021-04-06 17:07:42 -07003449 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003450
3451 pw.println();
3452 pw.println("bandwidth update requests (by uid):");
3453 pw.increaseIndent();
3454 synchronized (mBandwidthRequests) {
3455 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3456 pw.println("[" + mBandwidthRequests.keyAt(i)
3457 + "]: " + mBandwidthRequests.valueAt(i));
3458 }
3459 }
3460 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003461 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003462
James Mattiscb1e0362021-04-06 17:07:42 -07003463 pw.println();
3464 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3465 pw.increaseIndent();
3466 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003467 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003468 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003469
3470 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003471
3472 pw.println();
3473 pw.println("Permission Monitor:");
3474 pw.increaseIndent();
3475 mPermissionMonitor.dump(pw);
3476 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003477
3478 pw.println();
3479 pw.println("Legacy network activity:");
3480 pw.increaseIndent();
3481 mNetworkActivityTracker.dump(pw);
3482 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003483 }
3484
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003485 private void dumpNetworks(IndentingPrintWriter pw) {
3486 for (NetworkAgentInfo nai : networksSortedById()) {
3487 pw.println(nai.toString());
3488 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003489 pw.println("Nat464Xlat:");
3490 pw.increaseIndent();
3491 nai.dumpNat464Xlat(pw);
3492 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003493 pw.println(String.format(
3494 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3495 nai.numForegroundNetworkRequests(),
3496 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3497 nai.numBackgroundNetworkRequests(),
3498 nai.numNetworkRequests()));
3499 pw.increaseIndent();
3500 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3501 pw.println(nai.requestAt(i).toString());
3502 }
3503 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003504 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003505 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003506 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003507 pw.decreaseIndent();
3508 pw.decreaseIndent();
3509 }
3510 }
3511
James Mattis8b298a02021-06-01 22:34:04 -07003512 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3513 if (!mProfileNetworkPreferences.isEmpty()) {
3514 pw.println("Profile preferences:");
3515 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09003516 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07003517 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003518 }
James Mattis8b298a02021-06-01 22:34:04 -07003519 if (!mOemNetworkPreferences.isEmpty()) {
3520 pw.println("OEM preferences:");
3521 pw.increaseIndent();
3522 pw.println(mOemNetworkPreferences);
3523 pw.decreaseIndent();
3524 }
3525 if (!mMobileDataPreferredUids.isEmpty()) {
3526 pw.println("Mobile data preferred UIDs:");
3527 pw.increaseIndent();
3528 pw.println(mMobileDataPreferredUids);
3529 pw.decreaseIndent();
3530 }
James Mattis45d81842021-01-10 14:24:24 -08003531
James Mattis8b298a02021-06-01 22:34:04 -07003532 pw.println("Default requests:");
3533 pw.increaseIndent();
3534 dumpPerAppDefaultRequests(pw);
3535 pw.decreaseIndent();
3536 }
3537
3538 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003539 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3540 if (mDefaultRequest == defaultRequest) {
3541 continue;
3542 }
3543
James Mattis8b298a02021-06-01 22:34:04 -07003544 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3545 final String networkOutput;
3546 if (null == satisfier) {
3547 networkOutput = "null";
3548 } else if (mNoServiceNetwork.equals(satisfier)) {
3549 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003550 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003551 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003552 }
James Mattis8b298a02021-06-01 22:34:04 -07003553 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3554 ? "" : " asUid: " + defaultRequest.mAsUid;
3555 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3556 + defaultRequest.mPid + asUidString + "]";
3557 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3558 + " Preference order: " + defaultRequest.mPreferenceOrder
3559 + " Tracked UIDs: " + defaultRequest.getUids();
3560 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003561 }
3562 }
3563
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003564 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003565 NetworkRequestInfo[] infos = null;
3566 while (infos == null) {
3567 try {
3568 infos = requestsSortedById();
3569 } catch (ConcurrentModificationException e) {
3570 // mNetworkRequests should only be accessed from handler thread, except dump().
3571 // As dump() is never called in normal usage, it would be needlessly expensive
3572 // to lock the collection only for its benefit. Instead, retry getting the
3573 // requests if ConcurrentModificationException is thrown during dump().
3574 }
3575 }
3576 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003577 pw.println(nri.toString());
3578 }
3579 }
3580
Ken Chene6d511f2022-01-25 11:10:42 +08003581 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
3582 boolean verbose) {
3583 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09003584 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08003585 } catch (ServiceSpecificException e) {
3586 pw.println(e.getMessage());
3587 } catch (IOException e) {
3588 loge("Dump BPF maps failed, " + e);
3589 }
3590 }
3591
Chalard Jean524f0b12021-10-25 21:11:56 +09003592 private void dumpAllRequestInfoLogsToLogcat() {
3593 try (PrintWriter logPw = new PrintWriter(new Writer() {
3594 @Override
3595 public void write(final char[] cbuf, final int off, final int len) {
3596 // This method is called with 0-length and 1-length arrays for empty strings
3597 // or strings containing only the DEL character.
3598 if (len <= 1) return;
3599 Log.e(TAG, new String(cbuf, off, len));
3600 }
3601 @Override public void flush() {}
3602 @Override public void close() {}
3603 })) {
3604 mNetworkRequestInfoLogs.dump(logPw);
3605 }
3606 }
3607
Hugo Benichia480ba52018-09-03 08:19:02 +09003608 /**
3609 * Return an array of all current NetworkAgentInfos sorted by network id.
3610 */
3611 private NetworkAgentInfo[] networksSortedById() {
3612 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003613 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003614 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003615 return networks;
3616 }
3617
3618 /**
3619 * Return an array of all current NetworkRequest sorted by request id.
3620 */
James Mattis258ea3c2020-11-15 15:04:40 -08003621 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003622 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003623 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003624 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003625 // Sort the array based off the NRI containing the min requestId in its requests.
3626 Arrays.sort(requests,
3627 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3628 Comparator.comparingInt(req -> req.requestId)).requestId
3629 )
3630 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003631 return requests;
3632 }
3633
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003634 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003635 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003636 if (officialNai != null && officialNai.equals(nai)) return true;
3637 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003638 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003639 " - " + nai);
3640 }
3641 return false;
3642 }
3643
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003644 private boolean isDisconnectRequest(Message msg) {
3645 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
3646 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
3647 return info.getState() == NetworkInfo.State.DISCONNECTED;
3648 }
3649
Robert Greenwalt2034b912009-08-12 16:08:25 -07003650 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003651 private class NetworkStateTrackerHandler extends Handler {
3652 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003653 super(looper);
3654 }
3655
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003656 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003657 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3658 final NetworkAgentInfo nai = arg.first;
3659 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003660 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003661 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003662 }
3663 return;
3664 }
3665
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003666 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09003667 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003668 return;
3669 }
3670
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003671 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003672 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09003673 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
3674 final NetworkCapabilities sanitized =
3675 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09003676 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003677 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003678 break;
3679 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003680 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003681 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003682 processLinkPropertiesFromAgent(nai, newLp);
3683 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003684 break;
3685 }
3686 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003687 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003688 updateNetworkInfo(nai, info);
3689 break;
3690 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003691 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003692 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003693 break;
3694 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003695 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09003696 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003697 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003698 // Note that if the NAI had been connected, this would affect the
3699 // score, and therefore would require re-mixing the score and performing
3700 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003701 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003702 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3703 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003704 // Mark the network as temporarily accepting partial connectivity so that it
3705 // will be validated (and possibly become default) even if it only provides
3706 // partial internet access. Note that if user connects to partial connectivity
3707 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3708 // out of wifi coverage) and if the same wifi is available again, the device
3709 // will auto connect to this wifi even though the wifi has "no internet".
3710 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003711 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003712 break;
3713 }
junyulai011b1f12019-01-03 18:50:15 +08003714 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003715 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003716 break;
3717 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003718 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003719 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003720 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003721
3722 if (isLegacyLockdownNai(nai)
3723 && (underlying == null || underlying.size() != 1)) {
3724 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3725 + " must have exactly one underlying network: " + underlying);
3726 }
3727
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003728 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3729 nai.declaredUnderlyingNetworks = (underlying != null)
3730 ? underlying.toArray(new Network[0]) : null;
3731
3732 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3733 if (DBG) {
3734 log(nai.toShortString() + " changed underlying networks to "
3735 + Arrays.toString(nai.declaredUnderlyingNetworks));
3736 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003737 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003738 notifyIfacesChangedForNetworkStats();
3739 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003740 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003741 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003742 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3743 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3744 nai.teardownDelayMs = msg.arg1;
3745 } else {
3746 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3747 }
Chalard Jean550b5212021-03-05 23:07:53 +09003748 break;
3749 }
3750 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3751 nai.setLingerDuration((int) arg.second);
3752 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003753 }
Tyler Wear72388212021-09-09 14:49:02 -07003754 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3755 DscpPolicy policy = (DscpPolicy) arg.second;
3756 if (mDscpPolicyTracker != null) {
3757 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3758 }
3759 break;
3760 }
3761 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3762 if (mDscpPolicyTracker != null) {
3763 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3764 }
3765 break;
3766 }
3767 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3768 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08003769 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07003770 }
3771 break;
3772 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09003773 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09003774 if (!nai.isCreated()) {
3775 Log.d(TAG, "unregisterAfterReplacement on uncreated " + nai.toShortString()
3776 + ", tearing down instead");
3777 teardownUnneededNetwork(nai);
3778 break;
3779 }
3780
3781 if (nai.isDestroyed()) {
3782 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
3783 + ", ignoring");
3784 break;
3785 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003786
3787 final int timeoutMs = (int) arg.second;
3788 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3789 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
3790 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
3791 }
3792
3793 // Marking a network awaiting replacement is used to ensure that any requests
3794 // satisfied by the network do not switch to another network until a
3795 // replacement is available or the wait for a replacement times out.
3796 // If the network is inactive (i.e., nascent or lingering), then there are no
3797 // such requests, and there is no point keeping it. Just tear it down.
3798 // Note that setLingerDuration(0) cannot be used to do this because the network
3799 // could be nascent.
3800 nai.clearInactivityState();
3801 if (unneeded(nai, UnneededFor.TEARDOWN)) {
3802 Log.d(TAG, nai.toShortString()
3803 + " marked awaiting replacement is unneeded, tearing down instead");
3804 teardownUnneededNetwork(nai);
3805 break;
3806 }
3807
3808 Log.d(TAG, "Marking " + nai.toShortString()
3809 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
3810 destroyNativeNetwork(nai);
3811
3812 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
3813 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
3814 // consider the fact that the network could already have disconnected or been
3815 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
3816 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
3817 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
3818 mKeepaliveTracker.handleStopAllKeepalives(nai,
3819 SocketKeepalive.ERROR_INVALID_NETWORK);
3820
3821 nai.updateScoreForNetworkAgentUpdate();
3822 // This rematch is almost certainly not going to result in any changes, because
3823 // the destroyed flag is only just above the "current satisfier wins"
3824 // tie-breaker. But technically anything that affects scoring should rematch.
3825 rematchAllNetworksAndRequests();
3826 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
3827 break;
3828 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003829 }
3830 }
3831
3832 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003833 final int netId = msg.arg2;
3834 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003835 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09003836 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003837 switch (msg.what) {
3838 default:
3839 return false;
lucasline117e2e2019-10-22 18:27:33 +08003840 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08003841 if (nai == null) {
3842 break;
3843 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003844 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
3845 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08003846 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003847 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08003848 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003849 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08003850 if (probePrivateDnsCompleted) {
3851 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3852 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003853 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003854 }
3855 // Only show the notification when the private DNS is broken and the
3856 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003857 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003858 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3859 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003860 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003861 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3862 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3863 // private DNS is broken, it means this network is being reevaluated.
3864 // Either probing private DNS is not necessary any more or it hasn't been
3865 // done yet. In either case, the networkCapabilities should be updated to
3866 // reflect the new status.
3867 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003868 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003869 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003870 }
3871 break;
3872 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003873 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003874 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3875
Erik Kline31b4a9e2018-01-11 21:07:29 +09003876 if (nai == null) break;
3877
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003878 handleNetworkTested(nai, results.mTestResult,
3879 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003880 break;
3881 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003882 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09003883 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07003884 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04003885 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003886 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003887 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003888 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3889 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003890 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003891 if (nai == null) {
3892 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3893 break;
3894 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003895 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003896 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003897 (PendingIntent) msg.obj,
3898 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003899 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003900 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003901 break;
3902 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003903 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09003904 if (nai == null) break;
3905
Erik Kline9a62f012018-03-21 07:18:33 -07003906 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003907 break;
3908 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003909 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003910 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003911 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003912 break;
3913 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003914 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003915 return true;
3916 }
3917
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003918 private void handleNetworkTested(
3919 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09003920 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
3921 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09003922 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003923
3924 // If there is any kind of working networking, then the NAI has been evaluated
3925 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
3926 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09003927 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003928 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09003929 // Because of b/245893397, if the score is updated when updateCapabilities is called,
3930 // any callback that receives onAvailable for that rematch receives an extra caps
3931 // callback. To prevent that, update the score in the agent so the updates below won't
3932 // see an update to both caps and score at the same time.
3933 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09003934 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
3935
he_won.hwang881307a2022-03-15 21:23:52 +09003936 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
3937 // Assume the validation failure is due to a temporary failure after roaming
3938 // and ignore it. NetworkMonitor will continue to retry validation. If it
3939 // continues to fail after the block timeout expires, the network will be
3940 // marked unvalidated. If it succeeds, then validation state will not change.
3941 return;
3942 }
3943
Chalard Jean254bd162022-08-25 13:04:51 +09003944 final boolean wasValidated = nai.isValidated();
3945 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09003946 final boolean wasPortal = nai.captivePortalDetected();
3947 nai.setPartialConnectivity(partial);
3948 nai.setCaptivePortalDetected(portal);
3949 nai.updateScoreForNetworkAgentUpdate();
3950 final boolean partialConnectivityChanged = (wasPartial != partial);
3951 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003952
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003953 if (DBG) {
3954 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3955 ? " with redirect to " + redirectUrl
3956 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003957 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003958 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09003959 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003960 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09003961 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003962 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003963 if (valid) {
3964 handleFreshlyValidatedNetwork(nai);
3965 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3966 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003967 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003968 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003969 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003970 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003971 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003972 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003973 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003974 NotificationType.PRIVATE_DNS_BROKEN);
3975 // If network becomes valid, the hasShownBroken should be reset for
3976 // that network so that the notification will be fired when the private
3977 // DNS is broken again.
3978 nai.networkAgentConfig.hasShownBroken = false;
3979 }
3980 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003981 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09003982 } else if (portalChanged) {
3983 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3984 == getCaptivePortalMode()) {
3985 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
3986 nai.onPreventAutomaticReconnect();
3987 teardownUnneededNetwork(nai);
3988 return;
3989 } else {
3990 updateCapabilitiesForNetwork(nai);
3991 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09003992 } else if (becameEvaluated) {
3993 // If valid or partial connectivity changed, updateCapabilities* has
3994 // done the rematch.
3995 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003996 }
3997 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003998
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003999 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004000 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004001 nai.onValidationStatusChanged(
4002 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4003 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004004
4005 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004006 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004007 // immediately. Re-notify partial connectivity silently if no internet
4008 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004009 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004010 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004011 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4012 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004013 }
4014
Chalard Jean254bd162022-08-25 13:04:51 +09004015 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004016 handleNetworkUnvalidated(nai);
4017 }
4018 }
4019
Calvin Ondada1452016-10-11 15:10:46 -07004020 private int getCaptivePortalMode() {
4021 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004022 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4023 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004024 }
4025
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004026 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4027 switch (msg.what) {
4028 default:
4029 return false;
4030 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4031 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4032 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4033 handleLingerComplete(nai);
4034 }
4035 break;
4036 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004037 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4038 handleNetworkAgentRegistered(msg);
4039 break;
4040 }
4041 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4042 handleNetworkAgentDisconnected(msg);
4043 break;
4044 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004045 }
4046 return true;
4047 }
4048
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004049 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004050 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004051 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004052 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004053 maybeHandleNetworkAgentMessage(msg);
4054 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004055 }
4056 }
4057
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004058 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004059 private final int mNetId;
4060 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004061
4062 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004063 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004064 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004065 }
4066
4067 @Override
4068 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4069 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004070 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004071 }
4072
4073 @Override
4074 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004075 // Legacy version of notifyNetworkTestedWithExtras.
4076 // Would only be called if the system has a NetworkStack module older than the
4077 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004078 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004079 }
4080
4081 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004082 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004083 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4084 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004085 final Message msg = mTrackerHandler.obtainMessage(
4086 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004087 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004088 new NetworkTestedResults(
4089 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004090 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004091
4092 // Invoke ConnectivityReport generation for this Network test event.
4093 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4094 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004095
Cody Kestingf1120be2020-08-03 18:01:40 -07004096 // NetworkMonitor reports the network validation result as a bitmask while
4097 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4098 // logical value for ConnectivityDiagnostics.
4099 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4100 p.result);
4101
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004102 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004103 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004104 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4105 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4106
Aaron Huang959d3642021-01-21 15:47:41 +08004107 ConnectivityReportEvent reportEvent =
4108 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4109 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004110 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004111 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004112 }
4113
4114 @Override
4115 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4116 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4117 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004118 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004119 }
4120
4121 @Override
lucasline117e2e2019-10-22 18:27:33 +08004122 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4123 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4124 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004125 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004126 }
4127
4128 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004129 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4130 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4131 EVENT_CAPPORT_DATA_CHANGED,
4132 0, mNetId, data));
4133 }
4134
4135 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004136 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004137 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004138 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004139
4140 final PendingIntent pendingIntent;
4141 // Only the system server can register notifications with package "android"
4142 final long token = Binder.clearCallingIdentity();
4143 try {
paulhu7746e4e2020-06-09 19:07:03 +08004144 pendingIntent = PendingIntent.getBroadcast(
4145 mContext,
4146 0 /* requestCode */,
4147 intent,
4148 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004149 } finally {
4150 Binder.restoreCallingIdentity(token);
4151 }
4152 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4153 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004154 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004155 }
4156
4157 @Override
4158 public void hideProvisioningNotification() {
4159 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004160 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004161 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004162
4163 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004164 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004165 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004166 }
4167
4168 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004169 public int getInterfaceVersion() {
4170 return this.VERSION;
4171 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004172
4173 @Override
4174 public String getInterfaceHash() {
4175 return this.HASH;
4176 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004177 }
4178
Cody Kestingf1120be2020-08-03 18:01:40 -07004179 /**
4180 * Converts the given NetworkMonitor-specific validation result bitmask to a
4181 * ConnectivityDiagnostics-specific validation result int.
4182 */
4183 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4184 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4185 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4186 }
4187 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4188 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4189 }
4190 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4191 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4192 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4193 }
4194
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004195 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004196 log("Data stall detected with methods: " + p.detectionMethod);
4197
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004198 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004199 int detectionMethod = 0;
4200 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4201 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4202 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4203 }
4204 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4205 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4206 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4207 p.tcpMetricsCollectionPeriodMillis);
4208 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004209 }
4210
Cody Kestingf53a0752020-04-15 12:33:28 -07004211 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004212 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004213 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004214
4215 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4216 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4217 // the cost of going through two handlers.
4218 mConnectivityDiagnosticsHandler.sendMessage(msg);
4219 }
4220
Cody Kestingb37958e2020-05-15 10:36:01 -07004221 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4222 return (p.detectionMethod & detectionMethod) != 0;
4223 }
4224
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004225 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4226 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004227 }
4228
Erik Klinea73af002018-06-26 18:53:43 +09004229 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4230 if (nai == null) return;
4231 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4232 // in order to restart a validation pass from within netd.
4233 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4234 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004235 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004236 }
4237 }
4238
Erik Kline31b4a9e2018-01-11 21:07:29 +09004239 private void handlePrivateDnsSettingsChanged() {
4240 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4241
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004242 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004243 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004244 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004245 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4246 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004247 }
4248 }
4249
Erik Kline9a62f012018-03-21 07:18:33 -07004250 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4251 // Private DNS only ever applies to networks that might provide
4252 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004253 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004254
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004255 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004256 // schedule DNS resolutions. If a DNS resolution is required the
4257 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004258 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004259
4260 // With Private DNS bypass support, we can proceed to update the
4261 // Private DNS config immediately, even if we're in strict mode
4262 // and have not yet resolved the provider name into a set of IPs.
4263 updatePrivateDns(nai, cfg);
4264 }
4265
4266 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4267 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004268 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004269 }
4270
dalyk1720e542018-03-05 12:42:22 -05004271 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4272 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4273 if (nai == null) {
4274 return;
4275 }
4276 mDnsManager.updatePrivateDnsValidation(update);
4277 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4278 }
4279
paulhu7c0a2e62021-01-08 00:51:49 +08004280 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004281 int prefixLength) {
4282 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4283 if (nai == null) return;
4284
paulhu7c0a2e62021-01-08 00:51:49 +08004285 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4286 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004287
4288 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004289 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004290 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004291 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004292 prefixLength);
4293 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004294 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004295 return;
4296 }
4297 }
4298
Lorenzo Colittid523d142020-04-01 20:16:30 +09004299 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004300 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4301 }
4302
Hai Shalome58bdc62021-01-11 18:45:34 -08004303 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004304 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004305 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004306 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4307 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4308 }
4309
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004310 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004311 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004312 * @param nai the agent info to update
4313 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004314 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004315 */
junyulai2b6f0c22021-02-03 20:15:30 +08004316 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4317 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4318 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004319 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004320 // one lingered request, set inactive.
4321 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004322 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004323 if (DBG) log("Unsetting inactive " + nai.toShortString());
4324 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004325 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004326 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004327 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004328 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4329 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004330 }
junyulai2b6f0c22021-02-03 20:15:30 +08004331 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004332 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004333 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004334 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004335 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004336 }
4337
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004338 private void handleNetworkAgentRegistered(Message msg) {
4339 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4340 if (!mNetworkAgentInfos.contains(nai)) {
4341 return;
4342 }
4343
4344 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4345 if (VDBG) log("NetworkAgent registered");
4346 } else {
4347 loge("Error connecting NetworkAgent");
4348 mNetworkAgentInfos.remove(nai);
4349 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004350 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004351 synchronized (mNetworkForNetId) {
4352 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004353 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004354 mNetIdManager.releaseNetId(nai.network.getNetId());
4355 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004356 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004357 }
4358 }
4359 }
Paul Jensend5f53392014-11-25 15:26:53 -05004360
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004361 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004362 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004363 }
4364
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004365 @VisibleForTesting
4366 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004367 // T+ devices should use unregisterAfterReplacement.
he_won.hwang881307a2022-03-15 21:23:52 +09004368 if (SdkLevel.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004369
4370 // If the network never roamed, return false. The check below is not sufficient if time
4371 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4372 if (nai.lastRoamTime == 0) return false;
4373
he_won.hwang881307a2022-03-15 21:23:52 +09004374 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4375 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004376 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004377 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004378 final long currentTimeMs = SystemClock.elapsedRealtime();
4379 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004380 if (timeSinceLastRoam <= blockTimeOut) {
4381 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4382 return true;
4383 }
4384 }
4385 return false;
4386 }
4387
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004388 private void handleNetworkAgentDisconnected(Message msg) {
4389 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004390 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004391 }
4392
Chalard Jeand9fffc32018-05-11 20:19:20 +09004393 // Destroys a network, remove references to it from the internal state managed by
4394 // ConnectivityService, free its interfaces and clean up.
4395 // Must be called on the Handler thread.
4396 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004397 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004398
4399 if (!mNetworkAgentInfos.contains(nai)) return;
4400
Chalard Jeand9fffc32018-05-11 20:19:20 +09004401 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004402 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004403 }
lucaslinb25c9a62019-02-12 15:30:13 +08004404 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004405 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004406 // A network agent has disconnected.
4407 // TODO - if we move the logic to the network agent (have them disconnect
4408 // because they lost all their requests or because their score isn't good)
4409 // then they would disconnect organically, report their new state and then
4410 // disconnect the channel.
4411 if (nai.networkInfo.isConnected()) {
4412 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4413 null, null);
4414 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004415 final boolean wasDefault = isDefaultNetwork(nai);
4416 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004417 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004418 }
4419 notifyIfacesChangedForNetworkStats();
4420 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4421 // by other networks that are already connected. Perhaps that can be done by
4422 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4423 // of rematchAllNetworksAndRequests
4424 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004425 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004426
4427 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004428 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4429 // Disable wakeup packet monitoring for each interface.
4430 wakeupModifyInterface(iface, nai.networkCapabilities, false);
4431 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004432 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004433 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004434 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004435 synchronized (mNetworkForNetId) {
4436 // Remove the NetworkAgent, but don't mark the netId as
4437 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004438 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004439 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004440 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08004441 // Update allowed network lists in netd. This should be called after removing nai
4442 // from mNetworkAgentInfos.
4443 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004444 // Remove all previously satisfied requests.
4445 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004446 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004447 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004448 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004449 if (currentNetwork != null
4450 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004451 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004452 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4453 // rematch not to keep disconnected agents instead of setting it here ; this
4454 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004455 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004456 for (final NetworkOfferInfo noi : mNetworkOffers) {
4457 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004458 }
James Mattise3ef1912020-12-20 11:09:58 -08004459
Chalard Jean5b409c72021-02-04 13:12:59 +09004460 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004461 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004462 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004463 // network, because while incorrect this is the closest to the old (also
4464 // incorrect) behavior.
4465 mNetworkActivityTracker.updateDataActivityTracking(
4466 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004467 ensureNetworkTransitionWakelock(nai.toShortString());
4468 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004469 }
4470 }
junyulai2b6f0c22021-02-03 20:15:30 +08004471 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004472 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004473 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004474 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004475 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004476 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004477 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004478
4479 // Immediate teardown.
4480 if (nai.teardownDelayMs == 0) {
4481 destroyNetwork(nai);
4482 return;
4483 }
4484
4485 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09004486 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304487 try {
4488 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4489 } catch (RemoteException e) {
4490 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4491 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004492 }
4493 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4494 }
4495
4496 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004497 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004498 // Tell netd to clean up the configuration for this network
4499 // (routing rules, DNS, etc).
4500 // This may be slow as it requires a lot of netd shelling out to ip and
4501 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004502 // after we've rematched networks with requests (which might change the default
4503 // network or service a new request from an app), so network traffic isn't interrupted
4504 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004505 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004506 }
Chalard Jean254bd162022-08-25 13:04:51 +09004507 if (!nai.isCreated() && !SdkLevel.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004508 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
4509 // This can never run if the code above runs because shouldDestroyNativeNetwork is
4510 // false if the network was never created.
4511 // TODO: delete when S is no longer supported.
4512 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004513 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004514 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004515 }
4516
Ken Chen6df7a902021-04-09 15:08:42 +08004517 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004518 try {
4519 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004520 final NativeNetworkConfig config;
4521 if (nai.isVPN()) {
4522 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004523 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004524 return false;
4525 }
4526 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4527 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004528 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08004529 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004530 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004531 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004532 getNetworkPermission(nai.networkCapabilities),
4533 false /* secure */,
4534 VpnManager.TYPE_VPN_NONE,
4535 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08004536 }
Ken Chen6df7a902021-04-09 15:08:42 +08004537 mNetd.networkCreate(config);
4538 mDnsResolver.createNetworkCache(nai.network.getNetId());
4539 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4540 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004541 return true;
4542 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004543 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004544 return false;
4545 }
4546 }
4547
Ken Chen6df7a902021-04-09 15:08:42 +08004548 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004549 if (mDscpPolicyTracker != null) {
4550 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
4551 }
Luke Huangfdd11f82019-04-09 18:41:49 +08004552 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004553 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004554 } catch (RemoteException | ServiceSpecificException e) {
4555 loge("Exception destroying network(networkDestroy): " + e);
4556 }
4557 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004558 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004559 } catch (RemoteException | ServiceSpecificException e) {
4560 loge("Exception destroying network: " + e);
4561 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004562 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
4563 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
4564 // gets created, could add data to DnsManager data structures that will never get deleted.
4565 mDnsManager.removeNetwork(nai.network);
4566
4567 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09004568 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004569 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
4570 }
4571
Chalard Jean254bd162022-08-25 13:04:51 +09004572 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004573 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08004574 }
4575
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004576 // If this method proves to be too slow then we can maintain a separate
4577 // pendingIntent => NetworkRequestInfo map.
4578 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4579 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004580 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4581 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4582 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004583 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004584 return entry.getValue();
4585 }
4586 }
4587 return null;
4588 }
4589
Chalard Jean524f0b12021-10-25 21:11:56 +09004590 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4591 if (SdkLevel.isAtLeastT()) {
4592 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4593 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4594 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4595 // bug is fixed.
4596 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004597 throw new IllegalStateException("This NRI is already registered. New : " + nri
4598 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004599 }
4600 }
4601 }
4602 }
4603
Chalard Jeanac9ace02022-01-26 16:54:05 +09004604 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
4605 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08004606 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004607 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
4608 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004609 }
4610 return false;
4611 }
4612
James Mattisf7027322020-12-13 16:28:14 -08004613 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004614 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004615 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4616 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4617 final NetworkRequestInfo existingRequest =
4618 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004619 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004620 if (DBG) {
4621 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4622 + nri.mRequests.get(0) + " because their intents matched.");
4623 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004624 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004625 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004626 }
Erik Kline05f2b402015-04-30 12:58:40 +09004627 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004628 }
4629
James Mattisf7027322020-12-13 16:28:14 -08004630 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004631 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004632 }
4633
James Mattis3ce3d3c2021-02-09 18:18:28 -08004634 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004635 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004636 for (final NetworkRequestInfo nri : nris) {
4637 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004638 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004639 for (final NetworkRequest req : nri.mRequests) {
4640 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004641 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004642 if (req.isListen()) {
4643 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4644 if (req.networkCapabilities.hasSignalStrength()
4645 && network.satisfiesImmutableCapabilitiesOf(req)) {
4646 updateSignalStrengthThresholds(network, "REGISTER", req);
4647 }
James Mattisf7027322020-12-13 16:28:14 -08004648 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004649 }
4650 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004651
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004652 // If this NRI has a satisfier already, it is replacing an older request that
4653 // has been removed. Track it.
4654 final NetworkRequest activeRequest = nri.getActiveRequest();
4655 if (null != activeRequest) {
4656 // If there is an active request, then for sure there is a satisfier.
4657 nri.getSatisfier().addRequest(activeRequest);
4658 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004659 }
James Mattisf7027322020-12-13 16:28:14 -08004660
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004661 if (mFlags.noRematchAllRequestsOnRegister()) {
4662 rematchNetworksAndRequests(nris);
4663 } else {
4664 rematchAllNetworksAndRequests();
4665 }
James Mattis45d81842021-01-10 14:24:24 -08004666
Chalard Jean0354d8c2021-01-12 10:58:56 +09004667 // Requests that have not been matched to a network will not have been sent to the
4668 // providers, because the old satisfier and the new satisfier are the same (null in this
4669 // case). Send these requests to the providers.
4670 for (final NetworkRequestInfo nri : nris) {
4671 for (final NetworkOfferInfo noi : mNetworkOffers) {
4672 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004673 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004674 }
4675 }
4676
James Mattisf7027322020-12-13 16:28:14 -08004677 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4678 final int callingUid) {
4679 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004680 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004681 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4682 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4683 handleReleaseNetworkRequest(
4684 nri.mRequests.get(0),
4685 callingUid,
4686 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004687 }
4688 }
4689
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004690 // Determines whether the network is the best (or could become the best, if it validated), for
4691 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4692 // on the value of reason:
4693 //
4694 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4695 // then it should be torn down.
4696 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4697 // then it should be lingered.
4698 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004699 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004700
Chalard Jean254bd162022-08-25 13:04:51 +09004701 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09004702 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4703 return false;
4704 }
4705
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004706 final int numRequests;
4707 switch (reason) {
4708 case TEARDOWN:
4709 numRequests = nai.numRequestNetworkRequests();
4710 break;
4711 case LINGER:
4712 numRequests = nai.numForegroundNetworkRequests();
4713 break;
4714 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004715 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004716 return true;
4717 }
4718
Chalard Jean947acd42021-03-08 22:29:27 +09004719 if (numRequests > 0) return false;
4720
Paul Jensende49eb12015-06-25 15:30:08 -04004721 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004722 if (reason == UnneededFor.LINGER
4723 && !nri.isMultilayerRequest()
4724 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004725 // Background requests don't affect lingering.
4726 continue;
4727 }
4728
James Mattis3d229892020-11-16 16:46:28 -08004729 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004730 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004731 }
4732 }
Paul Jensende49eb12015-06-25 15:30:08 -04004733 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004734 }
4735
James Mattis3d229892020-11-16 16:46:28 -08004736 private boolean isNetworkPotentialSatisfier(
4737 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4738 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004739 // request, return immediately. For multilayer requests, check to see if any of the
4740 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004741 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4742 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004743 return false;
4744 }
4745 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004746 // This multilayer listen request is satisfied therefore no further requests need to be
4747 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004748 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004749 return false;
4750 }
James Mattis3d229892020-11-16 16:46:28 -08004751 // As non-multilayer listen requests have already returned, the below would only happen
4752 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004753 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004754 continue;
4755 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09004756 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08004757 // there is hope for it to become one if it validated, then it is needed.
4758 if (candidate.satisfies(req)) {
4759 // As soon as a network is found that satisfies a request, return. Specifically for
4760 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4761 // is important so as to not evaluate lower priority requests further in
4762 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004763 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4764 ? nri.getSatisfier() : null;
4765 // Note that this catches two important cases:
4766 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4767 // is currently satisfying the request. This is desirable when
4768 // cellular ends up validating but WiFi does not.
4769 // 2. Unvalidated WiFi will not be reaped when validated cellular
4770 // is currently satisfying the request. This is desirable when
4771 // WiFi ends up validating and out scoring cellular.
4772 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004773 }
4774 }
4775
4776 return false;
4777 }
4778
Erik Kline0c04b742016-07-07 16:50:58 +09004779 private NetworkRequestInfo getNriForAppRequest(
4780 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004781 // Looking up the app passed param request in mRequests isn't possible since it may return
4782 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4783 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004784 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4785 // to avoid potential race conditions when validating a package->uid mapping when sending
4786 // the callback on the very low-chance that an application shuts down prior to the callback
4787 // being sent.
4788 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4789 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004790
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004791 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004792 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004793 log(String.format("UID %d attempted to %s for unowned request %s",
4794 callingUid, requestedOperation, nri));
4795 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004796 }
Erik Kline0c04b742016-07-07 16:50:58 +09004797 }
4798
4799 return nri;
4800 }
4801
James Mattisf7027322020-12-13 16:28:14 -08004802 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4803 final String callingMethod) {
4804 if (nri.isMultilayerRequest()) {
4805 throw new IllegalStateException(
4806 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004807 }
4808 }
4809
James Mattisf7027322020-12-13 16:28:14 -08004810 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004811 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004812 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4813 // single NetworkRequest and thus does not apply to multilayer requests.
4814 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4815 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004816 return;
4817 }
James Mattis2516da32021-01-31 17:06:19 -08004818 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004819 return;
4820 }
James Mattisf7027322020-12-13 16:28:14 -08004821 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4822 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004823 }
4824 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004825 callCallbackForRequest(
4826 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004827 }
4828
James Mattisf7027322020-12-13 16:28:14 -08004829 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4830 final int callingUid,
4831 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004832 final NetworkRequestInfo nri =
4833 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4834 if (nri == null) {
4835 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004836 }
James Mattisf7027322020-12-13 16:28:14 -08004837 if (VDBG || (DBG && request.isRequest())) {
4838 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004839 }
4840 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004841 if (callOnUnavailable) {
4842 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4843 }
Erik Kline155a59a2015-11-25 12:49:38 +09004844 }
Erik Kline0c04b742016-07-07 16:50:58 +09004845
James Mattisa076c532020-12-02 14:12:41 -08004846 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004847 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004848 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004849 if (null == mNetworkRequests.remove(req)) {
4850 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4851 continue;
4852 }
James Mattisa076c532020-12-02 14:12:41 -08004853 if (req.isListen()) {
4854 removeListenRequestFromNetworks(req);
4855 }
4856 }
James Mattis8f036802021-06-20 16:26:01 -07004857 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004858 if (mDefaultNetworkRequests.remove(nri)) {
4859 // If this request was one of the defaults, then the UID rules need to be updated
4860 // WARNING : if the app(s) for which this network request is the default are doing
4861 // traffic, this will kill their connected sockets, even if an equivalent request
4862 // is going to be reinstated right away ; unconnected traffic will go on the default
4863 // until the new default is set, which will happen very soon.
4864 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4865 // remove ranges for those requests that won't have a replacement
4866 final NetworkAgentInfo satisfier = nri.getSatisfier();
4867 if (null != satisfier) {
4868 try {
paulhu0e79d952021-06-09 16:11:35 +08004869 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4870 satisfier.network.getNetId(),
4871 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004872 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004873 } catch (RemoteException e) {
4874 loge("Exception setting network preference default network", e);
4875 }
4876 }
4877 }
Junyu Lai35665cc2022-12-19 17:37:48 +08004878
Junyu Lai00d92df2022-07-05 11:01:52 +08004879 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09004880 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004881 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004882
4883 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004884 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004885 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004886 }
4887 }
4888
Chalard Jean0354d8c2021-01-12 10:58:56 +09004889 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4890 // needed for this offer.
4891 for (final NetworkOfferInfo noi : mNetworkOffers) {
4892 for (final NetworkRequest req : nri.mRequests) {
4893 if (req.isRequest() && noi.offer.neededFor(req)) {
4894 noi.offer.onNetworkUnneeded(req);
4895 }
4896 }
4897 }
James Mattisa076c532020-12-02 14:12:41 -08004898 }
4899
James Mattis3ce3d3c2021-02-09 18:18:28 -08004900 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4901 for (final NetworkRequestInfo nri : nris) {
4902 if (mDefaultRequest == nri) {
4903 // Make sure we never remove the default request.
4904 continue;
4905 }
4906 handleRemoveNetworkRequest(nri);
4907 }
4908 }
4909
James Mattisa076c532020-12-02 14:12:41 -08004910 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4911 // listens don't have a singular affected Network. Check all networks to see
4912 // if this listen request applies and remove it.
4913 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4914 nai.removeRequest(req.requestId);
4915 if (req.networkCapabilities.hasSignalStrength()
4916 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4917 updateSignalStrengthThresholds(nai, "RELEASE", req);
4918 }
4919 }
4920 }
4921
4922 /**
4923 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4924 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4925 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4926 */
4927 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4928 boolean wasKept = false;
4929 final NetworkAgentInfo nai = nri.getSatisfier();
4930 if (nai != null) {
4931 final int requestLegacyType = nri.getActiveRequest().legacyType;
4932 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4933 nai.removeRequest(nri.getActiveRequest().requestId);
4934 if (VDBG || DDBG) {
4935 log(" Removing from current network " + nai.toShortString()
4936 + ", leaving " + nai.numNetworkRequests() + " requests.");
4937 }
4938 // If there are still lingered requests on this network, don't tear it down,
4939 // but resume lingering instead.
4940 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004941 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004942 notifyNetworkLosing(nai, now);
4943 }
4944 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4945 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4946 teardownUnneededNetwork(nai);
4947 } else {
4948 wasKept = true;
4949 }
James Mattisa076c532020-12-02 14:12:41 -08004950 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4951 // Went from foreground to background.
4952 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004953 }
4954
Erik Kline0c04b742016-07-07 16:50:58 +09004955 // Maintain the illusion. When this request arrived, we might have pretended
4956 // that a network connected to serve it, even though the network was already
4957 // connected. Now that this request has gone away, we might have to pretend
4958 // that the network disconnected. LegacyTypeTracker will generate that
4959 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004960 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004961 boolean doRemove = true;
4962 if (wasKept) {
4963 // check if any of the remaining requests for this network are for the
4964 // same legacy type - if so, don't remove the nai
4965 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4966 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004967 if (otherRequest.legacyType == requestLegacyType
4968 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004969 if (DBG) log(" still have other legacy request - leaving");
4970 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004971 }
4972 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004973 }
4974
Erik Kline0c04b742016-07-07 16:50:58 +09004975 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004976 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004977 }
4978 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004979 }
4980 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004981
Junyu Lai00d92df2022-07-05 11:01:52 +08004982 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004983 return checkAnyPermissionOf(
4984 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4985 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4986 }
4987
Lorenzo Colittid6459092016-07-04 12:55:44 +09004988 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004989 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004990 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004991 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004992 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004993 }
4994
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004995 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004996 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4997 enforceNetworkStackSettingsOrSetup();
4998 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4999 encodeBool(accept), encodeBool(always), network));
5000 }
5001
5002 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005003 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005004 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005005 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5006 }
5007
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005008 @Override
5009 public void setTestAllowBadWifiUntil(long timeMs) {
5010 enforceSettingsPermission();
5011 if (!Build.isDebuggable()) {
5012 throw new IllegalStateException("Does not support in non-debuggable build");
5013 }
5014
5015 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5016 throw new IllegalArgumentException("It should not exceed "
5017 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5018 }
5019
5020 mHandler.sendMessage(
5021 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5022 }
5023
chiachangwange0192a72023-02-06 13:25:01 +00005024 @Override
5025 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5026 enforceSettingsPermission();
5027 if (!Build.isDebuggable()) {
5028 throw new IllegalStateException("Is not supported in non-debuggable build");
5029 }
5030
5031 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5032 throw new IllegalArgumentException("Argument should not exceed "
5033 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5034 }
5035
5036 mHandler.sendMessage(
5037 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5038 }
5039
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005040 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5041 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5042 " accept=" + accept + " always=" + always);
5043
5044 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5045 if (nai == null) {
5046 // Nothing to do.
5047 return;
5048 }
5049
Chalard Jean254bd162022-08-25 13:04:51 +09005050 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005051 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005052 return;
5053 }
5054
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005055 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005056 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005057 }
5058
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005059 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5060 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005061 // If network becomes partial connectivity and user already accepted to use this
5062 // network, we should respect the user's option and don't need to popup the
5063 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005064 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005065 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005066 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005067 }
5068
5069 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005070 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005071 }
5072
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005073 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005074 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005075 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005076 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005077 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005078 }
5079
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005080 }
5081
lucaslin2240ef62019-03-12 13:08:03 +08005082 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5083 boolean always) {
5084 if (DBG) {
5085 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5086 + " always=" + always);
5087 }
5088
5089 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5090 if (nai == null) {
5091 // Nothing to do.
5092 return;
5093 }
5094
Chalard Jean254bd162022-08-25 13:04:51 +09005095 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005096 // The network validated while the dialog box was up. Take no action.
5097 return;
5098 }
5099
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005100 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5101 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005102 }
5103
5104 // TODO: Use the current design or save the user choice into IpMemoryStore.
5105 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005106 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005107 }
5108
5109 if (!accept) {
5110 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005111 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005112 // Tear down the network.
5113 teardownUnneededNetwork(nai);
5114 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005115 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5116 // result in a partial connectivity result which will be processed by
5117 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005118 //
5119 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5120 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005121 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005122 }
5123 }
5124
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005125 private void handleSetAvoidUnvalidated(Network network) {
5126 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005127 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005128 // Nothing to do. The network either disconnected or revalidated.
5129 return;
5130 }
Chalard Jean254bd162022-08-25 13:04:51 +09005131 if (0L == nai.getAvoidUnvalidated()) {
5132 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005133 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005134 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005135 }
5136 }
5137
Chalard Jean5fb43c72022-09-08 19:03:14 +09005138 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005139 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005140 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005141 mHandler.sendMessageDelayed(
Chalard Jean5fb43c72022-09-08 19:03:14 +09005142 mHandler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005143 }
5144
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005145 @Override
5146 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005147 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005148 mHandler.post(() -> {
5149 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5150 if (nai == null) return;
5151 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005152 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005153 });
5154 }
5155
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005156 /**
5157 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5158 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005159 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005160 * @param appExtras Bundle to use as intent extras for the captive portal application.
5161 * Must be treated as opaque to avoid preventing the captive portal app to
5162 * update its arguments.
5163 */
5164 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005165 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005166 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5167 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005168
5169 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5170 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005171 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5172 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005173 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5174
lucaslin75ff7022020-12-17 04:14:35 +08005175 final long token = Binder.clearCallingIdentity();
5176 try {
5177 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5178 } finally {
5179 Binder.restoreCallingIdentity(token);
5180 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005181 }
5182
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005183 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5184 private final Network mNetwork;
5185
5186 private CaptivePortalImpl(Network network) {
5187 mNetwork = network;
5188 }
5189
5190 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005191 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005192 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5193 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005194 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5195 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5196 // Since the network will be disconnected, skip notifying NetworkMonitor
5197 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005198 }
5199
Chiachang Wang938bfba2020-01-09 13:50:55 +08005200 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005201 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005202 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005203 }
5204
5205 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005206 public void appRequest(final int request) {
5207 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5208 if (nm == null) return;
5209
5210 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005211 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005212 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005213 }
5214 }
5215
5216 @Nullable
5217 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5218 // getNetworkAgentInfoForNetwork is thread-safe
5219 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5220 if (nai == null) return null;
5221
5222 // nai.networkMonitor() is thread-safe
5223 return nai.networkMonitor();
5224 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005225 }
5226
Hugo Benichic9048bc2016-09-14 23:23:08 +00005227 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005228 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005229 }
5230
Chalard Jean020b93a2022-09-01 13:20:14 +09005231 private boolean activelyPreferBadWifi() {
5232 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5233 }
5234
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005235 /**
5236 * Return whether the device should maintain continuous, working connectivity by switching away
5237 * from WiFi networks having no connectivity.
5238 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5239 */
5240 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005241 if (!checkNetworkStackPermission()) {
5242 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5243 }
5244 return avoidBadWifi();
5245 }
5246
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005247 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005248 ensureRunningOnConnectivityServiceThread();
5249 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005250 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005251 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005252 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005253 if (avoidBadWifi) {
5254 // If the device is now avoiding bad wifi, remove notifications that might have
5255 // been put up when the device didn't.
5256 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5257 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005258 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005259 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5260 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5261 for (final NetworkOfferInfo noi : offersToUpdate) {
5262 updateOfferScore(noi.offer);
5263 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005264 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005265 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005266 }
5267
Erik Kline95ecfee2016-10-02 18:02:14 +09005268 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005269 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005270 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005271 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005272 if (!configRestrict) {
5273 pw.println("Bad Wi-Fi avoidance: unrestricted");
5274 return;
5275 }
5276
5277 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5278 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005279 pw.println("Config restrict: " + configRestrict);
5280 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005281
Chalard Jeane0fdea32022-09-14 21:44:22 +09005282 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005283 String description;
5284 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005285 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005286 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005287 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005288 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005289 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005290 description = "avoid";
5291 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005292 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005293 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005294 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005295
5296 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5297 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005298 if (null == configValue) {
5299 description = "unset";
5300 } else if (configValue) {
5301 description = "force true";
5302 } else {
5303 description = "force false";
5304 }
5305 pw.println("Actively prefer bad wifi conf: " + description);
5306 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005307 pw.println("Network overrides:");
5308 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005309 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005310 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005311 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005312 }
5313 }
5314 pw.decreaseIndent();
5315 pw.decreaseIndent();
5316 }
5317
paulhu7746e4e2020-06-09 19:07:03 +08005318 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5319 // unify the method.
5320 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5321 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5322 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5323 return settingsComponent != null
5324 ? settingsComponent.getPackageName() : "com.android.settings";
5325 }
5326
lucaslinb1e8e382019-01-24 15:55:30 +08005327 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005328 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005329 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005330 switch (type) {
5331 case NO_INTERNET:
5332 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005333 // High priority because it is only displayed for explicitly selected networks.
5334 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005335 break;
lucasline117e2e2019-10-22 18:27:33 +08005336 case PRIVATE_DNS_BROKEN:
5337 action = Settings.ACTION_WIRELESS_SETTINGS;
5338 // High priority because we should let user know why there is no internet.
5339 highPriority = true;
5340 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005341 case LOST_INTERNET:
5342 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005343 // High priority because it could help the user avoid unexpected data usage.
5344 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005345 break;
lucaslin2240ef62019-03-12 13:08:03 +08005346 case PARTIAL_CONNECTIVITY:
5347 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005348 // Don't bother the user with a high-priority notification if the network was not
5349 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005350 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005351 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005352 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005353 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005354 return;
5355 }
5356
5357 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005358 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005359 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005360 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005361 // Some OEMs have their own Settings package. Thus, need to get the current using
5362 // Settings package name instead of just use default name "com.android.settings".
5363 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5364 intent.setClassName(settingsPkgName,
5365 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005366 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005367
paulhu2af50222020-10-11 22:52:27 +08005368 PendingIntent pendingIntent = PendingIntent.getActivity(
5369 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005370 0 /* requestCode */,
5371 intent,
paulhu2af50222020-10-11 22:52:27 +08005372 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005373
Serik Beketayevec8ad212020-12-07 22:43:07 -08005374 mNotifier.showNotification(
5375 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005376 }
5377
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005378 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5379 // Don't prompt if the network is validated, and don't prompt on captive portals
5380 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005381 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005382 return false;
5383 }
5384
5385 // If a network has partial connectivity, always prompt unless the user has already accepted
5386 // partial connectivity and selected don't ask again. This ensures that if the device
5387 // automatically connects to a network that has partial Internet access, the user will
5388 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005389 // because we have prompted them.
5390 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005391 return true;
5392 }
5393
5394 // If a network has no Internet access, only prompt if the network was explicitly selected
5395 // and if the user has not already told us to use the network regardless of whether it
5396 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005397 if (nai.networkAgentConfig.explicitlySelected
5398 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005399 return true;
5400 }
5401
5402 return false;
5403 }
5404
Chalard Jean5fb43c72022-09-08 19:03:14 +09005405 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5406 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005407
Chalard Jean5fb43c72022-09-08 19:03:14 +09005408 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5409 if (null == nai) return;
5410
5411 if (nai.setEvaluated()) {
5412 // If setEvaluated() returned true, the network never had any form of connectivity.
5413 // This may have an impact on request matching if bad WiFi avoidance is off and the
5414 // network was found not to have Internet access.
5415 nai.updateScoreForNetworkAgentUpdate();
5416 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09005417
5418 // Also, if this is WiFi and it should be preferred actively, now is the time to
5419 // prompt the user that they walked past and connected to a bad WiFi.
5420 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
5421 && !avoidBadWifi()
5422 && activelyPreferBadWifi()) {
5423 // The notification will be removed if the network validates or disconnects.
5424 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
5425 return;
5426 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005427 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005428
Chalard Jean5fb43c72022-09-08 19:03:14 +09005429 if (!shouldPromptUnvalidated(nai)) return;
5430
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005431 // Stop automatically reconnecting to this network in the future. Automatically connecting
5432 // to a network that provides no or limited connectivity is not useful, because the user
5433 // cannot use that network except through the notification shown by this method, and the
5434 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005435 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005436
Chalard Jean254bd162022-08-25 13:04:51 +09005437 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005438 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005439 } else {
5440 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5441 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005442 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005443
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005444 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5445 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005446 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005447
lucaslin2240ef62019-03-12 13:08:03 +08005448 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5449 return;
5450 }
5451
5452 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005453 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005454 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005455 }
5456
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005457 @Override
5458 public int getMultipathPreference(Network network) {
5459 enforceAccessPermission();
5460
5461 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005462 if (nai != null && nai.networkCapabilities
5463 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005464 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5465 }
5466
Aaron Huang9a57acf2020-12-08 10:03:29 +08005467 final NetworkPolicyManager netPolicyManager =
5468 mContext.getSystemService(NetworkPolicyManager.class);
5469
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005470 final long token = Binder.clearCallingIdentity();
5471 final int networkPreference;
5472 try {
5473 networkPreference = netPolicyManager.getMultipathPreference(network);
5474 } finally {
5475 Binder.restoreCallingIdentity(token);
5476 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005477 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005478 return networkPreference;
5479 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005480 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5481 }
5482
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005483 @Override
5484 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005485 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005486 }
5487
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005488 private class InternalHandler extends Handler {
5489 public InternalHandler(Looper looper) {
5490 super(looper);
5491 }
5492
5493 @Override
5494 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005495 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005496 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005497 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005498 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005499 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005500 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005501 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005502 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005503 break;
5504 }
Jason Monka69f1b02013-10-10 14:02:51 -04005505 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005506 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5507 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005508 break;
5509 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005510 case EVENT_REGISTER_NETWORK_PROVIDER: {
5511 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005512 break;
5513 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005514 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5515 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005516 break;
5517 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005518 case EVENT_REGISTER_NETWORK_OFFER: {
5519 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5520 break;
5521 }
5522 case EVENT_UNREGISTER_NETWORK_OFFER: {
5523 final NetworkOfferInfo offer =
5524 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5525 if (null != offer) {
5526 handleUnregisterNetworkOffer(offer);
5527 }
5528 break;
5529 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005530 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005531 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5532 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5533 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005534 break;
5535 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005536 case EVENT_REGISTER_NETWORK_REQUEST:
5537 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005538 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005539 break;
5540 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005541 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5542 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005543 handleRegisterNetworkRequestWithIntent(msg);
5544 break;
5545 }
Erik Kline155a59a2015-11-25 12:49:38 +09005546 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5547 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5548 handleTimedOutNetworkRequest(nri);
5549 break;
5550 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005551 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5552 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5553 break;
5554 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005555 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005556 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5557 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005558 break;
5559 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005560 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005561 Network network = (Network) msg.obj;
5562 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005563 break;
5564 }
lucaslin2240ef62019-03-12 13:08:03 +08005565 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5566 Network network = (Network) msg.obj;
5567 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5568 toBool(msg.arg2));
5569 break;
5570 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005571 case EVENT_SET_AVOID_UNVALIDATED: {
5572 handleSetAvoidUnvalidated((Network) msg.obj);
5573 break;
5574 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09005575 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
5576 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005577 break;
5578 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005579 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5580 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005581 break;
5582 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005583 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005584 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005585 mKeepaliveTracker.handleStartKeepalive(msg);
5586 break;
5587 }
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005588 case NetworkAgent.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09005589 final AutomaticOnOffKeepalive ki =
5590 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
5591 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005592
chiachangwang676c84e2023-02-14 09:22:05 +00005593 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005594 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005595 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00005596 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005597 for (NetworkAgentInfo n : mNetworkAgentInfos) {
5598 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00005599 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
5600 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005601 }
5602 }
5603
5604 // If the network no longer exists, then the keepalive should have been
5605 // cleaned up already. There is no point trying to resume keepalives.
5606 if (!networkFound) return;
5607
chiachangwang676c84e2023-02-14 09:22:05 +00005608 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005609 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
chiachangwang676c84e2023-02-14 09:22:05 +00005610 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005611 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00005612 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005613 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005614 }
5615 break;
5616 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005617 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005618 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09005619 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
5620 (IBinder) msg.obj);
5621 if (ki == null) {
5622 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00005623 return;
5624 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09005625 final int reason = msg.arg2;
5626 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005627 break;
5628 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005629 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5630 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5631 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005632 break;
5633 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005634 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5635 handlePrivateDnsSettingsChanged();
5636 break;
dalyk1720e542018-03-05 12:42:22 -05005637 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5638 handlePrivateDnsValidationUpdate(
5639 (PrivateDnsValidationUpdate) msg.obj);
5640 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005641 case EVENT_UID_BLOCKED_REASON_CHANGED:
5642 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005643 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005644 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5645 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5646 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005647 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005648 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5649 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005650 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005651 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005652 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005653 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09005654 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
5655 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005656 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005657 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005658 }
lucaslin1193a5d2021-01-21 02:04:15 +08005659 case EVENT_REPORT_NETWORK_ACTIVITY:
5660 mNetworkActivityTracker.handleReportNetworkActivity();
5661 break;
paulhu51f77dc2021-06-07 02:34:20 +00005662 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5663 handleMobileDataPreferredUidsChanged();
5664 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005665 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5666 final long timeMs = ((Long) msg.obj).longValue();
5667 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5668 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01005669 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
5670 handleIngressRateLimitChanged();
5671 break;
Hansen Kurli55396972022-10-28 03:31:17 +00005672 case EVENT_USER_DOES_NOT_WANT:
5673 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5674 if (nai == null) break;
5675 nai.onPreventAutomaticReconnect();
5676 nai.disconnect();
5677 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00005678 case EVENT_SET_VPN_NETWORK_PREFERENCE:
5679 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
5680 break;
chiachangwange0192a72023-02-06 13:25:01 +00005681 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
5682 final long time = ((Long) msg.obj).longValue();
5683 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
5684 break;
5685 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005686 }
5687 }
5688 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005689
Lorenzo Colittid6459092016-07-04 12:55:44 +09005690 @Override
markchien5776f962019-12-16 20:15:20 +08005691 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005692 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08005693 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005694 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5695 Context.TETHERING_SERVICE);
5696 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005697 }
5698
Lorenzo Colittid6459092016-07-04 12:55:44 +09005699 @Override
markchien5776f962019-12-16 20:15:20 +08005700 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005701 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08005702 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005703 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5704 Context.TETHERING_SERVICE);
5705 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005706 }
5707
Lorenzo Colittid6459092016-07-04 12:55:44 +09005708 @Override
markchien5776f962019-12-16 20:15:20 +08005709 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005710 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005711 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005712 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5713 Context.TETHERING_SERVICE);
5714 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005715 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005716
markchien5776f962019-12-16 20:15:20 +08005717
Lorenzo Colittid6459092016-07-04 12:55:44 +09005718 @Override
markchien5776f962019-12-16 20:15:20 +08005719 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005720 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005721 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005722 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5723 Context.TETHERING_SERVICE);
5724
5725 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005726 }
5727
Lorenzo Colittid6459092016-07-04 12:55:44 +09005728 @Override
markchien5776f962019-12-16 20:15:20 +08005729 @Deprecated
5730 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08005731 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005732 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5733 Context.TETHERING_SERVICE);
5734
5735 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005736 }
5737
Udam Saini8f7d6a72017-06-07 12:06:28 -07005738 @Override
markchien5776f962019-12-16 20:15:20 +08005739 @Deprecated
5740 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08005741 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005742 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5743 Context.TETHERING_SERVICE);
5744 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005745 }
5746
Robert Greenwalte0b00512014-07-02 09:59:16 -07005747 // Called when we lose the default network and have no replacement yet.
5748 // This will automatically be cleared after X seconds or a new default network
5749 // becomes CONNECTED, whichever happens first. The timer is started by the
5750 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005751 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005752 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005753 if (mNetTransitionWakeLock.isHeld()) {
5754 return;
5755 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005756 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005757 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5758 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005759 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005760 mWakelockLogs.log("ACQUIRE for " + forWhom);
5761 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005762 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005763 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005764 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005765 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005766
Hugo Benichi471b62a2017-03-30 23:18:10 +09005767 // Called when we gain a new default network to release the network transition wakelock in a
5768 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5769 // message is cancelled.
5770 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005771 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005772 if (!mNetTransitionWakeLock.isHeld()) {
5773 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005774 }
5775 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005776 // Cancel self timeout on wakelock hold.
5777 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5778 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5779 mHandler.sendMessageDelayed(msg, 1000);
5780 }
5781
5782 // Called when either message of ensureNetworkTransitionWakelock or
5783 // scheduleReleaseNetworkTransitionWakelock is processed.
5784 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5785 String event = eventName(eventId);
5786 synchronized (this) {
5787 if (!mNetTransitionWakeLock.isHeld()) {
5788 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005789 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005790 return;
5791 }
5792 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005793 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5794 mTotalWakelockDurationMs += lockDuration;
5795 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5796 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005797 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005798 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005799 }
5800
Robert Greenwalt986c7412010-09-08 15:24:47 -07005801 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005802 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005803 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005804 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005805 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005806 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005807 }
5808
Lorenzo Colittid6459092016-07-04 12:55:44 +09005809 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005810 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005811 enforceAccessPermission();
5812 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005813 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005814 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005815
5816 final NetworkAgentInfo nai;
5817 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005818 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005819 } else {
5820 nai = getNetworkAgentInfoForNetwork(network);
5821 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005822
5823 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005824 mHandler.obtainMessage(
5825 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005826 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005827
Hugo Benichid6b510a2017-04-06 17:22:18 +09005828 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005829 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005830 if (nai == null
5831 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005832 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005833 return;
5834 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005835 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09005836 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005837 mConnectivityDiagnosticsHandler.sendMessage(
5838 mConnectivityDiagnosticsHandler.obtainMessage(
5839 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5840 new ReportedNetworkConnectivityInfo(
5841 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005842 return;
5843 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005844 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005845 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005846 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005847 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005848 // Validating a network that has not yet connected could result in a call to
5849 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09005850 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005851 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005852 }
paulhu7aeba372020-12-30 00:42:19 +08005853 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5854 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005855 return;
5856 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005857
5858 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5859 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5860 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5861 // completed.
5862 mConnectivityDiagnosticsHandler.sendMessage(
5863 mConnectivityDiagnosticsHandler.obtainMessage(
5864 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5865 new ReportedNetworkConnectivityInfo(
5866 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005867 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005868 }
5869
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005870 // TODO: call into netd.
5871 private boolean queryUserAccess(int uid, Network network) {
5872 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5873 if (nai == null) return false;
5874
5875 // Any UID can use its default network.
5876 if (nai == getDefaultNetworkForUid(uid)) return true;
5877
5878 // Privileged apps can use any network.
5879 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5880 return true;
5881 }
5882
5883 // An unprivileged UID can use a VPN iff the VPN applies to it.
5884 if (nai.isVPN()) {
5885 return nai.networkCapabilities.appliesToUid(uid);
5886 }
5887
5888 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5889 // sockets, i.e., if it is the owner.
5890 final NetworkAgentInfo vpn = getVpnForUid(uid);
5891 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5892 && uid != vpn.networkCapabilities.getOwnerUid()) {
5893 return false;
5894 }
5895
5896 // The UID's permission must be at least sufficient for the network. Since the restricted
5897 // permission was already checked above, that just leaves background networks.
5898 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5899 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5900 }
5901
5902 // Unrestricted network. Anyone gets to use it.
5903 return true;
5904 }
5905
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005906 /**
5907 * Returns information about the proxy a certain network is using. If given a null network, it
5908 * it will return the proxy for the bound network for the caller app or the default proxy if
5909 * none.
5910 *
5911 * @param network the network we want to get the proxy information for.
5912 * @return Proxy information if a network has a proxy configured, or otherwise null.
5913 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005914 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005915 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005916 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005917 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005918 if (network == null) {
5919 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005920 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005921 true);
5922 if (activeNetwork == null) {
5923 return null;
5924 }
5925 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005926 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005927 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5928 // caller may not have.
5929 return getLinkPropertiesProxyInfo(network);
5930 }
5931 // No proxy info available if the calling UID does not have network access.
5932 return null;
5933 }
5934
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005935
5936 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005937 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5938 if (nai == null) return null;
5939 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005940 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5941 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005942 }
5943 }
5944
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005945 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005946 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08005947 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005948 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005949 }
5950
Chalard Jean777e2e52018-06-07 18:02:37 +09005951 @Override
5952 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005953 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005954 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005955 }
5956
Junyu Lai970963e2022-10-25 15:46:47 +08005957 private void handleApplyDefaultProxy(@Nullable ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005958 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005959 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005960 proxy = null;
5961 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005962 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005963 }
5964
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005965 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5966 // when any network changes proxy.
5967 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5968 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08005969 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
5970 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05005971 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5972
Chalard Jean7d97afc2018-06-07 17:41:29 +09005973 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005974 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005975 }
5976 }
5977
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005978 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005979 final private HashMap<Uri, Integer> mUriEventMap;
5980 final private Context mContext;
5981 final private Handler mHandler;
5982
5983 SettingsObserver(Context context, Handler handler) {
5984 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005985 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005986 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005987 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005988 }
5989
Erik Kline05f2b402015-04-30 12:58:40 +09005990 void observe(Uri uri, int what) {
5991 mUriEventMap.put(uri, what);
5992 final ContentResolver resolver = mContext.getContentResolver();
5993 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005994 }
5995
5996 @Override
5997 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005998 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005999 }
6000
6001 @Override
6002 public void onChange(boolean selfChange, Uri uri) {
6003 final Integer what = mUriEventMap.get(uri);
6004 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006005 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006006 } else {
6007 loge("No matching event to send for URI=" + uri);
6008 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006009 }
6010 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006011
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006012 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006013 Log.d(TAG, s);
6014 }
6015
6016 private static void logw(String s) {
6017 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006018 }
6019
Daniel Brightf9e945b2020-06-15 16:10:01 -07006020 private static void logwtf(String s) {
6021 Log.wtf(TAG, s);
6022 }
6023
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006024 private static void logwtf(String s, Throwable t) {
6025 Log.wtf(TAG, s, t);
6026 }
6027
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006028 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006029 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006030 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006031
Hugo Benichi39621362017-02-11 17:04:43 +09006032 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006033 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006034 }
6035
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006036 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006037 * Return the information of all ongoing VPNs.
6038 *
6039 * <p>This method is used to update NetworkStatsService.
6040 *
6041 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006042 */
junyulai2050bed2021-01-23 09:46:34 +08006043 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006044 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006045 if (mLockdownEnabled) {
6046 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006047 }
junyulai2050bed2021-01-23 09:46:34 +08006048 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006049 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006050 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006051 if (info != null) {
6052 infoList.add(info);
6053 }
6054 }
junyulai2050bed2021-01-23 09:46:34 +08006055 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006056 }
6057
6058 /**
6059 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006060 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006061 */
junyulai2050bed2021-01-23 09:46:34 +08006062 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006063 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006064 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6065 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006066 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6067 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6068 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006069 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6070 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006071 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006072 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006073 }
6074 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006075
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006076 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006077
6078 List<String> interfaces = new ArrayList<>();
6079 for (Network network : underlyingNetworks) {
6080 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6081 if (underlyingNai == null) continue;
6082 LinkProperties lp = underlyingNai.linkProperties;
6083 for (String iface : lp.getAllInterfaceNames()) {
6084 if (!TextUtils.isEmpty(iface)) {
6085 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006086 }
6087 }
Benedict Wong34857f82019-06-12 17:46:15 +00006088 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006089
6090 if (interfaces.isEmpty()) return null;
6091
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006092 // Must be non-null or NetworkStatsService will crash.
6093 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6094 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006095 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006096 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006097
junyulai2050bed2021-01-23 09:46:34 +08006098 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6099 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006100 }
6101
James Mattisd31bdfa2020-12-23 16:37:26 -08006102 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006103 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6104 Network[] underlyingNetworks) {
6105 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006106 if (underlyingNetworks == null && defaultNetwork != null) {
6107 // null underlying networks means to track the default.
6108 underlyingNetworks = new Network[] { defaultNetwork };
6109 }
6110 return underlyingNetworks;
6111 }
6112
6113 // Returns true iff |network| is an underlying network of |nai|.
6114 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6115 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6116 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006117 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006118 final Network[] underlying = underlyingNetworksOrDefault(
6119 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006120 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006121 }
6122
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006123 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006124 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006125 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006126 * When underlying networks change, such networks may have to update capabilities to reflect
6127 * things like the metered bit, their transports, and so on. The capabilities are calculated
6128 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006129 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006130 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006131 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006132 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006133 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006134 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006135 }
6136 }
6137 }
6138
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006139 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6140 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6141 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6142 // a VPN is not up.
6143 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6144 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6145 for (UidRange range : blockedUidRanges) {
6146 if (range.contains(uid)) return true;
6147 }
6148 return false;
6149 }
6150
6151 @Override
6152 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006153 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006154 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6155 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6156 }
6157
6158 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6159 if (DBG) {
6160 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6161 + Arrays.toString(ranges));
6162 }
6163 // Cannot use a Set since the list of UID ranges might contain duplicates.
6164 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6165 for (int i = 0; i < ranges.length; i++) {
6166 if (requireVpn) {
6167 newVpnBlockedUidRanges.add(ranges[i]);
6168 } else {
6169 newVpnBlockedUidRanges.remove(ranges[i]);
6170 }
6171 }
6172
6173 try {
6174 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6175 } catch (RemoteException | ServiceSpecificException e) {
6176 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6177 + Arrays.toString(ranges) + "): netd command failed: " + e);
6178 }
6179
Motomu Utsumib08654c2022-05-11 05:56:26 +00006180 if (SdkLevel.isAtLeastT()) {
6181 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6182 }
6183
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006184 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6185 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006186 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6187 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006188 }
6189
6190 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6191 }
6192
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006193 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006194 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006195 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006196 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006197 }
6198
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006199 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6200 return mLockdownEnabled
6201 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6202 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006203 }
6204
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006205 private NetworkAgentInfo getLegacyLockdownNai() {
6206 if (!mLockdownEnabled) {
6207 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006208 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006209 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006210 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6211 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006212
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006213 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006214 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6215 // a local variable. There is no need to make a copy because its contents cannot change.
6216 final Network[] underlying = nai.declaredUnderlyingNetworks;
6217 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006218 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006219 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006220
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006221 // The legacy lockdown VPN always uses the default network.
6222 // If the VPN's underlying network is no longer the current default network, it means that
6223 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006224 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6225 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006226 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006227 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006228 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006229 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006230
6231 return nai;
6232 };
6233
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006234 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6235 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6236 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006237 private DetailedState getLegacyLockdownState(DetailedState origState) {
6238 if (origState != DetailedState.CONNECTED) {
6239 return origState;
6240 }
6241 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6242 ? DetailedState.CONNECTING
6243 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006244 }
6245
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006246 private void filterForLegacyLockdown(NetworkInfo ni) {
6247 if (!mLockdownEnabled || !ni.isConnected()) return;
6248 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6249 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6250 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6251 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6252 // network, this time with a state of CONNECTED.
6253 //
6254 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6255 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6256 // is not too far off the truth, since an always-on VPN, when not connected, is always
6257 // trying to reconnect.
6258 if (getLegacyLockdownNai() == null) {
6259 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6260 }
6261 }
6262
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006263 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006264 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006265 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006266 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006267 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6268 return;
6269 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006270 final long ident = Binder.clearCallingIdentity();
6271 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006272 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006273 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006274 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006275 } finally {
6276 Binder.restoreCallingIdentity(ident);
6277 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006278 }
Wink Savillecb117d32013-08-29 14:57:08 -07006279
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006280 @Override
6281 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006282 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006283 final long ident = Binder.clearCallingIdentity();
6284 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006285 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006286 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006287 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6288 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006289 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006290 } finally {
6291 Binder.restoreCallingIdentity(ident);
6292 }
6293 }
6294
James Mattis02220e22021-03-13 19:27:21 -08006295 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006296 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6297 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6298 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006299 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006300 }
6301
James Mattis02220e22021-03-13 19:27:21 -08006302 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006303 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006304 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006305 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6306 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006307 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006308 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6309 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6310 }
junyulaid91e7052020-08-28 13:44:33 +08006311 }
6312
James Mattis02220e22021-03-13 19:27:21 -08006313 private void onPackageChanged(@NonNull final String packageName) {
6314 // This is necessary in case a package is added or removed, but also when it's replaced to
6315 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6316 // as one in the preferences, then it should follow the same routing as that other package,
6317 // which means updating the rules is never to be needed in this case (whether it joins or
6318 // leaves a UID with a preference).
6319 if (isMappedInOemNetworkPreference(packageName)) {
6320 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6321 }
6322 }
6323
6324 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006325 @Override
6326 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006327 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006328 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006329 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006330
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006331 // User should be filled for below intents, check the existence.
6332 if (user == null) {
6333 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6334 return;
6335 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006336
Lorenzo Colitticd675292021-02-04 17:32:07 +09006337 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006338 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006339 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006340 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006341 } else {
junyulaid91e7052020-08-28 13:44:33 +08006342 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006343 }
6344 }
6345 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006346
James Mattis02220e22021-03-13 19:27:21 -08006347 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6348 @Override
6349 public void onReceive(Context context, Intent intent) {
6350 ensureRunningOnConnectivityServiceThread();
6351 switch (intent.getAction()) {
6352 case Intent.ACTION_PACKAGE_ADDED:
6353 case Intent.ACTION_PACKAGE_REMOVED:
6354 case Intent.ACTION_PACKAGE_REPLACED:
6355 onPackageChanged(intent.getData().getSchemeSpecificPart());
6356 break;
6357 default:
6358 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6359 }
6360 }
6361 };
6362
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006363 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006364 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006365
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006366 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006367 public final String name;
6368 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006369 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006370 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006371
lifraf3a3492021-03-10 13:58:14 +08006372 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6373 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006374 this.name = name;
6375 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006376 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006377 mDeathRecipient = deathRecipient;
6378
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006379 if (mDeathRecipient == null) {
6380 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006381 }
6382 }
6383
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006384 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006385 try {
6386 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6387 } catch (RemoteException e) {
6388 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006389 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006390 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006391 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006392
James Mattis4fce5d12020-11-12 15:53:42 -08006393 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6394 for (int i = 0; i < requests.size(); i++) {
6395 ensureNetworkRequestHasType(requests.get(i));
6396 }
6397 }
6398
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006399 private void ensureNetworkRequestHasType(NetworkRequest request) {
6400 if (request.type == NetworkRequest.Type.NONE) {
6401 throw new IllegalArgumentException(
6402 "All NetworkRequests in ConnectivityService must have a type");
6403 }
6404 }
6405
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006406 /**
6407 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006408 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006409 */
James Mattis258ea3c2020-11-15 15:04:40 -08006410 @VisibleForTesting
6411 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006412 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6413 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006414 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006415
James Mattisa076c532020-12-02 14:12:41 -08006416 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6417 void setSatisfier(
6418 @Nullable final NetworkAgentInfo satisfier,
6419 @Nullable final NetworkRequest activeRequest) {
6420 mSatisfier = satisfier;
6421 mActiveRequest = activeRequest;
6422 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006423
James Mattisd31bdfa2020-12-23 16:37:26 -08006424 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006425 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006426 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006427 private NetworkAgentInfo mSatisfier;
6428 NetworkAgentInfo getSatisfier() {
6429 return mSatisfier;
6430 }
6431
6432 // The request in mRequests assigned to a network agent. This is null if none of the
6433 // requests in mRequests can be satisfied. This member has the constraint of only being
6434 // accessible on the handler thread.
6435 @Nullable
6436 private NetworkRequest mActiveRequest;
6437 NetworkRequest getActiveRequest() {
6438 return mActiveRequest;
6439 }
6440
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006441 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006442 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006443 @Nullable
6444 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006445
6446 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006447 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006448 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006449 final int mPid;
6450 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006451 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006452 @Nullable
6453 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006454
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006455 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006456 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006457
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006458 // Effective UID of this request. This is different from mUid when a privileged process
6459 // files a request on behalf of another UID. This UID is used to determine blocked status,
6460 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6461 // maximum limit of registered callbacks per UID.
6462 final int mAsUid;
6463
paulhu48291862021-07-14 14:53:57 +08006464 // Preference order of this request.
6465 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006466
James Mattis3ce3d3c2021-02-09 18:18:28 -08006467 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6468 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6469 // maintained for keying off of. This is only a concern when the original nri
6470 // mNetworkRequests changes which happens currently for apps that register callbacks to
6471 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6472 // that match the per-app default nri that currently tracks the calling app's uid so that
6473 // callbacks are fired at the appropriate time. When the callbacks fire,
6474 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6475 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6476 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6477 @NonNull
6478 private final NetworkRequest mNetworkRequestForCallback;
6479 NetworkRequest getNetworkRequestForCallback() {
6480 return mNetworkRequestForCallback;
6481 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006482
James Mattisd31bdfa2020-12-23 16:37:26 -08006483 /**
6484 * Get the list of UIDs this nri applies to.
6485 */
6486 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006487 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006488 // networkCapabilities.getUids() returns a defensive copy.
6489 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006490 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6491 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006492 }
6493
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006494 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6495 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006496 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006497 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006498 }
6499
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006500 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006501 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006502 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006503 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006504 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006505 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006506 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006507 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006508 mBinder = null;
6509 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006510 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006511 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006512 mPerUidCounter = getRequestCounter(this);
6513 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006514 /**
6515 * Location sensitive data not included in pending intent. Only included in
6516 * {@link NetworkCallback}.
6517 */
6518 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006519 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006520 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006521 }
6522
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006523 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006524 @Nullable final IBinder binder,
6525 @NetworkCallback.Flag int callbackFlags,
6526 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006527 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
6528 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08006529 }
6530
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006531 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006532 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006533 @Nullable final IBinder binder,
6534 @NetworkCallback.Flag int callbackFlags,
6535 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006536 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006537 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006538 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006539 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006540 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006541 mBinder = binder;
6542 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006543 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006544 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006545 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006546 mPerUidCounter = getRequestCounter(this);
6547 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006548 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006549 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006550 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006551 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006552 }
6553
James Mattis3ce3d3c2021-02-09 18:18:28 -08006554 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6555 @NonNull final List<NetworkRequest> r) {
6556 super();
6557 ensureAllNetworkRequestsHaveType(r);
6558 mRequests = initializeRequests(r);
6559 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006560 final NetworkAgentInfo satisfier = nri.getSatisfier();
6561 if (null != satisfier) {
6562 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6563 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09006564 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006565 // As this code creates a new NRI with a new set of requests, figure out which of
6566 // the list of requests should be the active request. It is always the first
6567 // request of the list that can be satisfied by the satisfier since the order of
6568 // requests is a priority order.
6569 // Note even in the presence of a satisfier there may not be an active request,
6570 // when the satisfier is the no-service network.
6571 NetworkRequest activeRequest = null;
6572 for (final NetworkRequest candidate : r) {
6573 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6574 activeRequest = candidate;
6575 break;
6576 }
6577 }
6578 setSatisfier(satisfier, activeRequest);
6579 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006580 mMessenger = nri.mMessenger;
6581 mBinder = nri.mBinder;
6582 mPid = nri.mPid;
6583 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006584 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006585 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006586 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006587 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006588 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006589 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006590 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006591 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006592 }
6593
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006594 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006595 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006596 }
6597
paulhue9913722021-05-26 15:19:20 +08006598 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006599 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006600 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006601 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006602 }
6603
James Mattis2516da32021-01-31 17:06:19 -08006604 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6605 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6606 // false.
6607 boolean isBeingSatisfied() {
6608 return (null != mSatisfier && null != mActiveRequest);
6609 }
6610
James Mattis3d229892020-11-16 16:46:28 -08006611 boolean isMultilayerRequest() {
6612 return mRequests.size() > 1;
6613 }
6614
James Mattis45d81842021-01-10 14:24:24 -08006615 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6616 // Creating a defensive copy to prevent the sender from modifying the list being
6617 // reflected in the return value of this method.
6618 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006619 return Collections.unmodifiableList(tempRequests);
6620 }
6621
James Mattisb1392002021-03-31 13:57:52 -07006622 void linkDeathRecipient() {
6623 if (null != mBinder) {
6624 try {
6625 mBinder.linkToDeath(this, 0);
6626 } catch (RemoteException e) {
6627 binderDied();
6628 }
6629 }
6630 }
6631
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006632 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006633 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006634 try {
6635 mBinder.unlinkToDeath(this, 0);
6636 } catch (NoSuchElementException e) {
6637 // Temporary workaround for b/194394697 pending analysis of additional logs
6638 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6639 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006640 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006641 }
6642
paulhu48291862021-07-14 14:53:57 +08006643 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6644 // Compare two preference orders.
6645 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006646 }
6647
paulhu48291862021-07-14 14:53:57 +08006648 int getPreferenceOrderForNetd() {
6649 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6650 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6651 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006652 }
paulhu48291862021-07-14 14:53:57 +08006653 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006654 }
6655
James Mattis4fce5d12020-11-12 15:53:42 -08006656 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006657 public void binderDied() {
6658 log("ConnectivityService NetworkRequestInfo binderDied(" +
Chalard Jean524f0b12021-10-25 21:11:56 +09006659 "uid/pid:" + mUid + "/" + mPid + ", " + mRequests + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09006660 // As an immutable collection, mRequests cannot change by the time the
6661 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6662 // is acceptable. Use handleReleaseNetworkRequest and not directly
6663 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6664 // the app already unregistered the request.
6665 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6666 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006667 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006668
James Mattis4fce5d12020-11-12 15:53:42 -08006669 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006670 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006671 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6672 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006673 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006674 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006675 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006676 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006677 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006678 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006679 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006680 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006681 }
6682
Junyu Lai00d92df2022-07-05 11:01:52 +08006683 // Keep backward compatibility since the ServiceSpecificException is used by
6684 // the API surface, see {@link ConnectivityManager#convertServiceException}.
6685 public static class RequestInfoPerUidCounter extends PerUidCounter {
6686 RequestInfoPerUidCounter(int maxCountPerUid) {
6687 super(maxCountPerUid);
6688 }
6689
6690 @Override
6691 public synchronized void incrementCountOrThrow(int uid) {
6692 try {
6693 super.incrementCountOrThrow(uid);
6694 } catch (IllegalStateException e) {
6695 throw new ServiceSpecificException(
6696 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
6697 "Uid " + uid + " exceeded its allotted requests limit");
6698 }
6699 }
6700
6701 @Override
6702 public synchronized void decrementCountOrThrow(int uid) {
6703 throw new UnsupportedOperationException("Use decrementCount instead.");
6704 }
6705
6706 public synchronized void decrementCount(int uid) {
6707 try {
6708 super.decrementCountOrThrow(uid);
6709 } catch (IllegalStateException e) {
6710 logwtf("Exception when decrement per uid request count: ", e);
6711 }
6712 }
6713 }
6714
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006715 // This checks that the passed capabilities either do not request a
6716 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006717 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006718 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006719 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006720 throw new SecurityException("Insufficient permissions to request a specific SSID");
6721 }
paulhu1a407652019-03-22 16:35:06 +08006722
6723 if (nc.hasSignalStrength()
6724 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6725 throw new SecurityException(
6726 "Insufficient permissions to request a specific signal strength");
6727 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006728 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006729
junyulai2217bec2021-04-14 23:33:31 +08006730 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006731 enforceNetworkFactoryPermission();
6732 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006733 }
6734
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006735 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006736 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006737 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006738 // mNetworkRequests may contain the same value multiple times in case of
6739 // multilayer requests. It won't matter in this case because the thresholds
6740 // will then be the same and be deduplicated as they enter the `thresholds` set.
6741 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006742 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6743 for (final NetworkRequest req : nri.mRequests) {
6744 if (req.networkCapabilities.hasSignalStrength()
6745 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6746 thresholds.add(req.networkCapabilities.getSignalStrength());
6747 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006748 }
6749 }
6750 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006751 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006752 }
6753
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006754 private void updateSignalStrengthThresholds(
6755 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006756 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006757
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006758 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006759 String detail;
6760 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6761 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6762 } else {
6763 detail = reason;
6764 }
6765 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006766 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006767 }
6768
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006769 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006770 }
6771
Chalard Jeandd421992021-12-16 23:16:02 +09006772 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07006773 if (nc == null) {
6774 return;
6775 }
6776 NetworkSpecifier ns = nc.getNetworkSpecifier();
6777 if (ns == null) {
6778 return;
6779 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006780 if (ns instanceof MatchAllNetworkSpecifier) {
6781 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6782 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006783 }
6784
Chalard Jeandd421992021-12-16 23:16:02 +09006785 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08006786 ensureValidNetworkSpecifier(nc);
6787 if (nc.isPrivateDnsBroken()) {
6788 throw new IllegalArgumentException("Can't request broken private DNS");
6789 }
Chalard Jeande665262022-02-25 16:12:12 +09006790 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09006791 throw new IllegalArgumentException("Can't request access UIDs");
6792 }
lucasline117e2e2019-10-22 18:27:33 +08006793 }
6794
Chalard Jeandd421992021-12-16 23:16:02 +09006795 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
6796 ensureListenableCapabilities(nc);
6797 final String badCapability = nc.describeFirstNonRequestableCapability();
6798 if (badCapability != null) {
6799 throw new IllegalArgumentException("Cannot request network with " + badCapability);
6800 }
6801 }
6802
Chiachang Wang3bc52762021-11-25 14:17:57 +08006803 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6804 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006805 private boolean isTargetSdkAtleast(int version, int callingUid,
6806 @NonNull String callingPackageName) {
6807 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006808 final PackageManager pm =
6809 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006810 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006811 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006812 if (callingVersion < version) return false;
6813 } catch (PackageManager.NameNotFoundException e) { }
6814 return true;
6815 }
6816
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006817 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006818 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006819 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006820 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006821 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006822 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006823 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6824 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006825 throw new SecurityException("Insufficient permissions to specify legacy type");
6826 }
markchienfac84a22020-03-18 21:16:15 +08006827 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006828 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006829 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006830 // Privileged callers can track the default network of another UID by passing in a UID.
6831 if (asUid != Process.INVALID_UID) {
6832 enforceSettingsPermission();
6833 } else {
6834 asUid = callingUid;
6835 }
junyulaiad010792021-01-11 16:53:38 +08006836 final NetworkRequest.Type reqType;
6837 try {
6838 reqType = NetworkRequest.Type.values()[reqTypeInt];
6839 } catch (ArrayIndexOutOfBoundsException e) {
6840 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6841 }
6842 switch (reqType) {
6843 case TRACK_DEFAULT:
6844 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006845 // is unused and will be replaced by ones appropriate for the UID (usually, the
6846 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006847 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006848 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006849 enforceAccessPermission();
6850 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006851 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00006852 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006853 networkCapabilities = new NetworkCapabilities(defaultNc);
6854 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006855 case BACKGROUND_REQUEST:
6856 enforceNetworkStackOrSettingsPermission();
6857 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006858 case REQUEST:
6859 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6860 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006861 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08006862 // TODO: this is incorrect. We mark the request as metered or not depending on
6863 // the state of the app when the request is filed, but we never change the
6864 // request if the app changes network state. http://b/29964605
6865 enforceMeteredApnPolicy(networkCapabilities);
6866 break;
junyulai1b1c8742021-03-12 20:05:08 +08006867 case LISTEN_FOR_BEST:
6868 enforceAccessPermission();
6869 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6870 break;
junyulaiad010792021-01-11 16:53:38 +08006871 default:
6872 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006873 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006874 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006875 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006876 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006877
junyulai1b1c8742021-03-12 20:05:08 +08006878 // Enforce FOREGROUND if the caller does not have permission to use background network.
6879 if (reqType == LISTEN_FOR_BEST) {
6880 restrictBackgroundRequestForCaller(networkCapabilities);
6881 }
6882
6883 // Set the UID range for this request to the single UID of the requester, unless the
6884 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006885 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6886 // are no visible methods to set the UIDs, an app could use reflection to try and get
6887 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006888 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006889 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6890 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006891
Etan Cohen85000162017-02-05 10:42:27 -08006892 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006893 throw new IllegalArgumentException("Bad timeout specified");
6894 }
Etan Cohen9786d922015-11-18 10:56:15 -08006895
James Mattis3ce3d3c2021-02-09 18:18:28 -08006896 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006897 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006898 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006899 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006900 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006901 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006902
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006903 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6904 // copied from the default request above. (This is necessary to ensure, for example, that
6905 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6906 // changes don't alter request matching.
6907 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6908 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006909 throw new IllegalStateException(
6910 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006911 + networkCapabilities + " vs. " + defaultNc);
6912 }
6913
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006914 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006915 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006916 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006917 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006918 }
6919 return networkRequest;
6920 }
6921
James Mattis3ce3d3c2021-02-09 18:18:28 -08006922 /**
6923 * Return the nri to be used when registering a network request. Specifically, this is used with
6924 * requests registered to track the default request. If there is currently a per-app default
6925 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6926 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006927 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6928 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006929 * @param nr the network request for the nri.
6930 * @param msgr the messenger for the nri.
6931 * @param binder the binder for the nri.
6932 * @param callingAttributionTag the calling attribution tag for the nri.
6933 * @return the nri to register.
6934 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006935 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006936 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006937 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006938 @Nullable String callingAttributionTag) {
6939 final List<NetworkRequest> requests;
6940 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6941 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006942 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006943 } else {
6944 requests = Collections.singletonList(nr);
6945 }
Roshan Pius951c0032020-12-22 15:10:42 -08006946 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006947 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006948 }
6949
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006950 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08006951 String callingPackageName, String callingAttributionTag, final int callingUid) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006952 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08006953 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
6954 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
6955 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
6956 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006957 }
junyulai96bd9fe2022-03-08 17:36:42 +08006958 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006959 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006960 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006961 }
6962 }
6963
fenglu3f357402015-03-20 11:29:56 -07006964 @Override
fenglub00f4882015-04-21 17:12:05 -07006965 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006966 enforceAccessPermission();
6967 NetworkAgentInfo nai = null;
6968 if (network == null) {
6969 return false;
6970 }
6971 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006972 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006973 }
6974 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006975 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006976 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006977 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006978 Integer uidReqs = mBandwidthRequests.get(uid);
6979 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006980 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006981 }
6982 mBandwidthRequests.put(uid, ++uidReqs);
6983 }
fenglu3f357402015-03-20 11:29:56 -07006984 return true;
6985 }
6986 return false;
6987 }
6988
Felipe Leme0a5ae422016-06-20 16:36:29 -07006989 private boolean isSystem(int uid) {
6990 return uid < Process.FIRST_APPLICATION_UID;
6991 }
fenglu3f357402015-03-20 11:29:56 -07006992
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006993 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006994 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006995 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006996 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006997 return;
6998 }
Hugo Benichi39621362017-02-11 17:04:43 +09006999 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7000 // Policy already enforced.
7001 return;
7002 }
paulhuaf50d7d2020-12-24 19:47:34 +08007003 final long ident = Binder.clearCallingIdentity();
7004 try {
7005 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7006 // If UID is restricted, don't allow them to bring up metered APNs.
7007 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7008 }
7009 } finally {
7010 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007011 }
7012 }
7013
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007014 @Override
7015 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007016 PendingIntent operation, @NonNull String callingPackageName,
7017 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007018 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007019 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007020 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007021 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007022 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007023 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007024 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007025 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007026 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007027 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7028 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007029
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007030 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007031 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007032 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7033 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007034 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007035 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7036 nri));
7037 return networkRequest;
7038 }
7039
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007040 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7041 mHandler.sendMessageDelayed(
7042 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007043 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007044 }
7045
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007046 @Override
7047 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007048 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007049 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007050 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007051 }
7052
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007053 // In order to implement the compatibility measure for pre-M apps that call
7054 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7055 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7056 // This ensures it has permission to do so.
7057 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7058 if (nc == null) {
7059 return false;
7060 }
7061 int[] transportTypes = nc.getTransportTypes();
7062 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7063 return false;
7064 }
7065 try {
7066 mContext.enforceCallingOrSelfPermission(
7067 android.Manifest.permission.ACCESS_WIFI_STATE,
7068 "ConnectivityService");
7069 } catch (SecurityException e) {
7070 return false;
7071 }
7072 return true;
7073 }
7074
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007075 @Override
7076 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007077 Messenger messenger, IBinder binder,
7078 @NetworkCallback.Flag int callbackFlags,
7079 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007080 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007081 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7082 enforceAccessPermission();
7083 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007084
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007085 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007086 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007087 Binder.getCallingPid(), callingUid, callingPackageName);
7088 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007089 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7090 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7091 // onLost and onAvailable callbacks when networks move in and out of the background.
7092 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7093 // can't request networks.
7094 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007095 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007096
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007097 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007098 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007099 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007100 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007101 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007102 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007103
7104 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7105 return networkRequest;
7106 }
7107
7108 @Override
7109 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007110 PendingIntent operation, @NonNull String callingPackageName,
7111 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007112 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007113 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007114 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7115 enforceAccessPermission();
7116 }
Chalard Jeandd421992021-12-16 23:16:02 +09007117 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007118 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007119 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007120 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007121 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007122
7123 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007124 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007125 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7126 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007127 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007128
WeiZhang1cc3f172021-06-03 19:02:04 -05007129 mHandler.sendMessage(mHandler.obtainMessage(
7130 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007131 }
7132
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007133 /** Returns the next Network provider ID. */
7134 public final int nextNetworkProviderId() {
7135 return mNextNetworkProviderId.getAndIncrement();
7136 }
7137
Erik Kline0c04b742016-07-07 16:50:58 +09007138 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007139 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007140 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007141 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007142 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007143 }
7144
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007145 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7146 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007147 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7148 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7149 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007150 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007151 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007152 return;
7153 }
7154
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007155 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7156 mNetworkProviderInfos.put(npi.messenger, npi);
7157 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007158 }
7159
7160 @Override
7161 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007162 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007163 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007164 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007165 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007166 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7167 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007168 }
7169
7170 @Override
7171 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007172 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007173 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007174 }
7175
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007176 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007177 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007178 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7179 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007180 Objects.requireNonNull(score);
7181 Objects.requireNonNull(caps);
7182 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007183 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007184 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007185 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7186 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007187 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7188 }
7189
Chalard Jeanbb902a52021-08-18 01:35:19 +09007190 private void updateOfferScore(final NetworkOffer offer) {
7191 final boolean yieldToBadWiFi =
7192 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7193 final NetworkOffer newOffer = new NetworkOffer(
7194 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7195 offer.caps, offer.callback, offer.providerId);
7196 if (offer.equals(newOffer)) return;
7197 handleRegisterNetworkOffer(newOffer);
7198 }
7199
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007200 @Override
7201 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007202 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007203 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7204 }
7205
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007206 private void handleUnregisterNetworkProvider(Messenger messenger) {
7207 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7208 if (npi == null) {
7209 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007210 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007211 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007212 // Unregister all the offers from this provider
7213 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7214 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007215 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007216 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7217 toRemove.add(noi);
7218 }
7219 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007220 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007221 handleUnregisterNetworkOffer(noi);
7222 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007223 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007224 }
7225
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007226 @Override
James Mattisf7027322020-12-13 16:28:14 -08007227 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007228 if (request.hasTransport(TRANSPORT_TEST)) {
7229 enforceNetworkFactoryOrTestNetworksPermission();
7230 } else {
7231 enforceNetworkFactoryPermission();
7232 }
James Mattisf7027322020-12-13 16:28:14 -08007233 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7234 if (nri != null) {
7235 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7236 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7237 mHandler.post(() -> handleReleaseNetworkRequest(
7238 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7239 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007240 }
7241
Paul Jensen1f567382015-02-13 14:18:39 -05007242 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7243 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007244 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007245 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007246 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007247 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007248 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007249
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007250 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007251 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007252 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007253
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007254 // UID ranges for users that are currently blocked by VPNs.
7255 // This array is accessed and iterated on multiple threads without holding locks, so its
7256 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7257 // (on the handler thread).
7258 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7259
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007260 // Must only be accessed on the handler thread
7261 @NonNull
7262 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7263
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007264 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007265 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007266
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007267 // Current OEM network preferences. This object must only be written to on the handler thread.
7268 // Since it is immutable and always non-null, other threads may read it if they only care
7269 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007270 @NonNull
7271 private OemNetworkPreferences mOemNetworkPreferences =
7272 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007273 // Current per-profile network preferences. This object follows the same threading rules as
7274 // the OEM network preferences above.
7275 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007276 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7277 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007278
lucaslin3ba7cc22022-12-19 02:35:33 +00007279 // Current VPN network preferences. This object follows the same threading rules as the OEM
7280 // network preferences above.
7281 @NonNull
7282 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7283 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7284
paulhu51f77dc2021-06-07 02:34:20 +00007285 // A set of UIDs that should use mobile data preferentially if available. This object follows
7286 // the same threading rules as the OEM network preferences above.
7287 @NonNull
7288 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7289
James Mattiscb1e0362021-04-06 17:07:42 -07007290 // OemNetworkPreferences activity String log entries.
7291 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7292 @NonNull
7293 private final LocalLog mOemNetworkPreferencesLogs =
7294 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7295
James Mattis02220e22021-03-13 19:27:21 -08007296 /**
7297 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7298 * @param packageName the package name to check existence of a mapping for.
7299 * @return true if a mapping exists, false otherwise
7300 */
7301 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7302 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7303 }
7304
James Mattise3ef1912020-12-20 11:09:58 -08007305 // The always-on request for an Internet-capable network that apps without a specific default
7306 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007307 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007308 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007309 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007310 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007311 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007312 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007313 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007314
James Mattisd31bdfa2020-12-23 16:37:26 -08007315 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7316 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7317 }
7318
7319 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007320 * Return the default network request currently tracking the given uid.
7321 * @param uid the uid to check.
7322 * @return the NetworkRequestInfo tracking the given uid.
7323 */
7324 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007325 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007326 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007327 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007328 // Checking the first request is sufficient as only multilayer requests will have more
7329 // than one request and for multilayer, all requests will track the same uids.
7330 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007331 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007332 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007333 highestPriorityNri = nri;
7334 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007335 }
7336 }
paulhuaa0743d2021-05-26 21:56:03 +08007337 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007338 }
7339
7340 /**
7341 * Get a copy of the network requests of the default request that is currently tracking the
7342 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007343 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7344 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007345 * @param requestorUid the uid to check the default for.
7346 * @param requestorPackageName the requestor's package name.
7347 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7348 */
7349 @NonNull
7350 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007351 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007352 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007353 getDefaultRequestTrackingUid(asUid).mRequests,
7354 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007355 }
7356
7357 /**
7358 * Copy the given nri's NetworkRequest collection.
7359 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007360 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7361 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007362 * @param requestorUid the uid to set on the copied collection.
7363 * @param requestorPackageName the package name to set on the copied collection.
7364 * @return the copied NetworkRequest collection.
7365 */
7366 @NonNull
7367 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007368 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7369 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007370 final List<NetworkRequest> requests = new ArrayList<>();
7371 for (final NetworkRequest nr : requestsToCopy) {
7372 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007373 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007374 nr.legacyType, nextNetworkRequestId(), nr.type));
7375 }
7376 return requests;
7377 }
7378
7379 @NonNull
7380 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007381 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7382 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007383 // These capabilities are for a TRACK_DEFAULT callback, so:
7384 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7385 // mDefaultRequest and a per-UID default request.
7386 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007387 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007388 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007389 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7390 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007391 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007392 restrictRequestUidsForCallerAndSetRequestorInfo(
7393 netCap, requestorUid, requestorPackageName);
7394 return netCap;
7395 }
7396
7397 /**
7398 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7399 * @param nr the network request to check for equality against.
7400 * @return the nri if one exists, null otherwise.
7401 */
7402 @Nullable
7403 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7404 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7405 if (nri.getNetworkRequestForCallback().equals(nr)) {
7406 return nri;
7407 }
7408 }
7409 return null;
7410 }
7411
7412 /**
7413 * Check if an nri is currently being managed by per-app default networking.
7414 * @param nri the nri to check.
7415 * @return true if this nri is currently being managed by per-app default networking.
7416 */
7417 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7418 // nri.mRequests.get(0) is only different from the original request filed in
7419 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7420 // functionality therefore if these two don't match, it means this particular nri is
7421 // currently being managed by a per-app default.
7422 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7423 }
7424
7425 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007426 * Determine if an nri is a managed default request that disallows default networking.
7427 * @param nri the request to evaluate
7428 * @return true if device-default networking is disallowed
7429 */
7430 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7431 // Check if this nri is a managed default that supports the default network at its
7432 // lowest priority request.
7433 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7434 final NetworkCapabilities lowestPriorityNetCap =
7435 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7436 return isPerAppDefaultRequest(nri)
7437 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7438 lowestPriorityNetCap));
7439 }
7440
Erik Kline05f2b402015-04-30 12:58:40 +09007441 // Request used to optionally keep mobile data active even when higher
7442 // priority networks like Wi-Fi are active.
7443 private final NetworkRequest mDefaultMobileDataRequest;
7444
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007445 // Request used to optionally keep wifi data active even when higher
7446 // priority networks like ethernet are active.
7447 private final NetworkRequest mDefaultWifiRequest;
7448
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007449 // Request used to optionally keep vehicle internal network always active
7450 private final NetworkRequest mDefaultVehicleRequest;
7451
James Mattisd31bdfa2020-12-23 16:37:26 -08007452 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7453 // network with no service. This NAI should never be matched against, nor should any public API
7454 // ever return the associated network. For this reason, this NAI is not in the list of available
7455 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7456 // default requests that don't support using the device default network which will ultimately
7457 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7458 @VisibleForTesting
7459 final NetworkAgentInfo mNoServiceNetwork;
7460
Chalard Jean5b409c72021-02-04 13:12:59 +09007461 // The NetworkAgentInfo currently satisfying the default request, if any.
7462 private NetworkAgentInfo getDefaultNetwork() {
7463 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09007464 }
7465
James Mattis2516da32021-01-31 17:06:19 -08007466 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007467 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08007468 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7469 // Currently, all network requests will have the same uids therefore checking the first
7470 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007471 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08007472 if (null == uids) {
7473 continue;
7474 }
7475 for (final UidRange range : uids) {
7476 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08007477 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007478 highestPriorityNri = nri;
7479 }
James Mattis2516da32021-01-31 17:06:19 -08007480 }
7481 }
7482 }
paulhuaa0743d2021-05-26 21:56:03 +08007483 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08007484 }
7485
Varun Ananddf569952019-02-06 10:13:38 -08007486 @Nullable
7487 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
7488 return nai != null ? nai.network : null;
7489 }
7490
7491 private void ensureRunningOnConnectivityServiceThread() {
7492 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
7493 throw new IllegalStateException(
7494 "Not running on ConnectivityService thread: "
7495 + Thread.currentThread().getName());
7496 }
7497 }
7498
Chalard Jean3a3f5f22019-04-10 23:07:55 +09007499 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09007500 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
7501 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007502 }
7503
Chalard Jean29d06db2018-05-02 21:14:54 +09007504 /**
7505 * Register a new agent with ConnectivityService to handle a network.
7506 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007507 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09007508 * @param networkInfo the initial info associated with this network. It can be updated later :
7509 * see {@link #updateNetworkInfo}.
7510 * @param linkProperties the initial link properties of this network. They can be updated
7511 * later : see {@link #updateLinkProperties}.
7512 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007513 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007514 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007515 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007516 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007517 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007518 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007519 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007520 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007521 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7522 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007523 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7524 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7525 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007526 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007527 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007528 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08007529 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007530 } else {
7531 enforceNetworkFactoryPermission();
7532 }
7533
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007534 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007535 final long token = Binder.clearCallingIdentity();
7536 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007537 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007538 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007539 } finally {
7540 Binder.restoreCallingIdentity(token);
7541 }
7542 }
7543
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007544 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007545 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007546 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7547 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007548
Chalard Jeandbc46952022-02-02 00:14:18 +09007549 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
7550 // and mutate them at any time.
7551 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
7552 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
7553 final LinkProperties lpCopy = new LinkProperties(linkProperties);
7554
Chalard Jean366c5252022-01-25 18:27:53 +09007555 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09007556 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09007557 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7558 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007559 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09007560 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007561 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007562 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7563 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007564
Chalard Jeandbc46952022-02-02 00:14:18 +09007565 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09007566 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007567 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007568 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007569 mDeps.getNetworkStack().makeNetworkMonitor(
7570 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007571 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7572 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007573 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007574 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007575 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007576 }
7577
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007578 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007579 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007580 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09007581 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007582 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09007583 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
7584 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
7585 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09007586
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007587 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007588
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007589 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007590 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007591 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007592 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007593
7594 try {
7595 networkMonitor.start();
7596 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007597 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007598 }
Chalard Jean366c5252022-01-25 18:27:53 +09007599
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007600 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007601 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007602 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007603 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007604 }
7605
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007606 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7607 @NonNull public final NetworkOffer offer;
7608
7609 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7610 this.offer = offer;
7611 }
7612
7613 @Override
7614 public void binderDied() {
7615 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7616 }
7617 }
7618
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007619 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7620 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7621 if (npi.providerId == providerId) return true;
7622 }
7623 return false;
7624 }
7625
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007626 /**
7627 * Register or update a network offer.
7628 * @param newOffer The new offer. If the callback member is the same as an existing
7629 * offer, it is an update of that offer.
7630 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007631 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007632 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7633 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007634 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007635 // This may actually happen if a provider updates its score or registers and then
7636 // immediately unregisters. The offer would still be in the handler queue, but the
7637 // provider would have been removed.
7638 if (DBG) log("Received offer from an unregistered provider");
7639 return;
7640 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007641 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7642 if (null != existingOffer) {
7643 handleUnregisterNetworkOffer(existingOffer);
7644 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007645 if (DBG) {
7646 // handleUnregisterNetworkOffer has already logged the old offer
7647 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7648 }
7649 } else {
7650 if (DBG) {
7651 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7652 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007653 }
7654 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7655 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007656 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007657 } catch (RemoteException e) {
7658 noi.binderDied();
7659 return;
7660 }
7661 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007662 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007663 }
7664
7665 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7666 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007667 if (DBG) {
7668 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7669 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007670
7671 // If the provider removes the offer and dies immediately afterwards this
7672 // function may be called twice in a row, but the array will no longer contain
7673 // the offer.
7674 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007675 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007676 }
7677
7678 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7679 @NonNull final INetworkOfferCallback callback) {
7680 ensureRunningOnConnectivityServiceThread();
7681 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007682 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007683 }
7684 return null;
7685 }
7686
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007687 /**
7688 * Called when receiving LinkProperties directly from a NetworkAgent.
7689 * Stores into |nai| any data coming from the agent that might also be written to the network's
7690 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7691 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007692 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007693 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007694 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7695 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007696 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007697 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007698 }
7699
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007700 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08007701 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007702 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007703
Lorenzo Colittid523d142020-04-01 20:16:30 +09007704 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7705 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7706 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007707 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007708
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007709 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007710
7711 // update filtering rules, need to happen after the interface update so netd knows about the
7712 // new interface (the interface name -> index map becomes initialized)
7713 updateVpnFiltering(newLp, oldLp, networkAgent);
7714
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007715 updateMtu(newLp, oldLp);
7716 // TODO - figure out what to do for clat
7717// for (LinkProperties lp : newLp.getStackedLinks()) {
7718// updateMtu(lp, null);
7719// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007720 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007721 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7722 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007723
Erik Klineb9888902016-04-05 13:30:49 +09007724 updateRoutes(newLp, oldLp, netId);
7725 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007726 // Make sure LinkProperties represents the latest private DNS status.
7727 // This does not need to be done before updateDnses because the
7728 // LinkProperties are not the source of the private DNS configuration.
7729 // updateDnses will fetch the private DNS configuration from DnsManager.
7730 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007731
Chalard Jean5b409c72021-02-04 13:12:59 +09007732 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007733 handleApplyDefaultProxy(newLp.getHttpProxy());
7734 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007735 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007736 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007737
7738 updateWakeOnLan(newLp);
7739
Hai Shalome58bdc62021-01-11 18:45:34 -08007740 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7741 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7742 // does, it needs to be merged here.
7743 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7744 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007745
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007746 // TODO - move this check to cover the whole function
7747 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007748 synchronized (networkAgent) {
7749 networkAgent.linkProperties = newLp;
7750 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007751 // Start or stop DNS64 detection and 464xlat according to network state.
7752 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08007753 // Notify NSS when relevant events happened. Currently, NSS only cares about
7754 // interface changed to update clat interfaces accounting.
7755 final boolean interfacesChanged = oldLp == null
7756 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
7757 if (interfacesChanged) {
7758 notifyIfacesChangedForNetworkStats();
7759 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007760 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7761 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09007762 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007763 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007764
7765 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007766 }
7767
Hai Shalome58bdc62021-01-11 18:45:34 -08007768 /**
7769 * @param naData captive portal data from NetworkAgent
7770 * @param apiData captive portal data from capport API
7771 */
7772 @Nullable
7773 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7774 CaptivePortalData apiData) {
7775 if (naData == null || apiData == null) {
7776 return naData == null ? apiData : naData;
7777 }
7778 final CaptivePortalData.Builder captivePortalBuilder =
7779 new CaptivePortalData.Builder(naData);
7780
7781 if (apiData.isCaptive()) {
7782 captivePortalBuilder.setCaptive(true);
7783 }
7784 if (apiData.isSessionExtendable()) {
7785 captivePortalBuilder.setSessionExtendable(true);
7786 }
7787 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7788 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7789 // otherwise data would be inconsistent. Prefer the capport API info if present,
7790 // as it can generally be refreshed more often.
7791 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7792 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7793 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7794 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7795 // No source has time / bytes remaining information: surface the newest refresh time
7796 // for other fields
7797 captivePortalBuilder.setRefreshTime(
7798 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7799 }
7800
Hai Shalom7c6ab402021-02-04 19:34:06 -08007801 // Prioritize the user portal URL from the network agent if the source is authenticated.
7802 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7803 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7804 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7805 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007806 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007807 // Prioritize the venue information URL from the network agent if the source is
7808 // authenticated.
7809 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7810 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7811 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7812 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007813 }
7814 return captivePortalBuilder.build();
7815 }
7816
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007817 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007818 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007819 // marks on unsupported interfaces is harmless.
7820 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7821 return;
7822 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007823
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007824 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7825 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7826
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007827 // Mask/mark of zero will not detect anything interesting.
7828 // Don't install rules unless both values are nonzero.
7829 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007830 return;
7831 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007832
7833 final String prefix = "iface:" + iface;
7834 try {
7835 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007836 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007837 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007838 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007839 }
7840 } catch (Exception e) {
7841 loge("Exception modifying wakeup packet monitoring: " + e);
7842 }
7843
Joel Scherpelza235a812017-05-22 13:47:41 +09007844 }
7845
Junyu Lai970963e2022-10-25 15:46:47 +08007846 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09007847 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007848 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09007849 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08007850 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09007851 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007852 for (final String iface : interfaceDiff.added) {
7853 try {
7854 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007855 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09007856 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007857 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7858 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007859 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007860 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007861 }
Paul Jensenbff73492014-04-28 10:33:11 -04007862 }
7863 }
Chalard Jean9589e722019-11-19 19:03:53 +09007864 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007865 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007866 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007867 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007868 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007869 } catch (Exception e) {
7870 loge("Exception removing interface: " + e);
7871 }
7872 }
7873 }
7874
Tyler Weare4314862019-12-05 14:55:30 -08007875 // TODO: move to frameworks/libs/net.
7876 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7877 final String nextHop;
7878
7879 switch (route.getType()) {
7880 case RouteInfo.RTN_UNICAST:
7881 if (route.hasGateway()) {
7882 nextHop = route.getGateway().getHostAddress();
7883 } else {
7884 nextHop = INetd.NEXTHOP_NONE;
7885 }
7886 break;
7887 case RouteInfo.RTN_UNREACHABLE:
7888 nextHop = INetd.NEXTHOP_UNREACHABLE;
7889 break;
7890 case RouteInfo.RTN_THROW:
7891 nextHop = INetd.NEXTHOP_THROW;
7892 break;
7893 default:
7894 nextHop = INetd.NEXTHOP_NONE;
7895 break;
7896 }
7897
7898 final RouteInfoParcel rip = new RouteInfoParcel();
7899 rip.ifName = route.getInterface();
7900 rip.destination = route.getDestination().toString();
7901 rip.nextHop = nextHop;
7902 rip.mtu = route.getMtu();
7903
7904 return rip;
7905 }
7906
Paul Jensene0fd4a82014-08-06 15:51:33 -04007907 /**
7908 * Have netd update routes from oldLp to newLp.
7909 * @return true if routes changed between oldLp and newLp
7910 */
Junyu Lai970963e2022-10-25 15:46:47 +08007911 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
7912 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007913 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007914 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7915 new CompareOrUpdateResult<>(
7916 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08007917 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08007918 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007919
7920 // add routes before removing old in case it helps with continuous connectivity
7921
Chalard Jean9dd11612018-06-04 16:52:49 +09007922 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007923 for (RouteInfo route : routeDiff.added) {
7924 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007925 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007926 try {
Tyler Weare4314862019-12-05 14:55:30 -08007927 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007928 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007929 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007930 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007931 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007932 }
7933 }
7934 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007935 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007936 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007937 try {
Tyler Weare4314862019-12-05 14:55:30 -08007938 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007939 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007940 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007941 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007942 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007943 }
7944 }
7945
7946 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007947 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007948 try {
Tyler Weare4314862019-12-05 14:55:30 -08007949 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007950 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007951 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007952 }
7953 }
Tyler Weare4314862019-12-05 14:55:30 -08007954
7955 for (RouteInfo route : routeDiff.updated) {
7956 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7957 try {
7958 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7959 } catch (Exception e) {
7960 loge("Exception in networkUpdateRouteParcel: " + e);
7961 }
7962 }
7963 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7964 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007965 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007966
Junyu Lai970963e2022-10-25 15:46:47 +08007967 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
7968 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09007969 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7970 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007971 }
Erik Klineb9888902016-04-05 13:30:49 +09007972
Erik Kline31b4a9e2018-01-11 21:07:29 +09007973 if (DBG) {
7974 final Collection<InetAddress> dnses = newLp.getDnsServers();
7975 log("Setting DNS servers for network " + netId + " to " + dnses);
7976 }
Erik Klineb9888902016-04-05 13:30:49 +09007977 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007978 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007979 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007980 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007981 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007982 }
Erik Kline54e35c02017-04-07 15:29:29 +09007983 }
7984
Junyu Lai970963e2022-10-25 15:46:47 +08007985 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
7986 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00007987 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
7988 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00007989 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
7990 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007991
7992 if (!wasFiltering && !needsFiltering) {
7993 // Nothing to do.
7994 return;
7995 }
7996
7997 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7998 // Nothing changed.
7999 return;
8000 }
8001
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008002 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008003 if (ranges == null || ranges.isEmpty()) {
8004 return;
8005 }
8006
Qingxi Libb8da982020-01-17 17:54:27 -08008007 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008008 // TODO: this create a window of opportunity for apps to receive traffic between the time
8009 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008010 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008011 // old rules are being removed.
8012 if (wasFiltering) {
8013 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8014 }
8015 if (needsFiltering) {
8016 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8017 }
8018 }
8019
Valentin Iftime9fa35092019-09-24 13:32:13 +02008020 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008021 if (mWolSupportedInterfaces == null) {
8022 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008023 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008024 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008025 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8026 }
8027
Luke Huangb913c812018-08-24 20:33:16 +08008028 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008029 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008030 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008031 }
8032 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008033 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008034 }
Luke Huangb913c812018-08-24 20:33:16 +08008035 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008036 }
8037
Chalard Jean62edfd82019-12-02 18:39:29 +09008038 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8039 @NonNull final NetworkCapabilities newNc) {
8040 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8041 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008042 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008043 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008044 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008045 } catch (RemoteException | ServiceSpecificException e) {
8046 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008047 }
8048 }
8049 }
8050
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008051 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008052 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008053 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008054 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008055 underlyingNetworks = underlyingNetworksOrDefault(
8056 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008057 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008058 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8059 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008060 // metered if any underlying is metered, or originally declared metered by the agent.
8061 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008062 boolean roaming = false; // roaming if any underlying is roaming
8063 boolean congested = false; // congested if any underlying is congested
8064 boolean suspended = true; // suspended if all underlying are suspended
8065
8066 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008067 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008068 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008069 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008070 for (Network underlyingNetwork : underlyingNetworks) {
8071 final NetworkAgentInfo underlying =
8072 getNetworkAgentInfoForNetwork(underlyingNetwork);
8073 if (underlying == null) continue;
8074
8075 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8076 hadUnderlyingNetworks = true;
8077 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008078 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008079 }
8080
8081 // Merge capabilities of this underlying network. For bandwidth, assume the
8082 // worst case.
8083 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8084 underlyingCaps.getLinkDownstreamBandwidthKbps());
8085 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8086 underlyingCaps.getLinkUpstreamBandwidthKbps());
8087 // If this underlying network is metered, the VPN is metered (it may cost money
8088 // to send packets on this network).
8089 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8090 // If this underlying network is roaming, the VPN is roaming (the billing structure
8091 // is different than the usual, local one).
8092 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8093 // If this underlying network is congested, the VPN is congested (the current
8094 // condition of the network affects the performance of this network).
8095 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8096 // If this network is not suspended, the VPN is not suspended (the VPN
8097 // is able to transfer some data).
8098 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008099 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008100 }
8101 }
8102 if (!hadUnderlyingNetworks) {
8103 // No idea what the underlying networks are; assume reasonable defaults
8104 metered = true;
8105 roaming = false;
8106 congested = false;
8107 suspended = false;
8108 }
8109
Chalard Jean1d420b32022-10-12 16:39:37 +09008110 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008111 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8112 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8113 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8114 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8115 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8116 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008117 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008118 }
8119
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008120 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008121 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8122 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8123 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008124 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008125 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008126 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008127 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008128 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8129 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008130 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008131 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008132 if (nai.everConnected()
8133 && !nai.isVPN()
8134 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008135 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008136 // does not cause any request (that is not a listen) currently matching that agent to
8137 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008138 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008139 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008140 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008141 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008142 }
8143
Paul Jensen53f08952015-06-16 14:27:36 -04008144 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008145 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008146 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008147 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008148 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008149 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008150 }
Chalard Jean254bd162022-08-25 13:04:51 +09008151 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008152 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008153 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008154 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008155 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008156 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008157 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008158 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008159 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008160 }
Chalard Jean254bd162022-08-25 13:04:51 +09008161 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008162 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8163 } else {
8164 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8165 }
lucasline117e2e2019-10-22 18:27:33 +08008166 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008167
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008168 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008169 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8170 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008171 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008172 }
8173
Lorenzo Colittibd079452021-07-02 11:47:57 +09008174 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008175 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008176 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008177 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008178 }
8179
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008180 return newNc;
8181 }
8182
Lorenzo Colitti44840702021-01-11 22:27:57 +09008183 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8184 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8185 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8186 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8187 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8188 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8189 if (prevSuspended != suspended) {
8190 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8191 // onResumed have been removed.
8192 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8193 : ConnectivityManager.CALLBACK_RESUMED);
8194 }
8195 if (prevSuspended != suspended || prevRoaming != roaming) {
8196 // updateNetworkInfo will mix in the suspended info from the capabilities and
8197 // take appropriate action for the network having possibly changed state.
8198 updateNetworkInfo(nai, nai.networkInfo);
8199 }
8200 }
8201
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008202 /**
8203 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8204 *
8205 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8206 * capabilities we manage and store in {@code nai}, such as validated status and captive
8207 * portal status)
8208 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8209 * potentially triggers rematches.
8210 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8211 * change.)
8212 *
8213 * @param oldScore score of the network before any of the changes that prompted us
8214 * to call this function.
8215 * @param nai the network having its capabilities updated.
8216 * @param nc the new network capabilities.
8217 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008218 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008219 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008220 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008221 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008222 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8223 if (null != differences) {
8224 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8225 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008226 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008227 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008228
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008229 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008230 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008231 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008232
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008233 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008234 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8235 // the change we're processing can't affect any requests, it can only affect the listens
8236 // on this network. We might have been called by rematchNetworkAndRequests when a
8237 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008238 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008239 } else {
8240 // If the requestable capabilities have changed or the score changed, we can't have been
8241 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008242 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008243 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008244 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008245 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008246
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008247 final boolean oldMetered = prevNc.isMetered();
8248 final boolean newMetered = newNc.isMetered();
8249 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008250
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008251 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008252 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8253 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008254 }
junyulaif2c67e42018-08-07 19:50:45 +08008255
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008256 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8257 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008258
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008259 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008260 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008261 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008262 }
8263
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008264 // This network might have been underlying another network. Propagate its capabilities.
8265 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008266
8267 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008268 mDnsManager.updateTransportsForNetwork(
8269 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008270 }
lucaslin53e8a262021-06-08 01:43:59 +08008271
8272 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008273 }
8274
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008275 /** Convenience method to update the capabilities for a given network. */
8276 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008277 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008278 }
8279
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008280 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008281 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008282 *
8283 * Ingress interface filtering enforces that all apps under the given network can only receive
8284 * packets from the network's interface (and loopback). This is important for VPNs because
8285 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8286 * non-VPN interfaces.
8287 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008288 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008289 * 1. the network is an app VPN (not legacy VPN)
8290 * 2. the VPN does not allow bypass
8291 * 3. the VPN is fully-routed
8292 * 4. the VPN interface is non-null
8293 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008294 * @see INetd#firewallAddUidInterfaceRules
8295 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008296 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008297 @Nullable
8298 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008299 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008300 if (nc == null || lp == null) return null;
8301 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008302 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008303 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008304 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008305 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008306 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008307 && !lp.hasExcludeRoute()) {
8308 return lp.getInterfaceName();
8309 }
8310 return null;
8311 }
8312
8313 /**
8314 * Returns whether we need to set interface filtering rule or not
8315 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008316 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008317 String isolationIface) {
8318 // Allow rules are always needed if VPN isolation is enabled.
8319 if (isolationIface != null) return true;
8320
8321 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8322 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8323 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
8324 return SdkLevel.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008325 }
8326
Chiachang Wang28afaff2020-12-10 22:24:47 +08008327 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8328 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8329 int index = 0;
8330 for (UidRange range : ranges) {
8331 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8332 index++;
8333 }
8334 return stableRanges;
8335 }
8336
Chalard Jeane6c95272022-01-25 21:04:21 +09008337 private static UidRangeParcel[] intsToUidRangeStableParcels(
8338 final @NonNull ArraySet<Integer> uids) {
8339 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8340 int index = 0;
8341 for (int uid : uids) {
8342 stableRanges[index] = new UidRangeParcel(uid, uid);
8343 index++;
8344 }
8345 return stableRanges;
8346 }
8347
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008348 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8349 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8350 for (int i = 0; i < ranges.length; i++) {
8351 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8352 }
8353 return stableRanges;
8354 }
8355
Ken Chen5e65a852020-12-24 12:59:10 +08008356 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
8357 int[] exemptUids) {
8358 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8359 try {
8360 mNetd.socketDestroy(ranges, exemptUids);
8361 } catch (Exception e) {
8362 loge("Exception in socket destroy: ", e);
8363 }
8364 }
8365 }
8366
paulhuaa0743d2021-05-26 21:56:03 +08008367 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08008368 int[] exemptUids = new int[2];
8369 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8370 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8371 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
8372 exemptUids[0] = VPN_UID;
8373 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
8374 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8375
8376 maybeCloseSockets(nai, ranges, exemptUids);
8377 try {
8378 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008379 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008380 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008381 } else {
paulhu0e79d952021-06-09 16:11:35 +08008382 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008383 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008384 }
8385 } catch (Exception e) {
8386 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8387 " on netId " + nai.network.netId + ". " + e);
8388 }
8389 maybeCloseSockets(nai, ranges, exemptUids);
8390 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008391
lucaslin53e8a262021-06-08 01:43:59 +08008392 private boolean isProxySetOnAnyDefaultNetwork() {
8393 ensureRunningOnConnectivityServiceThread();
8394 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8395 final NetworkAgentInfo nai = nri.getSatisfier();
8396 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8397 return true;
8398 }
8399 }
8400 return false;
8401 }
8402
8403 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8404 NetworkCapabilities newNc) {
8405 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8406 // the proxy might be changed since the default network satisfied by the apps might also
8407 // changed.
8408 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
8409 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09008410 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
8411 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09008412 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08008413 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
8414 mProxyTracker.sendProxyBroadcast();
8415 }
8416 }
8417
Chalard Jeane6c95272022-01-25 21:04:21 +09008418 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
8419 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008420 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
8421 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008422 if (null == prevRanges) prevRanges = new ArraySet<>();
8423 if (null == newRanges) newRanges = new ArraySet<>();
8424 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
8425
8426 prevRanges.removeAll(newRanges);
8427 newRanges.removeAll(prevRangesCopy);
8428
8429 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008430 // When updating the VPN uid routing rules, add the new range first then remove the old
8431 // range. If old range were removed first, there would be a window between the old
8432 // range being removed and the new range being added, during which UIDs contained
8433 // in both ranges are not subject to any VPN routing rules. Adding new range before
8434 // removing old range works because, unlike the filtering rules below, it's possible to
8435 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08008436 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
8437 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
8438 // [1-5] & [1-2],[4-5] == [3]
8439 // Then we can do:
8440 // maybeCloseSockets([3])
8441 // mNetd.networkAddUidRanges([1-2],[4-5])
8442 // mNetd.networkRemoveUidRanges([1-5])
8443 // maybeCloseSockets([3])
8444 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
8445 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09008446 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008447 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008448 }
8449 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008450 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008451 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00008452 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
8453 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008454 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
8455 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008456 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09008457 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008458 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
8459 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
8460 // were added first and then newRanges got removed later, there would be only one uid
8461 // 10013 left. A consequence of removing old ranges before adding new ranges is that
8462 // there is now a window of opportunity when the UIDs are not subject to any filtering.
8463 // Note that this is in contrast with the (more robust) update of VPN routing rules
8464 // above, where the addition of new ranges happens before the removal of old ranges.
8465 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
8466 // to be removed will never overlap with the new range to be added.
8467 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008468 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
8469 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008470 }
8471 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008472 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008473 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09008474 } catch (Exception e) {
8475 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008476 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008477 }
8478 }
8479
Chalard Jeande665262022-02-25 16:12:12 +09008480 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09008481 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
8482 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09008483 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
8484 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09008485 if (prevEmpty && newEmpty) return;
8486
8487 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09008488 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008489 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09008490 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008491
8492 if (prevUids.equals(newUids)) return;
8493
8494 // This implementation is very simple and vastly faster for sets of Integers than
8495 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
8496 // a key computed from the value and has storage for that.
8497 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
8498 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
8499 toRemove.removeAll(newUids);
8500 toAdd.removeAll(prevUids);
8501
8502 try {
8503 if (!toAdd.isEmpty()) {
8504 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
8505 nai.network.netId,
8506 intsToUidRangeStableParcels(toAdd),
8507 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8508 }
8509 if (!toRemove.isEmpty()) {
8510 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
8511 nai.network.netId,
8512 intsToUidRangeStableParcels(toRemove),
8513 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8514 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008515 } catch (ServiceSpecificException e) {
8516 // Has the interface disappeared since the network was built ?
8517 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09008518 } catch (RemoteException e) {
8519 // Netd died. This usually causes a runtime restart anyway.
8520 }
8521 }
8522
Junyu Lai2ed7d412022-10-07 16:52:21 +08008523 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
8524 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008525 ensureRunningOnConnectivityServiceThread();
8526
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008527 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008528 // Ignore updates for disconnected networks
8529 return;
8530 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008531 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008532 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09008533 + "; created=" + nai.getCreatedTime()
8534 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00008535 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008536 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8537 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008538 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008539 }
8540
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008541 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8542 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008543 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008544 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008545 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008546 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8547 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8548 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008549 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8550 // need to be sent as a separate extra.
8551 final NetworkRequest req = nri.isMultilayerRequest()
8552 ? nri.getActiveRequest()
8553 // Non-multilayer listen requests do not have an active request
8554 : nri.mRequests.get(0);
8555 if (req == null) {
8556 Log.wtf(TAG, "No request in NRI " + nri);
8557 }
8558 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008559 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008560 sendIntent(nri.mPendingIntent, intent);
8561 }
8562 // else not handled
8563 }
8564
Michael Groover73f69482023-01-27 11:01:25 -06008565 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
8566 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008567 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8568 mPendingIntentWakeLock.acquire();
8569 try {
8570 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00008571 final BroadcastOptions options = BroadcastOptions.makeBasic();
8572 if (SdkLevel.isAtLeastT()) {
8573 // Explicitly disallow the receiver from starting activities, to prevent apps from
8574 // utilizing the PendingIntent as a backdoor to do this.
8575 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
8576 }
8577 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
8578 null /* requiredPermission */,
8579 SdkLevel.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008580 } catch (PendingIntent.CanceledException e) {
8581 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8582 mPendingIntentWakeLock.release();
8583 releasePendingNetworkRequest(pendingIntent);
8584 }
8585 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8586 }
8587
8588 @Override
8589 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8590 String resultData, Bundle resultExtras) {
8591 if (DBG) log("Finished sending " + pendingIntent);
8592 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008593 // Release with a delay so the receiving client has an opportunity to put in its
8594 // own request.
8595 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008596 }
8597
Chalard Jean46bfbf02022-02-02 00:56:25 +09008598 // networkAgent is only allowed to be null if notificationType is
8599 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
8600 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08008601 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09008602 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08008603 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008604 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008605 // Default request has no msgr. Also prevents callbacks from being invoked for
8606 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8607 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8608 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008609 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008610 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008611 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008612 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008613 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008614 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008615 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008616 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8617 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008618 }
Roshan Pius951c0032020-12-22 15:10:42 -08008619 final boolean includeLocationSensitiveInfo =
8620 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008621 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008622 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008623 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08008624 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09008625 networkCapabilitiesRestrictedForCallerPermissions(
8626 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
8627 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008628 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09008629 nri.mCallingAttributionTag);
8630 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008631 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8632 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008633 // For this notification, arg1 contains the blocked status.
8634 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008635 break;
8636 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008637 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008638 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008639 break;
8640 }
8641 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008642 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008643 final NetworkCapabilities netCap =
8644 networkCapabilitiesRestrictedForCallerPermissions(
8645 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8646 putParcelable(
8647 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008648 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008649 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008650 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008651 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008652 break;
8653 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008654 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008655 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8656 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008657 break;
8658 }
junyulaif2c67e42018-08-07 19:50:45 +08008659 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008660 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008661 msg.arg1 = arg1;
8662 break;
8663 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008664 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008665 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008666 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008667 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008668 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008669 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008670 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008671 }
James Mattis45d81842021-01-10 14:24:24 -08008672 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008673 } catch (RemoteException e) {
8674 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008675 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008676 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008677 }
8678
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008679 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8680 bundle.putParcelable(t.getClass().getSimpleName(), t);
8681 }
8682
Chalard Jean0702f982021-09-16 21:50:07 +09008683 /**
8684 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8685 *
8686 * When a request should be assigned to a new network, it is normally lingered to give
8687 * time for apps to gracefully migrate their connections. When both networks are on the same
8688 * radio, but that radio can't do time-sharing efficiently, this may end up being
8689 * counter-productive because any traffic on the old network may drastically reduce the
8690 * performance of the new network.
8691 * The stack supports a configuration to let modem vendors state that their radio can't
8692 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8693 * from one cell network to another can't be done gracefully.
8694 *
8695 * @param oldNai the old network serving the request
8696 * @param newNai the new network serving the request
8697 * @return whether the switch can be graceful
8698 */
8699 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8700 @NonNull final NetworkAgentInfo newSatisfier) {
8701 if (mCellularRadioTimesharingCapable) return true;
8702 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8703 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8704 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8705 }
8706
Paul Jensenaf94b982014-09-30 15:37:41 -04008707 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008708 if (nai.numRequestNetworkRequests() != 0) {
8709 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8710 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008711 // Ignore listening and track default requests.
8712 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008713 loge("Dead network still had at least " + nr);
8714 break;
8715 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008716 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008717 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008718 }
8719
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008720 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8721 if (oldNetwork == null) {
8722 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8723 return;
8724 }
Chalard Jean49707572019-12-10 21:07:02 +09008725 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008726
8727 // If we get here it means that the last linger timeout for this network expired. So there
8728 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008729 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008730
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008731 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008732 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008733 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008734 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008735 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008736 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008737 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008738 }
8739
James Mattise3ef1912020-12-20 11:09:58 -08008740 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8741 boolean isDefaultChanged = false;
8742 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8743 final NetworkReassignment.RequestReassignment reassignment =
8744 changes.getReassignment(defaultRequestInfo);
8745 if (null == reassignment) {
8746 continue;
8747 }
8748 // reassignment only contains those instances where the satisfying network changed.
8749 isDefaultChanged = true;
8750 // Notify system services of the new default.
8751 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8752 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008753
James Mattise3ef1912020-12-20 11:09:58 -08008754 if (isDefaultChanged) {
8755 // Hold a wakelock for a short time to help apps in migrating to a new default.
8756 scheduleReleaseNetworkTransitionWakelock();
8757 }
8758 }
8759
8760 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8761 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8762 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8763 if (DBG) {
8764 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8765 }
Chalard Jean8e382112019-12-03 20:45:30 +09008766
James Mattisd31bdfa2020-12-23 16:37:26 -08008767 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8768 if (newDefaultNetwork != null) {
8769 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008770 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008771
James Mattisd31bdfa2020-12-23 16:37:26 -08008772 // Set an app level managed default and return since further processing only applies to the
8773 // default network.
8774 if (mDefaultRequest != nri) {
8775 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8776 return;
8777 }
8778
8779 makeDefaultNetwork(newDefaultNetwork);
8780
James Mattise3ef1912020-12-20 11:09:58 -08008781 if (oldDefaultNetwork != null) {
8782 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8783 }
8784 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008785 handleApplyDefaultProxy(null != newDefaultNetwork
8786 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8787 updateTcpBufferSizes(null != newDefaultNetwork
8788 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008789 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008790 }
8791
James Mattisd31bdfa2020-12-23 16:37:26 -08008792 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8793 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8794 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8795 try {
8796 if (VDBG) {
8797 log("Setting default network for " + nri
8798 + " using UIDs " + nri.getUids()
8799 + " with old network " + (oldDefaultNetwork != null
8800 ? oldDefaultNetwork.network().getNetId() : "null")
8801 + " and new network " + (newDefaultNetwork != null
8802 ? newDefaultNetwork.network().getNetId() : "null"));
8803 }
8804 if (nri.getUids().isEmpty()) {
8805 throw new IllegalStateException("makeDefaultForApps called without specifying"
8806 + " any applications to set as the default." + nri);
8807 }
8808 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008809 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008810 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008811 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008812 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008813 }
8814 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008815 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008816 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008817 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008818 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008819 }
8820 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008821 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008822 }
8823 }
8824
Junyu Lai35665cc2022-12-19 17:37:48 +08008825 /**
8826 * Collect restricted uid ranges for the given network and UserHandle, these uids
8827 * are not restricted for matched enterprise networks but being restricted for non-matched
8828 * enterprise networks and non-enterprise networks.
8829 */
8830 @NonNull
8831 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
8832 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
8833 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
8834 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
8835 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
8836
8837 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
8838 // The NC is built from a `ProfileNetworkPreference` which has only one
8839 // enterprise ID, so it's guaranteed to have exactly one.
8840 final int prefId = pref.capabilities.getEnterpriseIds()[0];
8841 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
8842 continue;
8843 }
8844 }
8845
8846 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
8847 pref.capabilities.getUidRanges())) {
8848 throw new IllegalArgumentException(
8849 "Overlapping uid range in preference: " + pref);
8850 }
8851 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
8852 }
8853 return restrictedUidRanges;
8854 }
8855
8856 private void updateProfileAllowedNetworks() {
8857 ensureRunningOnConnectivityServiceThread();
8858 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
8859 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
8860 .getUserHandles(true /* excludeDying */);
8861 if (users.isEmpty()) {
8862 throw new IllegalStateException("No user is available");
8863 }
8864
8865 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
8866 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
8867 for (final UserHandle user : users) {
8868 final ArraySet<UidRange> restrictedUidRanges =
8869 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
8870 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
8871 UidRange.createForUser(user), restrictedUidRanges));
8872 }
8873
8874 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
8875 configs.add(new NativeUidRangeConfig(
8876 nai.network.netId, rangesParcel, 0 /* subPriority */));
8877 }
8878
8879 // The netd API replaces the previous configs with the current configs.
8880 // Thus, for network disconnection or preference removal, no need to
8881 // unset previous config. Instead, collecting all currently needed
8882 // configs and issue to netd.
8883 try {
8884 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
8885 } catch (ServiceSpecificException e) {
8886 // Has the interface disappeared since the network was built?
8887 } catch (RemoteException e) {
8888 // Netd died. This usually causes a runtime restart anyway.
8889 }
8890 }
8891
James Mattisd31bdfa2020-12-23 16:37:26 -08008892 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8893 try {
8894 if (null != newDefaultNetwork) {
8895 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8896 } else {
8897 mNetd.networkClearDefault();
8898 }
8899 } catch (RemoteException | ServiceSpecificException e) {
8900 loge("Exception setting default network :" + e);
8901 }
8902 }
8903
Chalard Jean05cbe972019-12-09 11:50:38 +09008904 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008905 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09008906 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09008907 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09008908 processNewlySatisfiedListenRequests(nai);
8909 }
8910
8911 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008912 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8913 if (nri.isMultilayerRequest()) {
8914 continue;
8915 }
8916 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008917 if (!nr.isListen()) continue;
8918 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08008919 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008920 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
8921 }
8922 }
Chalard Jeancd397a22019-11-22 22:33:33 +09008923 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008924
Chalard Jeancd397a22019-11-22 22:33:33 +09008925 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008926 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8927 if (nri.isMultilayerRequest()) {
8928 continue;
8929 }
8930 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008931 if (!nr.isListen()) continue;
8932 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
8933 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09008934 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008935 }
8936 }
8937 }
8938
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008939 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008940 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008941 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08008942 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09008943 @Nullable public final NetworkRequest mOldNetworkRequest;
8944 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008945 @Nullable public final NetworkAgentInfo mOldNetwork;
8946 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08008947 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008948 @Nullable final NetworkRequest oldNetworkRequest,
8949 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008950 @Nullable final NetworkAgentInfo oldNetwork,
8951 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008952 mNetworkRequestInfo = networkRequestInfo;
8953 mOldNetworkRequest = oldNetworkRequest;
8954 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008955 mOldNetwork = oldNetwork;
8956 mNewNetwork = newNetwork;
8957 }
Chalard Jean49707572019-12-10 21:07:02 +09008958
8959 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09008960 final NetworkRequest requestToShow = null != mNewNetworkRequest
8961 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
8962 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08008963 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
8964 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09008965 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008966 }
8967
Chalard Jean46a62372019-12-10 21:25:24 +09008968 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008969
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008970 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09008971 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008972 }
8973
8974 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09008975 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09008976 // The code is never supposed to add two reassignments of the same request. Make
8977 // sure this stays true, but without imposing this expensive check on all
8978 // reassignments on all user devices.
8979 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08008980 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09008981 throw new IllegalStateException("Trying to reassign ["
8982 + reassignment + "] but already have ["
8983 + existing + "]");
8984 }
8985 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09008986 }
Chalard Jean46a62372019-12-10 21:25:24 +09008987 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008988 }
8989
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008990 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09008991 // the passed request.
8992 @Nullable
8993 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008994 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008995 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008996 }
8997 return null;
8998 }
Chalard Jean49707572019-12-10 21:07:02 +09008999
9000 public String toString() {
9001 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9002 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009003 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009004 for (final RequestReassignment rr : getRequestReassignments()) {
9005 sj.add(rr.toString());
9006 }
9007 return sj.toString();
9008 }
9009
9010 public String debugString() {
9011 final StringBuilder sb = new StringBuilder();
9012 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009013 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009014 for (final RequestReassignment rr : getRequestReassignments()) {
9015 sb.append("\n ").append(rr);
9016 }
9017 return sb.append("\n").toString();
9018 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009019 }
9020
Chalard Jean24344d72019-12-04 13:32:31 +09009021 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009022 @Nullable final NetworkRequest previousRequest,
9023 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009024 @Nullable final NetworkAgentInfo previousSatisfier,
9025 @Nullable final NetworkAgentInfo newSatisfier,
9026 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009027 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009028 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009029 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009030 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009031 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09009032 }
James Mattisa076c532020-12-02 14:12:41 -08009033 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009034 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009035 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009036 // If this network switch can't be supported gracefully, the request is not
9037 // lingered. This allows letting go of the network sooner to reclaim some
9038 // performance on the new network, since the radio can't do both at the same
9039 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009040 //
9041 // Also don't linger the request if the old network has been destroyed.
9042 // A destroyed network does not provide actual network connectivity, so
9043 // lingering it is not useful. In particular this ensures that a destroyed
9044 // network is outscored by its replacement,
9045 // then it is torn down immediately instead of being lingered, and any apps that
9046 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009047 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9048 }
Chalard Jean24344d72019-12-04 13:32:31 +09009049 } else {
9050 if (VDBG || DDBG) log(" accepting network in place of null");
9051 }
junyulai0ac374f2020-12-14 18:41:52 +08009052
9053 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9054 // and immediately satisfies a request then remove the timer. This will happen for
9055 // all networks except in the case of an underlying network for a VCN.
9056 if (newSatisfier.isNascent()) {
9057 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009058 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009059 }
9060
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009061 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009062 newSatisfier.unlingerRequest(newRequest.requestId);
9063 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009064 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009065 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009066 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009067 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009068 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009069 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009070 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009071 }
James Mattisa076c532020-12-02 14:12:41 -08009072 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009073 }
James Mattisa076c532020-12-02 14:12:41 -08009074 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009075 }
9076
James Mattisa076c532020-12-02 14:12:41 -08009077 /**
9078 * This function is triggered when something can affect what network should satisfy what
9079 * request, and it computes the network reassignment from the passed collection of requests to
9080 * network match to the one that the system should now have. That data is encoded in an
9081 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9082 * satisfier.
9083 *
9084 * After the reassignment is computed, it is applied to the state objects.
9085 *
9086 * @param networkRequests the nri objects to evaluate for possible network reassignment
9087 * @return NetworkReassignment listing of proposed network assignment changes
9088 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009089 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009090 private NetworkReassignment computeNetworkReassignment(
9091 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009092 final NetworkReassignment changes = new NetworkReassignment();
9093
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009094 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009095 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009096 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009097 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009098 }
Chalard Jean857a1712019-12-10 21:08:07 +09009099
James Mattisa076c532020-12-02 14:12:41 -08009100 for (final NetworkRequestInfo nri : networkRequests) {
9101 // Non-multilayer listen requests can be ignored.
9102 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9103 continue;
9104 }
9105 NetworkAgentInfo bestNetwork = null;
9106 NetworkRequest bestRequest = null;
9107 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009108 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009109 // Stop evaluating as the highest possible priority request is satisfied.
9110 if (null != bestNetwork) {
9111 bestRequest = req;
9112 break;
9113 }
9114 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009115 if (null == bestNetwork && isDefaultBlocked(nri)) {
9116 // Remove default networking if disallowed for managed default requests.
9117 bestNetwork = mNoServiceNetwork;
9118 }
9119 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009120 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009121 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009122 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009123 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009124 }
9125 return changes;
9126 }
9127
James Mattisa076c532020-12-02 14:12:41 -08009128 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9129 return new HashSet<>(mNetworkRequests.values());
9130 }
9131
Paul Jensenc88b39b2015-06-16 14:27:36 -04009132 /**
James Mattisa076c532020-12-02 14:12:41 -08009133 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009134 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009135 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009136 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009137 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9138 }
9139
9140 /**
9141 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9142 * being disconnected.
9143 */
9144 private void rematchNetworksAndRequests(
9145 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9146 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009147 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009148 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009149 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09009150 final long computed = SystemClock.elapsedRealtime();
9151 applyNetworkReassignment(changes, start);
9152 final long applied = SystemClock.elapsedRealtime();
9153 issueNetworkNeeds();
9154 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09009155 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009156 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
9157 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009158 log(changes.debugString());
9159 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009160 // Shorter form, only one line of log
9161 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
9162 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009163 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09009164 }
Chalard Jean64520dc2019-12-04 19:55:32 +09009165
Chalard Jeand7f762d2019-12-10 19:01:29 +09009166 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09009167 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009168 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09009169
9170 // Since most of the time there are only 0 or 1 background networks, it would probably
9171 // be more efficient to just use an ArrayList here. TODO : measure performance
9172 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
9173 for (final NetworkAgentInfo nai : nais) {
9174 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
9175 }
9176
Chalard Jeand7f762d2019-12-10 19:01:29 +09009177 // First, update the lists of satisfied requests in the network agents. This is necessary
9178 // because some code later depends on this state to be correct, most prominently computing
9179 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09009180 for (final NetworkReassignment.RequestReassignment event :
9181 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009182 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
9183 event.mOldNetworkRequest, event.mNewNetworkRequest,
9184 event.mOldNetwork, event.mNewNetwork,
9185 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09009186 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009187
James Mattise3ef1912020-12-20 11:09:58 -08009188 // Process default network changes if applicable.
9189 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009190
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009191 // Notify requested networks are available after the default net is switched, but
9192 // before LegacyTypeTracker sends legacy broadcasts
9193 for (final NetworkReassignment.RequestReassignment event :
9194 changes.getRequestReassignments()) {
9195 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009196 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009197 } else {
James Mattisa076c532020-12-02 14:12:41 -08009198 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009199 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009200 }
9201 }
9202
junyulai0ac374f2020-12-14 18:41:52 +08009203 // Update the inactivity state before processing listen callbacks, because the background
9204 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009205 // just yet though, because they have to be sent after the listens are processed to keep
9206 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08009207 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09009208 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08009209 // Rematching may have altered the inactivity state of some networks, so update all
9210 // inactivity timers. updateInactivityState reads the state from the network agent
9211 // and does nothing if the state has not changed : the source of truth is controlled
9212 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
9213 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08009214 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08009215 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009216 }
9217 }
9218
Chalard Jeanb10ab412019-12-11 14:12:30 +09009219 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009220 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009221 // Process listen requests and update capabilities if the background state has
9222 // changed for this network. For consistency with previous behavior, send onLost
9223 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09009224 processNewlyLostListenRequests(nai);
9225 if (oldBackground != nai.isBackgroundNetwork()) {
9226 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009227 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09009228 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009229 }
9230
junyulai0ac374f2020-12-14 18:41:52 +08009231 for (final NetworkAgentInfo nai : inactiveNetworks) {
9232 // For nascent networks, if connecting with no foreground request, skip broadcasting
9233 // LOSING for backward compatibility. This is typical when mobile data connected while
9234 // wifi connected with mobile data always-on enabled.
9235 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009236 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009237 }
9238
James Mattise3ef1912020-12-20 11:09:58 -08009239 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09009240
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009241 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009242 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009243 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08009244 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009245 // This network has active linger timers and no requests, but is not
9246 // lingering. Linger it.
9247 //
9248 // One way (the only way?) this can happen if this network is unvalidated
9249 // and became unneeded due to another network improving its score to the
9250 // point where this network will no longer be able to satisfy any requests
9251 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08009252 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009253 notifyNetworkLosing(nai, now);
9254 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09009255 } else {
Chalard Jean49707572019-12-10 21:07:02 +09009256 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09009257 teardownUnneededNetwork(nai);
9258 }
9259 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04009260 }
9261 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009262
Chalard Jean62edfd82019-12-02 18:39:29 +09009263 /**
9264 * Apply a change in background state resulting from rematching networks with requests.
9265 *
9266 * During rematch, a network may change background states by starting to satisfy or stopping
9267 * to satisfy a foreground request. Listens don't count for this. When a network changes
9268 * background states, its capabilities need to be updated and callbacks fired for the
9269 * capability change.
9270 *
9271 * @param nai The network that changed background states
9272 */
9273 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
9274 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
9275 if (Objects.equals(nai.networkCapabilities, newNc)) return;
9276 updateNetworkPermissions(nai, newNc);
9277 nai.getAndSetNetworkCapabilities(newNc);
9278 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
9279 }
9280
Chalard Jeanf0344532019-11-19 19:23:38 +09009281 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08009282 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009283 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09009284 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
9285 changes.getReassignment(mDefaultRequest);
9286 final NetworkAgentInfo oldDefaultNetwork =
9287 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
9288 final NetworkAgentInfo newDefaultNetwork =
9289 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08009290
Chalard Jean5b409c72021-02-04 13:12:59 +09009291 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009292 // Maintain the illusion : since the legacy API only understands one network at a time,
9293 // if the default network changed, apps should see a disconnected broadcast for the
9294 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09009295 if (oldDefaultNetwork != null) {
9296 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
9297 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009298 }
Chalard Jean5b409c72021-02-04 13:12:59 +09009299 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009300 // The new default network can be newly null if and only if the old default
9301 // network doesn't satisfy the default request any more because it lost a
9302 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09009303 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08009304 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09009305 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009306 }
9307 }
9308
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009309 // Now that all the callbacks have been sent, send the legacy network broadcasts
9310 // as needed. This is necessary so that legacy requests correctly bind dns
9311 // requests to this network. The legacy users are listening for this broadcast
9312 // and will generally do a dns request so they can ensureRouteToHost and if
9313 // they do that before the callbacks happen they'll use the default network.
9314 //
9315 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
9316 // callbacks, but if apps can receive the broadcast before the callback, they still might
9317 // have an inconsistent view of networking.
9318 //
9319 // This *does* introduce a race where if the user uses the new api
9320 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
9321 // they may get old info. Reverse this after the old startUsing api is removed.
9322 // This is on top of the multiple intent sequencing referenced in the todo above.
9323 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09009324 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009325 addNetworkToLegacyTypeTracker(nai);
9326 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08009327 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009328 }
9329
Chalard Jean0354d8c2021-01-12 10:58:56 +09009330 private void issueNetworkNeeds() {
9331 ensureRunningOnConnectivityServiceThread();
9332 for (final NetworkOfferInfo noi : mNetworkOffers) {
9333 issueNetworkNeeds(noi);
9334 }
9335 }
9336
9337 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
9338 ensureRunningOnConnectivityServiceThread();
9339 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9340 informOffer(nri, noi.offer, mNetworkRanker);
9341 }
9342 }
9343
9344 /**
9345 * Inform a NetworkOffer about any new situation of a request.
9346 *
9347 * This function handles updates to offers. A number of events may happen that require
9348 * updating the registrant for this offer about the situation :
9349 * • The offer itself was updated. This may lead the offer to no longer being able
9350 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
9351 * or conversely being strengthened enough to beat the satisfier (and therefore
9352 * start being needed)
9353 * • The network satisfying a request changed (including cases where the request
9354 * starts or stops being satisfied). The new network may be a stronger or weaker
9355 * match than the old one, possibly affecting whether the offer is needed.
9356 * • The network satisfying a request updated their score. This may lead the offer
9357 * to no longer be able to beat it if the current satisfier got better, or
9358 * conversely start being a good choice if the current satisfier got weaker.
9359 *
9360 * @param nri The request
9361 * @param offer The offer. This may be an updated offer.
9362 */
9363 private static void informOffer(@NonNull NetworkRequestInfo nri,
9364 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9365 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9366 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009367
9368 // Multi-layer requests have a currently active request, the one being satisfied.
9369 // Since the system will try to bring up a better network than is currently satisfying
9370 // the request, NetworkProviders need to be told the offers matching the requests *above*
9371 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9372 // not needed, and the offer is needed for the active request iff the offer can beat
9373 // the satisfier.
9374 // For non-multilayer requests, the logic above gracefully degenerates to only the
9375 // last case.
9376 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9377 // providers that the offer is needed for this request, until the active request is found.
9378 // In a second phase, deal with the currently active request. In a third phase, inform
9379 // the providers that offer is unneeded for the remaining requests.
9380
9381 // First phase : inform providers of all requests above the active request.
9382 int i;
9383 for (i = 0; nri.mRequests.size() > i; ++i) {
9384 final NetworkRequest request = nri.mRequests.get(i);
9385 if (activeRequest == request) break; // Found the active request : go to phase 2
9386 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9387 // Since this request is higher-priority than the one currently satisfied, if the
9388 // offer can satisfy it, the provider should try and bring up the network for sure ;
9389 // no need to even ask the ranker – an offer that can satisfy is always better than
9390 // no network. Hence tell the provider so unless it already knew.
9391 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
9392 offer.onNetworkNeeded(request);
9393 }
9394 }
9395
9396 // Second phase : deal with the active request (if any)
9397 if (null != activeRequest && activeRequest.isRequest()) {
9398 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00009399 // If an offer can satisfy the request, it is considered needed if it is currently
9400 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09009401 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00009402 && satisfier.factorySerialNumber == offer.providerId
9403 && activeRequest.canBeSatisfiedBy(offer.caps);
9404 final boolean newNeeded = currentlyServing
9405 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09009406 if (newNeeded != oldNeeded) {
9407 if (newNeeded) {
9408 offer.onNetworkNeeded(activeRequest);
9409 } else {
9410 // The offer used to be able to beat the satisfier. Now it can't.
9411 offer.onNetworkUnneeded(activeRequest);
9412 }
9413 }
9414 }
9415
9416 // Third phase : inform the providers that the offer isn't needed for any request
9417 // below the active one.
9418 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
9419 final NetworkRequest request = nri.mRequests.get(i);
9420 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9421 // Since this request is lower-priority than the one currently satisfied, if the
9422 // offer can satisfy it, the provider should not try and bring up the network.
9423 // Hence tell the provider so unless it already knew.
9424 if (offer.neededFor(request)) {
9425 offer.onNetworkUnneeded(request);
9426 }
9427 }
9428 }
9429
Chalard Jean61c79252019-11-07 23:07:32 +09009430 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
9431 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9432 NetworkRequest nr = nai.requestAt(i);
9433 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
9434 // legacy type tracker filters out repeat adds
9435 mLegacyTypeTracker.add(nr.legacyType, nai);
9436 }
9437 }
9438
9439 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09009440 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09009441 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
9442 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
9443 if (nai.isVPN()) {
9444 mLegacyTypeTracker.add(TYPE_VPN, nai);
9445 }
9446 }
9447
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09009448 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04009449 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +09009450 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09009451 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04009452 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09009453 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009454
Chalard Jean254bd162022-08-25 13:04:51 +09009455 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009456 // Don't repeat publish.
9457 if (newInetCondition == mDefaultInetConditionPublished) return;
9458
9459 mDefaultInetConditionPublished = newInetCondition;
9460 sendInetConditionBroadcast(nai.networkInfo);
9461 }
9462
Chalard Jeand61375d2020-01-14 22:46:36 +09009463 @NonNull
9464 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
9465 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009466 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09009467 final boolean suspended =
9468 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9469 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
9470 // Only override the state with SUSPENDED if the network is currently in CONNECTED
9471 // state. This is because the network could have been suspended before connecting,
9472 // or it could be disconnecting while being suspended, and in both these cases
9473 // the state should not be overridden. Note that the only detailed state that
9474 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
9475 // worry about multiple different substates of CONNECTED.
9476 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
9477 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009478 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
9479 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
9480 // network agent is created, then goes to suspended, then goes out of suspended without
9481 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +09009482 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009483 ? NetworkInfo.DetailedState.CONNECTED
9484 : NetworkInfo.DetailedState.CONNECTING,
9485 info.getReason(),
9486 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09009487 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009488 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09009489 return newInfo;
9490 }
9491
9492 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
9493 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
9494
Erik Kline99f301b2017-02-15 19:59:17 +09009495 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009496 NetworkInfo oldInfo = null;
9497 synchronized (networkAgent) {
9498 oldInfo = networkAgent.networkInfo;
9499 networkAgent.networkInfo = newInfo;
9500 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009501
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009502 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009503 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
9504 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009505 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009506
Chalard Jean254bd162022-08-25 13:04:51 +09009507 if (!networkAgent.isCreated()
Robin Leea8c0b6e2016-05-01 23:00:00 +01009508 && (state == NetworkInfo.State.CONNECTED
9509 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009510
9511 // A network that has just connected has zero requests and is thus a foreground network.
9512 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
9513
Luke Huangfdd11f82019-04-09 18:41:49 +08009514 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09009515 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009516 // Initialize the network's capabilities to their starting values according to the
9517 // underlying networks. This ensures that the capabilities are correct before
9518 // anything happens to the network.
9519 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09009520 }
Chalard Jean254bd162022-08-25 13:04:51 +09009521 networkAgent.setCreated();
Chiachang Wang3f6cc072021-03-24 18:39:17 +08009522 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +09009523 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +08009524 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009525 }
9526
Chalard Jean254bd162022-08-25 13:04:51 +09009527 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
9528 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009529
lucaslin45e639b2019-04-03 17:09:28 +08009530 // NetworkCapabilities need to be set before sending the private DNS config to
9531 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09009532 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
9533
Erik Kline9a62f012018-03-21 07:18:33 -07009534 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08009535 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
9536 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009537
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +01009538 // If a rate limit has been configured and is applicable to this network (network
9539 // provides internet connectivity), apply it. The tc police filter cannot be attached
9540 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
9541 // updateInterfaces -> INetd#networkAddInterface.
9542 // Note: in case of a system server crash, the NetworkController constructor in netd
9543 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
9544 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
9545 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
9546 mIngressRateLimit);
9547 }
9548
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009549 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
9550 // command must be sent after updating LinkProperties to maximize chances of
9551 // NetworkMonitor seeing the correct LinkProperties when starting.
9552 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009553 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09009554 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009555 }
Chalard Jeand4900722022-02-06 12:25:38 +09009556 final NetworkMonitorParameters params = new NetworkMonitorParameters();
9557 params.networkAgentConfig = networkAgent.networkAgentConfig;
9558 params.networkCapabilities = networkAgent.networkCapabilities;
9559 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
9560 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +09009561 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
9562 // newer callback even before T. However getInterfaceVersion is a synchronized binder
9563 // call that would cause a Log.wtf to be emitted from the system_server process, and
9564 // in the absence of a satisfactory, scalable solution which follows an easy/standard
9565 // process to check the interface version, just use an SDK check. NetworkStack will
9566 // always be new enough when running on T+.
9567 if (SdkLevel.isAtLeastT()) {
9568 networkAgent.networkMonitor().notifyNetworkConnected(params);
9569 } else {
9570 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
9571 params.networkCapabilities);
9572 }
Chalard Jeane63c42f2022-09-16 19:31:45 +09009573 final long delay = activelyPreferBadWifi()
9574 ? ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS
9575 : DONT_ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
9576 scheduleEvaluationTimeout(networkAgent.network, delay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009577
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009578 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
9579 // be communicated to a particular NetworkAgent depends only on the network's immutable,
9580 // capabilities, so it only needs to be done once on initial connect, not every time the
9581 // network's capabilities change. Note that we do this before rematching the network,
9582 // so we could decide to tear it down immediately afterwards. That's fine though - on
9583 // disconnection NetworkAgents should stop any signal strength monitoring they have been
9584 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09009585 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009586
junyulai0ac374f2020-12-14 18:41:52 +08009587 // Before first rematching networks, put an inactivity timer without any request, this
9588 // allows {@code updateInactivityState} to update the state accordingly and prevent
9589 // tearing down for any {@code unneeded} evaluation in this period.
9590 // Note that the timer will not be rescheduled since the expiry time is
9591 // fixed after connection regardless of the network satisfying other requests or not.
9592 // But it will be removed as soon as the network satisfies a request for the first time.
9593 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
9594 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08009595 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009596
Paul Jensen05e85ee2014-09-11 11:00:39 -04009597 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009598 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009599
9600 // This has to happen after matching the requests, because callbacks are just requests.
9601 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009602 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009603 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04009604 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009605 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04009606 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09009607 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00009608 if (networkAgent.isVPN()) {
9609 // As the active or bound network changes for apps, broadcast the default proxy, as
9610 // apps may need to update their proxy data. This is called after disconnecting from
9611 // VPN to make sure we do not broadcast the old proxy data.
9612 // TODO(b/122649188): send the broadcast only to VPN users.
9613 mProxyTracker.sendProxyBroadcast();
9614 }
Chalard Jean254bd162022-08-25 13:04:51 +09009615 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
9616 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009617 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009618 }
9619 }
9620
Chalard Jean28018572020-12-21 18:36:52 +09009621 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09009622 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
9623 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009624 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07009625 }
9626
Erik Kline99f301b2017-02-15 19:59:17 +09009627 // Notify only this one new request of the current state. Transfer all the
9628 // current state by calling NetworkCapabilities and LinkProperties callbacks
9629 // so that callers can be guaranteed to have as close to atomicity in state
9630 // transfer as can be supported by this current API.
9631 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07009632 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09009633 if (nri.mPendingIntent != null) {
9634 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
9635 // Attempt no subsequent state pushes where intents are involved.
9636 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009637 }
Erik Kline99f301b2017-02-15 19:59:17 +09009638
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009639 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08009640 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009641 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
9642 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
9643 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08009644 }
9645
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009646 // Notify the requests on this NAI that the network is now lingered.
9647 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08009648 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009649 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
9650 }
9651
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009652 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
9653 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
9654 return vpnBlocked
9655 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
9656 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
9657 }
9658
9659 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
9660 if (blockedReasons == BLOCKED_REASON_NONE) {
9661 mUidBlockedReasons.delete(uid);
9662 } else {
9663 mUidBlockedReasons.put(uid, blockedReasons);
9664 }
9665 }
9666
junyulaif2c67e42018-08-07 19:50:45 +08009667 /**
9668 * Notify of the blocked state apps with a registered callback matching a given NAI.
9669 *
9670 * Unlike other callbacks, blocked status is different between each individual uid. So for
9671 * any given nai, all requests need to be considered according to the uid who filed it.
9672 *
9673 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009674 * @param oldMetered True if the previous network capabilities were metered.
9675 * @param newMetered True if the current network capabilities are metered.
9676 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
9677 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08009678 */
9679 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00009680 boolean newMetered, List<UidRange> oldBlockedUidRanges,
9681 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08009682
9683 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9684 NetworkRequest nr = nai.requestAt(i);
9685 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009686
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009687 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9688 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9689 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009690 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009691 : oldVpnBlocked;
9692
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009693 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9694 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9695 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009696 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009697 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009698 }
9699 }
9700 }
9701
9702 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009703 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009704 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009705 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009706 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009707 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009708 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009709 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009710 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009711
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009712 final int oldBlockedState = getBlockedState(
9713 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9714 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9715 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009716 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009717 }
junyulaif2c67e42018-08-07 19:50:45 +08009718 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9719 NetworkRequest nr = nai.requestAt(i);
9720 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009721 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009722 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
9723 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009724 }
9725 }
9726 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009727 }
9728
Chalard Jean3a3f5f22019-04-10 23:07:55 +09009729 @VisibleForTesting
9730 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09009731 // The NetworkInfo we actually send out has no bearing on the real
9732 // state of affairs. For example, if the default connection is mobile,
9733 // and a request for HIPRI has just gone away, we need to pretend that
9734 // HIPRI has just disconnected. So we need to set the type to HIPRI and
9735 // the state to DISCONNECTED, even though the network is of type MOBILE
9736 // and is still connected.
9737 NetworkInfo info = new NetworkInfo(nai.networkInfo);
9738 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09009739 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009740 if (state != DetailedState.DISCONNECTED) {
9741 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09009742 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009743 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009744 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07009745 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
9746 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
9747 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
9748 if (info.isFailover()) {
9749 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
9750 nai.networkInfo.setFailover(false);
9751 }
9752 if (info.getReason() != null) {
9753 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
9754 }
9755 if (info.getExtraInfo() != null) {
9756 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
9757 }
9758 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09009759 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08009760 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07009761 if (newDefaultAgent != null) {
9762 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
9763 newDefaultAgent.networkInfo);
9764 } else {
9765 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
9766 }
9767 }
9768 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
9769 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09009770 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009771 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09009772 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009773 }
9774 }
9775 }
9776
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009777 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009778 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009779 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09009780 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09009781 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009782 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
9783 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009784 NetworkRequestInfo nri = mNetworkRequests.get(nr);
9785 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009786 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009787 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009788 } else {
9789 sendPendingIntentForRequest(nri, networkAgent, notifyType);
9790 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009791 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009792 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009793
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009794 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
9795 notifyNetworkCallbacks(networkAgent, notifyType, 0);
9796 }
9797
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009798 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09009799 * Returns the list of all interfaces that could be used by network traffic that does not
9800 * explicitly specify a network. This includes the default network, but also all VPNs that are
9801 * currently connected.
9802 *
9803 * Must be called on the handler thread.
9804 */
junyulaie7c7d2a2021-01-26 15:29:15 +08009805 @NonNull
9806 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009807 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08009808 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08009809 final Set<Integer> activeNetIds = new ArraySet<>();
9810 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9811 if (nri.isBeingSatisfied()) {
9812 activeNetIds.add(nri.getSatisfier().network().netId);
9813 }
9814 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009815 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +09009816 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09009817 defaultNetworks.add(nai.network);
9818 }
9819 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009820 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09009821 }
9822
9823 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09009824 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
9825 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009826 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08009827 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009828 ensureRunningOnConnectivityServiceThread();
9829 String activeIface = null;
9830 LinkProperties activeLinkProperties = getActiveLinkProperties();
9831 if (activeLinkProperties != null) {
9832 activeIface = activeLinkProperties.getInterfaceName();
9833 }
Benedict Wong9308cd32019-06-12 17:46:31 +00009834
junyulai2050bed2021-01-23 09:46:34 +08009835 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009836 try {
junyulaide41fc22021-01-22 22:46:01 +08009837 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +09009838 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +08009839 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
9840 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009841 } catch (Exception ignored) {
9842 }
9843 }
9844
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07009845 @Override
Udam Sainicd645462016-01-04 12:16:14 -08009846 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08009847 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009848 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009849 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009850
9851 if (!TextUtils.isEmpty(settingUrl)) {
9852 return settingUrl;
9853 }
9854
9855 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009856 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009857 if (!TextUtils.isEmpty(settingUrl)) {
9858 return settingUrl;
9859 }
9860
9861 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009862 }
9863
9864 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009865 public void startNattKeepalive(Network network, int intervalSeconds,
9866 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009867 enforceKeepalivePermission();
9868 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009869 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +00009870 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
9871 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +00009872 // false and set the underpinned network to null because there is no way and no
9873 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
9874 // deprecated method.
9875 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009876 }
9877
9878 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009879 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009880 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +00009881 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -07009882 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009883 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009884 mKeepaliveTracker.startNattKeepalive(
9885 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +00009886 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
9887 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -07009888 } finally {
9889 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9890 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009891 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9892 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009893 }
9894 }
junyulaid05a1922019-01-15 11:32:44 +08009895 }
9896
9897 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009898 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009899 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009900 try {
9901 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08009902 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009903 mKeepaliveTracker.startTcpKeepalive(
9904 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
9905 } finally {
9906 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9907 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009908 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9909 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009910 }
9911 }
junyulai0835a1e2019-01-08 20:04:33 +08009912 }
9913
9914 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +09009915 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009916 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +09009917 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
9918 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009919 }
9920
9921 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07009922 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08009923 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07009924
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009925 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08009926 final long token = Binder.clearCallingIdentity();
9927 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009928 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
9929 UserHandle.getUserHandleForUid(uid))) {
9930 return;
9931 }
9932
Heemin Seogdb8489d2019-06-12 09:21:44 -07009933 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
9934 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009935
9936 // Turn airplane mode off
9937 setAirplaneMode(false);
9938
9939 // restore private DNS settings to default mode (opportunistic)
9940 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
9941 UserHandle.getUserHandleForUid(uid))) {
9942 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
9943 PRIVATE_DNS_MODE_OPPORTUNISTIC);
9944 }
9945
9946 Settings.Global.putString(mContext.getContentResolver(),
9947 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08009948 } finally {
9949 Binder.restoreCallingIdentity(token);
9950 }
Stuart Scottd5463642015-04-02 18:00:02 -07009951 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04009952
Ricky Wai7097cc92018-01-23 04:09:45 +00009953 @Override
9954 public byte[] getNetworkWatchlistConfigHash() {
9955 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
9956 if (nwm == null) {
9957 loge("Unable to get NetworkWatchlistManager");
9958 return null;
9959 }
9960 // Redirect it to network watchlist service to access watchlist file and calculate hash.
9961 return nwm.getWatchlistConfigHash();
9962 }
9963
Hugo Benichibe0c7652016-05-31 16:28:06 +09009964 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09009965 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08009966 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09009967 }
Hugo Benichif4210292017-04-21 15:07:12 +09009968
9969 private static boolean toBool(int encodedBoolean) {
9970 return encodedBoolean != 0; // Only 0 means false.
9971 }
9972
9973 private static int encodeBool(boolean b) {
9974 return b ? 1 : 0;
9975 }
mswest4632928412018-03-12 10:34:34 -07009976
9977 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009978 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
9979 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
9980 @NonNull String[] args) {
9981 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
9982 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07009983 }
9984
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009985 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07009986 @Override
9987 public int onCommand(String cmd) {
9988 if (cmd == null) {
9989 return handleDefaultCommands(cmd);
9990 }
9991 final PrintWriter pw = getOutPrintWriter();
9992 try {
9993 switch (cmd) {
9994 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +09009995 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
9996 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -07009997 final String action = getNextArg();
9998 if ("enable".equals(action)) {
9999 setAirplaneMode(true);
10000 return 0;
10001 } else if ("disable".equals(action)) {
10002 setAirplaneMode(false);
10003 return 0;
10004 } else if (action == null) {
10005 final ContentResolver cr = mContext.getContentResolver();
10006 final int enabled = Settings.Global.getInt(cr,
10007 Settings.Global.AIRPLANE_MODE_ON);
10008 pw.println(enabled == 0 ? "disabled" : "enabled");
10009 return 0;
10010 } else {
10011 onHelp();
10012 return -1;
10013 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010014 case "reevaluate":
10015 // Usage : adb shell cmd connectivity reevaluate <netId>
10016 // If netId is omitted, then reevaluate the default network
10017 final String netId = getNextArg();
10018 final NetworkAgentInfo nai;
10019 if (null == netId) {
10020 // Note that the command is running on the wrong thread to call this,
10021 // so this could in principle return stale data. But it can't crash.
10022 nai = getDefaultNetwork();
10023 } else {
10024 // If netId can't be parsed, this throws NumberFormatException, which
10025 // is passed back to adb who prints it.
10026 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
10027 }
10028 if (null == nai) {
10029 pw.println("Unknown network (net ID not found or no default network)");
10030 return 0;
10031 }
10032 Log.d(TAG, "Reevaluating network " + nai.network);
10033 reportNetworkConnectivity(nai.network, !nai.isValidated());
10034 return 0;
mswest4632928412018-03-12 10:34:34 -070010035 default:
10036 return handleDefaultCommands(cmd);
10037 }
10038 } catch (Exception e) {
10039 pw.println(e);
10040 }
10041 return -1;
10042 }
10043
10044 @Override
10045 public void onHelp() {
10046 PrintWriter pw = getOutPrintWriter();
10047 pw.println("Connectivity service commands:");
10048 pw.println(" help");
10049 pw.println(" Print this help text.");
10050 pw.println(" airplane-mode [enable|disable]");
10051 pw.println(" Turn airplane mode on or off.");
10052 pw.println(" airplane-mode");
10053 pw.println(" Get airplane mode.");
10054 }
10055 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010056
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090010057 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010058 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
10059 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
10060 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080010061 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010062 }
10063
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090010064 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
10065 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090010066 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
10067 final TransportInfo newInfo = nc.getTransportInfo();
10068 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
10069 return;
10070 }
10071 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090010072 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090010073 }
10074 }
10075
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010076 /**
10077 * @param connectionInfo the connection to resolve.
10078 * @return {@code uid} if the connection is found and the app has permission to observe it
10079 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
10080 * connection is not found.
10081 */
10082 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010083 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
10084 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
10085 }
10086
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090010087 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010088 connectionInfo.local, connectionInfo.remote);
10089
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010090 if (uid == INVALID_UID) return uid; // Not found.
10091
10092 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
10093 // VPN, if any, that applies to the UID that owns the connection.
10094 if (checkNetworkStackPermission()) return uid;
10095
10096 final NetworkAgentInfo vpn = getVpnForUid(uid);
10097 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090010098 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010099 return INVALID_UID;
10100 }
10101
10102 return uid;
10103 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000010104
Benedict Wong493e04b2018-11-09 14:45:34 -080010105 /**
10106 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
10107 *
10108 * <p>The TestNetworkService must be run in the system server due to TUN creation.
10109 */
10110 @Override
10111 public IBinder startOrGetTestNetworkService() {
10112 synchronized (mTNSLock) {
10113 TestNetworkService.enforceTestNetworkPermissions(mContext);
10114
10115 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080010116 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080010117 }
10118
10119 return mTNS;
10120 }
10121 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080010122
Cody Kesting73708bf2019-12-18 10:57:50 -080010123 /**
10124 * Handler used for managing all Connectivity Diagnostics related functions.
10125 *
10126 * @see android.net.ConnectivityDiagnosticsManager
10127 *
10128 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
10129 */
10130 @VisibleForTesting
10131 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010132 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
10133
Cody Kesting73708bf2019-12-18 10:57:50 -080010134 /**
10135 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
10136 * android.net.ConnectivityDiagnosticsManager}.
10137 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
10138 * NetworkRequestInfo to be registered
10139 */
10140 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
10141
10142 /**
10143 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
10144 * android.net.ConnectivityDiagnosticsManager}.
10145 * obj = the IConnectivityDiagnosticsCallback to be unregistered
10146 * arg1 = the uid of the caller
10147 */
10148 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
10149
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010150 /**
10151 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010152 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010153 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
10154 * NetworkMonitor.
10155 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010156 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010157 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010158
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010159 /**
10160 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
10161 * been detected on the network.
10162 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
10163 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
10164 * arg2 = NetID.
10165 * data = PersistableBundle of extras passed from NetworkMonitor.
10166 */
10167 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
10168
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010169 /**
10170 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
10171 * the platform. This event will invoke {@link
10172 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
10173 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070010174 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010175 */
10176 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
10177
Cody Kesting73708bf2019-12-18 10:57:50 -080010178 private ConnectivityDiagnosticsHandler(Looper looper) {
10179 super(looper);
10180 }
10181
10182 @Override
10183 public void handleMessage(Message msg) {
10184 switch (msg.what) {
10185 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10186 handleRegisterConnectivityDiagnosticsCallback(
10187 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
10188 break;
10189 }
10190 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10191 handleUnregisterConnectivityDiagnosticsCallback(
10192 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
10193 break;
10194 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010195 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010196 final ConnectivityReportEvent reportEvent =
10197 (ConnectivityReportEvent) msg.obj;
10198
Aaron Huang959d3642021-01-21 15:47:41 +080010199 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010200 break;
10201 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010202 case EVENT_DATA_STALL_SUSPECTED: {
10203 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080010204 final Pair<Long, PersistableBundle> arg =
10205 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010206 if (nai == null) break;
10207
Aaron Huang959d3642021-01-21 15:47:41 +080010208 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010209 break;
10210 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010211 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070010212 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010213 break;
10214 }
10215 default: {
10216 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
10217 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010218 }
10219 }
10220 }
10221
10222 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
10223 @VisibleForTesting
10224 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
10225 @NonNull private final IConnectivityDiagnosticsCallback mCb;
10226 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010227 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010228
10229 @VisibleForTesting
10230 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010231 @NonNull IConnectivityDiagnosticsCallback cb,
10232 @NonNull NetworkRequestInfo nri,
10233 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010234 mCb = cb;
10235 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010236 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010237 }
10238
10239 @Override
10240 public void binderDied() {
10241 log("ConnectivityDiagnosticsCallback IBinder died.");
10242 unregisterConnectivityDiagnosticsCallback(mCb);
10243 }
10244 }
10245
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010246 /**
10247 * Class used for sending information from {@link
10248 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
10249 */
10250 private static class NetworkTestedResults {
10251 private final int mNetId;
10252 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010253 @Nullable private final String mRedirectUrl;
10254
10255 private NetworkTestedResults(
10256 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
10257 mNetId = netId;
10258 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010259 mRedirectUrl = redirectUrl;
10260 }
10261 }
10262
10263 /**
10264 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
10265 * ConnectivityDiagnosticsHandler}.
10266 */
10267 private static class ConnectivityReportEvent {
10268 private final long mTimestampMillis;
10269 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080010270 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010271
Aaron Huang959d3642021-01-21 15:47:41 +080010272 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
10273 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010274 mTimestampMillis = timestampMillis;
10275 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080010276 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010277 }
10278 }
10279
Cody Kestingf1120be2020-08-03 18:01:40 -070010280 /**
10281 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
10282 * ConnectivityDiagnosticsHandler}.
10283 */
10284 private static class ReportedNetworkConnectivityInfo {
10285 public final boolean hasConnectivity;
10286 public final boolean isNetworkRevalidating;
10287 public final int reporterUid;
10288 @NonNull public final NetworkAgentInfo nai;
10289
10290 private ReportedNetworkConnectivityInfo(
10291 boolean hasConnectivity,
10292 boolean isNetworkRevalidating,
10293 int reporterUid,
10294 @NonNull NetworkAgentInfo nai) {
10295 this.hasConnectivity = hasConnectivity;
10296 this.isNetworkRevalidating = isNetworkRevalidating;
10297 this.reporterUid = reporterUid;
10298 this.nai = nai;
10299 }
10300 }
10301
Cody Kesting73708bf2019-12-18 10:57:50 -080010302 private void handleRegisterConnectivityDiagnosticsCallback(
10303 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
10304 ensureRunningOnConnectivityServiceThread();
10305
10306 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080010307 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010308 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
10309
James Mattis64b8b0f2020-11-24 17:40:49 -080010310 // Connectivity Diagnostics are meant to be used with a single network request. It would be
10311 // confusing for these networks to change when an NRI is satisfied in another layer.
10312 if (nri.isMultilayerRequest()) {
10313 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
10314 + "network requests.");
10315 }
10316
Cody Kesting73708bf2019-12-18 10:57:50 -080010317 // This means that the client registered the same callback multiple times. Do
10318 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080010319 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010320 if (VDBG) log("Diagnostics callback is already registered");
10321
10322 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10323 // incremented when the NetworkRequestInfo is created as part of
10324 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010325 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080010326 return;
10327 }
10328
Cody Kesting31f1ff62020-03-05 10:46:02 -080010329 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080010330
10331 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080010332 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010333 } catch (RemoteException e) {
10334 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080010335 return;
10336 }
10337
10338 // Once registered, provide ConnectivityReports for matching Networks
10339 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
10340 synchronized (mNetworkForNetId) {
10341 for (int i = 0; i < mNetworkForNetId.size(); i++) {
10342 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080010343 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
10344 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080010345 matchingNetworks.add(nai);
10346 }
10347 }
10348 }
10349 for (final NetworkAgentInfo nai : matchingNetworks) {
10350 final ConnectivityReport report = nai.getConnectivityReport();
10351 if (report == null) {
10352 continue;
10353 }
10354 if (!checkConnectivityDiagnosticsPermissions(
10355 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10356 continue;
10357 }
10358
10359 try {
10360 cb.onConnectivityReportAvailable(report);
10361 } catch (RemoteException e) {
10362 // Exception while sending the ConnectivityReport. Move on to the next network.
10363 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010364 }
10365 }
10366
10367 private void handleUnregisterConnectivityDiagnosticsCallback(
10368 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
10369 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010370 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010371
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010372 final ConnectivityDiagnosticsCallbackInfo cbInfo =
10373 mConnectivityDiagnosticsCallbacks.remove(iCb);
10374 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010375 if (VDBG) log("Removing diagnostics callback that is not currently registered");
10376 return;
10377 }
10378
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010379 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080010380
Cody Kesting70fa2b22020-12-02 12:16:56 -080010381 // Caller's UID must either be the registrants (if they are unregistering) or the System's
10382 // (if the Binder died)
10383 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
10384 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080010385 return;
10386 }
10387
Cody Kesting46cb1672020-03-04 13:35:20 -080010388 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10389 // incremented when the NetworkRequestInfo is created as part of
10390 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010391 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080010392
Cody Kesting31f1ff62020-03-05 10:46:02 -080010393 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010394 }
10395
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010396 private void handleNetworkTestedWithExtras(
10397 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
10398 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080010399 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010400 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010401 final ConnectivityReport report =
10402 new ConnectivityReport(
10403 reportEvent.mNai.network,
10404 reportEvent.mTimestampMillis,
10405 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010406 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010407 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080010408 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070010409
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010410 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010411 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010412 for (final IConnectivityDiagnosticsCallback cb : results) {
10413 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080010414 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010415 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070010416 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010417 }
10418 }
10419 }
10420
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010421 private void handleDataStallSuspected(
10422 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
10423 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080010424 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010425 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010426 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080010427 new DataStallReport(
10428 nai.network,
10429 timestampMillis,
10430 detectionMethod,
10431 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010432 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080010433 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010434 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010435 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010436 for (final IConnectivityDiagnosticsCallback cb : results) {
10437 try {
10438 cb.onDataStallSuspected(report);
10439 } catch (RemoteException ex) {
10440 loge("Error invoking onDataStallSuspected", ex);
10441 }
10442 }
10443 }
10444
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010445 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070010446 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
10447 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
10448 final ConnectivityReport cachedReport = nai.getConnectivityReport();
10449
10450 // If the Network is being re-validated as a result of this call to
10451 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
10452 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010453 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010454 getMatchingPermissionedCallbacks(
10455 nai,
10456 reportedNetworkConnectivityInfo.isNetworkRevalidating
10457 ? Process.INVALID_UID
10458 : reportedNetworkConnectivityInfo.reporterUid);
10459
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010460 for (final IConnectivityDiagnosticsCallback cb : results) {
10461 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070010462 cb.onNetworkConnectivityReported(
10463 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010464 } catch (RemoteException ex) {
10465 loge("Error invoking onNetworkConnectivityReported", ex);
10466 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010467
10468 // If the Network isn't re-validating, also provide the cached report. If there is no
10469 // cached report, the Network is still being validated and a report will be sent once
10470 // validation is complete. Note that networks which never undergo validation will still
10471 // have a cached ConnectivityReport with RESULT_SKIPPED.
10472 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
10473 try {
10474 cb.onConnectivityReportAvailable(cachedReport);
10475 } catch (RemoteException ex) {
10476 loge("Error invoking onConnectivityReportAvailable", ex);
10477 }
10478 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010479 }
10480 }
10481
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010482 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090010483 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
10484 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010485 sanitized.setUids(null);
10486 sanitized.setAdministratorUids(new int[0]);
10487 sanitized.setOwnerUid(Process.INVALID_UID);
10488 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080010489 }
10490
Cody Kestingf1120be2020-08-03 18:01:40 -070010491 /**
10492 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
10493 *
10494 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
10495 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010496 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070010497 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010498 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010499 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010500 mConnectivityDiagnosticsCallbacks.entrySet()) {
10501 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
10502 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070010503
James Mattis64b8b0f2020-11-24 17:40:49 -080010504 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070010505 if (!nai.satisfies(nri.mRequests.get(0))) {
10506 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010507 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010508
10509 // UID for this callback must either be:
10510 // - INVALID_UID (which sends callbacks to all UIDs), or
10511 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
10512 // notified as a result)
10513 if (uid != Process.INVALID_UID && uid != nri.mUid) {
10514 continue;
10515 }
10516
10517 if (!checkConnectivityDiagnosticsPermissions(
10518 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10519 continue;
10520 }
10521
10522 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010523 }
10524 return results;
10525 }
10526
Cody Kesting7474f672021-05-11 14:22:40 -070010527 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
10528 @NonNull NetworkAgentInfo nai) {
10529 // TODO(b/188483916): replace with a transport-agnostic location-aware check
10530 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
10531 }
10532
Cody Kesting160ef392021-05-05 13:17:22 -070010533 private boolean hasLocationPermission(String packageName, int uid) {
10534 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
10535 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
10536 // call in a try-catch.
10537 try {
10538 if (!mLocationPermissionChecker.checkLocationPermission(
10539 packageName, null /* featureId */, uid, null /* message */)) {
10540 return false;
10541 }
10542 } catch (SecurityException e) {
10543 return false;
10544 }
10545
10546 return true;
10547 }
10548
10549 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
10550 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090010551 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070010552 && virtual.networkCapabilities.getOwnerUid() == uid
10553 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
10554 return true;
10555 }
10556 }
10557
10558 return false;
10559 }
10560
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010561 @VisibleForTesting
10562 boolean checkConnectivityDiagnosticsPermissions(
10563 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
10564 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
10565 return true;
10566 }
10567
Cody Kesting160ef392021-05-05 13:17:22 -070010568 // Administrator UIDs also contains the Owner UID
10569 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
10570 if (!CollectionUtils.contains(administratorUids, callbackUid)
10571 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010572 return false;
10573 }
10574
Cody Kesting7474f672021-05-11 14:22:40 -070010575 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
10576 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010577 }
10578
Cody Kestingd199a9d2019-12-17 12:55:28 -080010579 @Override
10580 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010581 @NonNull IConnectivityDiagnosticsCallback callback,
10582 @NonNull NetworkRequest request,
10583 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010584 Objects.requireNonNull(callback, "callback must not be null");
10585 Objects.requireNonNull(request, "request must not be null");
10586 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
10587
Cody Kesting73708bf2019-12-18 10:57:50 -080010588 if (request.legacyType != TYPE_NONE) {
10589 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
10590 + " Please use NetworkCapabilities instead.");
10591 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010592 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080010593 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010594
10595 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
10596 // and administrator uids to be safe.
10597 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080010598 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010599
10600 final NetworkRequest requestWithId =
10601 new NetworkRequest(
10602 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
10603
10604 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
10605 //
10606 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
10607 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
10608 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010609 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080010610 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010611 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010612
10613 mConnectivityDiagnosticsHandler.sendMessage(
10614 mConnectivityDiagnosticsHandler.obtainMessage(
10615 ConnectivityDiagnosticsHandler
10616 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
10617 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010618 }
10619
10620 @Override
10621 public void unregisterConnectivityDiagnosticsCallback(
10622 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010623 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080010624 mConnectivityDiagnosticsHandler.sendMessage(
10625 mConnectivityDiagnosticsHandler.obtainMessage(
10626 ConnectivityDiagnosticsHandler
10627 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010628 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080010629 0,
10630 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010631 }
Cody Kestingf53a0752020-04-15 12:33:28 -070010632
10633 @Override
10634 public void simulateDataStall(int detectionMethod, long timestampMillis,
10635 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010636 Objects.requireNonNull(network, "network must not be null");
10637 Objects.requireNonNull(extras, "extras must not be null");
10638
paulhu3ffffe72021-09-16 10:15:22 +080010639 enforceAnyPermissionOf(mContext,
10640 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070010641 android.Manifest.permission.NETWORK_STACK);
10642 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
10643 if (!nc.hasTransport(TRANSPORT_TEST)) {
Chalard Jean15228572022-01-28 19:29:12 +090010644 throw new SecurityException("Data Stall simulation is only possible for test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070010645 }
10646
10647 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010648 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -070010649 throw new SecurityException("Data Stall simulation is only possible for network "
10650 + "creators");
10651 }
10652
Cody Kesting652e3ec2020-05-21 12:08:21 -070010653 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
10654 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
10655 // Data Stall information as a DataStallReportParcelable and passing to
10656 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
10657 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070010658 final DataStallReportParcelable p = new DataStallReportParcelable();
10659 p.timestampMillis = timestampMillis;
10660 p.detectionMethod = detectionMethod;
10661
10662 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
10663 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
10664 }
10665 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
10666 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
10667 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
10668 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
10669 }
10670
Serik Beketayevec8ad212020-12-07 22:43:07 -080010671 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070010672 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010673
lucaslin66f44212021-02-23 01:12:55 +080010674 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
10675 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080010676 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080010677 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080010678 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080010679 }
lucaslin37a16d92021-01-21 19:48:09 +080010680
10681 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010682 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080010683 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010684 nai.clatd.interfaceLinkStateChanged(iface, up);
10685 }
10686 }
10687
10688 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010689 public void onInterfaceRemoved(@NonNull String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080010690 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010691 nai.clatd.interfaceRemoved(iface);
10692 }
lucaslin66f44212021-02-23 01:12:55 +080010693 }
10694 }
10695
lucaslin1a8b4c62021-01-21 02:02:55 +080010696 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
10697
10698 /**
10699 * Class used for updating network activity tracking with netd and notify network activity
10700 * changes.
10701 */
10702 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080010703 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080010704 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080010705 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080010706 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
10707 new RemoteCallbackList<>();
10708 // Indicate the current system default network activity is active or not.
10709 @GuardedBy("mActiveIdleTimers")
10710 private boolean mNetworkActive;
10711 @GuardedBy("mActiveIdleTimers")
Chalard Jean46bfbf02022-02-02 00:56:25 +090010712 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1193a5d2021-01-21 02:04:15 +080010713 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010714
Chalard Jean46bfbf02022-02-02 00:56:25 +090010715 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080010716 public final int timeout;
10717 public final int transportType;
10718
10719 IdleTimerParams(int timeout, int transport) {
10720 this.timeout = timeout;
10721 this.transportType = transport;
10722 }
10723 }
10724
10725 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080010726 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080010727 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080010728 mNetd = netd;
10729 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010730 }
10731
lucaslin66f44212021-02-23 01:12:55 +080010732 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
10733 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
10734 synchronized (mActiveIdleTimers) {
10735 mNetworkActive = active;
10736 // If there are no idle timers, it means that system is not monitoring
10737 // activity, so the system default network for those default network
10738 // unspecified apps is always considered active.
10739 //
10740 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
10741 // any network activity change event. Whenever this event is received,
10742 // the mActiveIdleTimers should be always not empty. The legacy behavior
10743 // is no-op. Remove to refer to mNetworkActive only.
10744 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
10745 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
10746 }
10747 }
10748 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010749
lucaslin1193a5d2021-01-21 02:04:15 +080010750 // The network activity should only be updated from ConnectivityService handler thread
10751 // when mActiveIdleTimers lock is held.
10752 @GuardedBy("mActiveIdleTimers")
10753 private void reportNetworkActive() {
10754 final int length = mNetworkActivityListeners.beginBroadcast();
10755 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
10756 try {
10757 for (int i = 0; i < length; i++) {
10758 try {
10759 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
10760 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010761 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080010762 }
10763 }
10764 } finally {
10765 mNetworkActivityListeners.finishBroadcast();
10766 }
10767 }
10768
10769 @GuardedBy("mActiveIdleTimers")
10770 public void handleReportNetworkActivity() {
10771 synchronized (mActiveIdleTimers) {
10772 reportNetworkActive();
10773 }
10774 }
10775
lucaslin1a8b4c62021-01-21 02:02:55 +080010776 // This is deprecated and only to support legacy use cases.
10777 private int transportTypeToLegacyType(int type) {
10778 switch (type) {
10779 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010780 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080010781 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010782 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080010783 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010784 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080010785 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010786 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080010787 default:
10788 loge("Unexpected transport in transportTypeToLegacyType: " + type);
10789 }
10790 return ConnectivityManager.TYPE_NONE;
10791 }
10792
10793 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
10794 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
10795 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
10796 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
10797 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
10798 final long ident = Binder.clearCallingIdentity();
10799 try {
10800 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
10801 RECEIVE_DATA_ACTIVITY_CHANGE,
10802 null /* resultReceiver */,
10803 null /* scheduler */,
10804 0 /* initialCode */,
10805 null /* initialData */,
10806 null /* initialExtra */);
10807 } finally {
10808 Binder.restoreCallingIdentity(ident);
10809 }
10810 }
10811
10812 /**
10813 * Setup data activity tracking for the given network.
10814 *
10815 * Every {@code setupDataActivityTracking} should be paired with a
10816 * {@link #removeDataActivityTracking} for cleanup.
10817 */
10818 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
10819 final String iface = networkAgent.linkProperties.getInterfaceName();
10820
10821 final int timeout;
10822 final int type;
10823
10824 if (networkAgent.networkCapabilities.hasTransport(
10825 NetworkCapabilities.TRANSPORT_CELLULAR)) {
10826 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010827 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080010828 10);
10829 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10830 } else if (networkAgent.networkCapabilities.hasTransport(
10831 NetworkCapabilities.TRANSPORT_WIFI)) {
10832 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010833 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080010834 15);
10835 type = NetworkCapabilities.TRANSPORT_WIFI;
10836 } else {
10837 return; // do not track any other networks
10838 }
10839
lucaslinb961efc2021-01-21 02:03:17 +080010840 updateRadioPowerState(true /* isActive */, type);
10841
lucaslin1a8b4c62021-01-21 02:02:55 +080010842 if (timeout > 0 && iface != null) {
10843 try {
lucaslin1193a5d2021-01-21 02:04:15 +080010844 synchronized (mActiveIdleTimers) {
10845 // Networks start up.
10846 mNetworkActive = true;
10847 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
10848 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
10849 reportNetworkActive();
10850 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010851 } catch (Exception e) {
10852 // You shall not crash!
10853 loge("Exception in setupDataActivityTracking " + e);
10854 }
10855 }
10856 }
10857
10858 /**
10859 * Remove data activity tracking when network disconnects.
10860 */
10861 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
10862 final String iface = networkAgent.linkProperties.getInterfaceName();
10863 final NetworkCapabilities caps = networkAgent.networkCapabilities;
10864
lucaslinb961efc2021-01-21 02:03:17 +080010865 if (iface == null) return;
10866
10867 final int type;
10868 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
10869 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10870 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
10871 type = NetworkCapabilities.TRANSPORT_WIFI;
10872 } else {
10873 return; // do not track any other networks
10874 }
10875
10876 try {
10877 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080010878 synchronized (mActiveIdleTimers) {
10879 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
10880 // The call fails silently if no idle timer setup for this interface
10881 mNetd.idletimerRemoveInterface(iface, params.timeout,
10882 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080010883 }
lucaslinb961efc2021-01-21 02:03:17 +080010884 } catch (Exception e) {
10885 // You shall not crash!
10886 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080010887 }
10888 }
10889
10890 /**
10891 * Update data activity tracking when network state is updated.
10892 */
10893 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
10894 NetworkAgentInfo oldNetwork) {
10895 if (newNetwork != null) {
10896 setupDataActivityTracking(newNetwork);
10897 }
10898 if (oldNetwork != null) {
10899 removeDataActivityTracking(oldNetwork);
10900 }
10901 }
lucaslinb961efc2021-01-21 02:03:17 +080010902
10903 private void updateRadioPowerState(boolean isActive, int transportType) {
10904 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
10905 switch (transportType) {
10906 case NetworkCapabilities.TRANSPORT_CELLULAR:
10907 bs.reportMobileRadioPowerState(isActive, NO_UID);
10908 break;
10909 case NetworkCapabilities.TRANSPORT_WIFI:
10910 bs.reportWifiRadioPowerState(isActive, NO_UID);
10911 break;
10912 default:
10913 logw("Untracked transport type:" + transportType);
10914 }
10915 }
lucaslin1193a5d2021-01-21 02:04:15 +080010916
10917 public boolean isDefaultNetworkActive() {
10918 synchronized (mActiveIdleTimers) {
10919 // If there are no idle timers, it means that system is not monitoring activity,
10920 // so the default network is always considered active.
10921 //
10922 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
10923 // tracking is disabled (negative idle timer value configured), or no active default
10924 // network. In the latter case, this reports active but it should report inactive.
10925 return mNetworkActive || mActiveIdleTimers.isEmpty();
10926 }
10927 }
10928
10929 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
10930 mNetworkActivityListeners.register(l);
10931 }
10932
10933 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
10934 mNetworkActivityListeners.unregister(l);
10935 }
lucaslin012f7a12021-01-21 02:04:35 +080010936
10937 public void dump(IndentingPrintWriter pw) {
10938 synchronized (mActiveIdleTimers) {
10939 pw.print("mNetworkActive="); pw.println(mNetworkActive);
10940 pw.println("Idle timers:");
10941 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
10942 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
10943 final IdleTimerParams params = ent.getValue();
10944 pw.print(" timeout="); pw.print(params.timeout);
10945 pw.print(" type="); pw.println(params.transportType);
10946 }
10947 }
10948 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010949 }
James Mattis47db0582021-01-01 14:13:35 -080010950
Daniel Brightf9e945b2020-06-15 16:10:01 -070010951 /**
10952 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
10953 *
10954 * @param socketInfo the socket information
10955 * @param callback the callback to register
10956 */
10957 @Override
10958 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
10959 @NonNull final IQosCallback callback) {
10960 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
10961 if (nai == null || nai.networkCapabilities == null) {
10962 try {
10963 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
10964 } catch (final RemoteException ex) {
10965 loge("registerQosCallbackInternal: RemoteException", ex);
10966 }
10967 return;
10968 }
10969 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
10970 }
10971
10972 /**
10973 * Register a {@link IQosCallback} with base {@link QosFilter}.
10974 *
10975 * @param filter the filter to register
10976 * @param callback the callback to register
10977 * @param nai the agent information related to the filter's network
10978 */
10979 @VisibleForTesting
10980 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
10981 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010982 Objects.requireNonNull(filter, "filter must be non-null");
10983 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010984
10985 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080010986 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
10987 // on this network is unregistered when the app loses permission or b) no QoS
10988 // callbacks are sent for restricted networks unless the app currently has permission
10989 // to access restricted networks.
10990 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070010991 }
10992 mQosCallbackTracker.registerCallback(callback, filter, nai);
10993 }
10994
10995 /**
10996 * Unregisters the given callback.
10997 *
10998 * @param callback the callback to unregister
10999 */
11000 @Override
11001 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011002 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011003 mQosCallbackTracker.unregisterCallback(callback);
11004 }
James Mattis47db0582021-01-01 14:13:35 -080011005
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011006 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
11007 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
11008 // Enterprise device can be fully managed like device owner and such use case
11009 // also should be supported. Calling app check for work profile and fully managed device
11010 // is already done in DevicePolicyManager.
11011 // This check is an extra caution to be sure device is fully managed or not.
11012 final UserManager um = mContext.getSystemService(UserManager.class);
11013 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
11014 if (um.isManagedProfile(profile.getIdentifier())) {
11015 return true;
11016 }
11017 if (SdkLevel.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
11018 return false;
11019 }
11020
James Mattis45d81842021-01-10 14:24:24 -080011021 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011022 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011023 *
11024 * See the documentation for the individual preferences for a description of the supported
11025 * behaviors.
11026 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011027 * @param profile If the device owner is set, any profile is allowed.
11028 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011029 * @param preferences the list of profile network preferences for the
11030 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011031 * @param listener an optional listener to listen for completion of the operation.
11032 */
11033 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011034 public void setProfileNetworkPreferences(
11035 @NonNull final UserHandle profile,
11036 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090011037 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011038 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011039 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011040
11041 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011042 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
11043 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
11044 .build();
11045 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011046 }
11047
paulhu3ffffe72021-09-16 10:15:22 +080011048 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011049 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011050 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011051 }
11052 if (profile.getIdentifier() < 0) {
11053 throw new IllegalArgumentException("Must explicitly specify a user handle ("
11054 + "UserHandle.CURRENT not supported)");
11055 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011056 if (!isNetworkPreferenceAllowedForProfile(profile)) {
11057 throw new IllegalArgumentException("Profile must be a managed profile "
11058 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011059 }
paulhuaa0743d2021-05-26 21:56:03 +080011060
Chalard Jean0606fc82022-12-14 20:34:43 +090011061 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011062 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011063 for (final ProfileNetworkPreference preference : preferences) {
11064 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011065 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080011066 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011067 switch (preference.getPreference()) {
11068 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
11069 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011070 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011071 if (preference.getPreferenceEnterpriseId() != 0) {
11072 throw new IllegalArgumentException(
11073 "Invalid enterprise identifier in setProfileNetworkPreferences");
11074 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011075 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080011076 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
11077 blockingNonEnterprise = true;
11078 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011079 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
11080 allowFallback = false;
11081 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011082 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011083 // This code is needed even though there is a check later on,
11084 // because isRangeAlreadyInPreferenceList assumes that every preference
11085 // has a UID list.
11086 if (hasDefaultPreference) {
11087 throw new IllegalArgumentException(
11088 "Default profile preference should not be set along with other "
11089 + "preference");
11090 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011091 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
11092 throw new IllegalArgumentException(
11093 "Invalid enterprise identifier in setProfileNetworkPreferences");
11094 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011095 final Set<UidRange> uidRangeSet =
11096 getUidListToBeAppliedForNetworkPreference(profile, preference);
11097 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
11098 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
11099 } else {
11100 throw new IllegalArgumentException(
11101 "Overlapping uid range in setProfileNetworkPreferences");
11102 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011103 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011104 nc.addEnterpriseId(
11105 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011106 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11107 break;
11108 default:
11109 throw new IllegalArgumentException(
11110 "Invalid preference in setProfileNetworkPreferences");
11111 }
Junyu Lai35665cc2022-12-19 17:37:48 +080011112 preferenceList.add(new ProfileNetworkPreferenceInfo(
11113 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011114 if (hasDefaultPreference && preferenceList.size() > 1) {
11115 throw new IllegalArgumentException(
11116 "Default profile preference should not be set along with other preference");
11117 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011118 }
11119 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011120 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011121 }
11122
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011123 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
11124 @NonNull final UserHandle profile,
11125 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
11126 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080011127 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
11128 profileNetworkPreference.getIncludedUids());
11129
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011130 if (uidRangeSet.size() > 0) {
11131 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
11132 throw new IllegalArgumentException(
11133 "Allow uid range is outside the uid range of profile.");
11134 }
11135 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080011136 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011137 profileNetworkPreference.getExcludedUids());
11138 if (disallowUidRangeSet.size() > 0) {
11139 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
11140 throw new IllegalArgumentException(
11141 "disallow uid range is outside the uid range of profile.");
11142 }
11143 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
11144 disallowUidRangeSet);
11145 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011146 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011147 uidRangeSet.add(profileUids);
11148 }
11149 }
11150 return uidRangeSet;
11151 }
11152
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011153 private boolean isEnterpriseIdentifierValid(
11154 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011155 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011156 return true;
11157 }
11158 return false;
11159 }
11160
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011161 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090011162 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011163 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090011164 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011165 // The NRI for a user should contain the request for capabilities.
11166 // If fallback to default network is needed then NRI should include
11167 // the request for the default network. Create an image of it to
11168 // have the correct UIDs in it (also a request can only be part of one NRI, because
11169 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011170 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
11171 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011172 if (pref.allowFallback) {
11173 nrs.add(createDefaultInternetRequestForTransport(
11174 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11175 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011176 if (VDBG) {
11177 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
11178 pref.capabilities.getUids()));
11179 }
11180
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011181 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080011182 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080011183 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011184 result.add(nri);
11185 }
11186 return result;
11187 }
11188
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011189 /**
11190 * Compare if the given UID range sets have the same UIDs.
11191 *
11192 */
11193 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090011194 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011195 @NonNull Set<UidRange> uidRangeSet) {
11196 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
11197 return false;
11198 }
Chalard Jean0606fc82022-12-14 20:34:43 +090011199 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011200 if (UidRangeUtils.doesRangeSetOverlap(
11201 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
11202 return true;
11203 }
11204 }
11205 return false;
11206 }
11207
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011208 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090011209 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011210 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011211 /*
11212 * handleSetProfileNetworkPreference is always called for single user.
11213 * preferenceList only contains preferences for different uids within the same user
11214 * (enforced by getUidListToBeAppliedForNetworkPreference).
11215 * Clear all the existing preferences for the user before applying new preferences.
11216 *
11217 */
Chalard Jean0606fc82022-12-14 20:34:43 +090011218 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
11219 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011220 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
11221 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011222
paulhu74128522021-09-28 02:29:03 +000011223 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
11224 addPerAppDefaultNetworkRequests(
11225 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080011226 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080011227
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011228 // Finally, rematch.
11229 rematchAllNetworksAndRequests();
11230
11231 if (null != listener) {
11232 try {
11233 listener.onComplete();
11234 } catch (RemoteException e) {
11235 loge("Listener for setProfileNetworkPreference has died");
11236 }
11237 }
11238 }
11239
paulhu51f77dc2021-06-07 02:34:20 +000011240 @VisibleForTesting
11241 @NonNull
11242 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
11243 @NonNull final Set<Integer> uids) {
11244 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11245 if (uids.size() == 0) {
11246 // Should not create NetworkRequestInfo if no preferences. Without uid range in
11247 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
11248 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
11249 return nris;
11250 }
11251
11252 final List<NetworkRequest> requests = new ArrayList<>();
11253 // The NRI should be comprised of two layers:
11254 // - The request for the mobile network preferred.
11255 // - The request for the default network, for fallback.
11256 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090011257 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000011258 requests.add(createDefaultInternetRequestForTransport(
11259 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11260 final Set<UidRange> ranges = new ArraySet<>();
11261 for (final int uid : uids) {
11262 ranges.add(new UidRange(uid, uid));
11263 }
11264 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080011265 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080011266 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000011267 return nris;
11268 }
11269
11270 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000011271 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000011272 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
11273 addPerAppDefaultNetworkRequests(
11274 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000011275 // Finally, rematch.
11276 rematchAllNetworksAndRequests();
11277 }
11278
Patrick Rohr2857ac42022-01-21 14:58:16 +010011279 private void handleIngressRateLimitChanged() {
11280 final long oldIngressRateLimit = mIngressRateLimit;
11281 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
11282 mContext);
11283 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
11284 if (canNetworkBeRateLimited(networkAgent)) {
11285 // If rate limit has previously been enabled, remove the old limit first.
11286 if (oldIngressRateLimit >= 0) {
11287 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
11288 }
11289 if (mIngressRateLimit >= 0) {
11290 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
11291 mIngressRateLimit);
11292 }
11293 }
11294 }
11295 }
11296
11297 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090011298 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
11299 if (!SdkLevel.isAtLeastT()) return false;
11300
Patrick Rohrff3b3f82022-02-09 15:15:52 +010011301 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
11302 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
11303 // internet connectivity can be rate limited.
11304 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
11305 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010011306 return false;
11307 }
11308
11309 final String iface = networkAgent.linkProperties.getInterfaceName();
11310 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010011311 // This may happen in tests, but if there is no interface then there is nothing that
11312 // can be rate limited.
11313 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010011314 return false;
11315 }
11316 return true;
11317 }
11318
James Mattis45d81842021-01-10 14:24:24 -080011319 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080011320 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
11321 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080011322 }
11323
11324 /**
11325 * Used by automotive devices to set the network preferences used to direct traffic at an
11326 * application level as per the given OemNetworkPreferences. An example use-case would be an
11327 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
11328 * vehicle via a particular network.
11329 *
11330 * Calling this will overwrite the existing preference.
11331 *
James Mattisda32cfe2021-01-26 16:23:52 -080011332 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090011333 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080011334 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080011335 */
James Mattis47db0582021-01-01 14:13:35 -080011336 @Override
James Mattis45d81842021-01-10 14:24:24 -080011337 public void setOemNetworkPreference(
11338 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011339 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080011340
James Mattisfa270db2021-05-31 17:11:10 -070011341 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11342 // Only bypass the permission/device checks if this is a valid test request.
11343 if (isValidTestOemNetworkPreference(preference)) {
11344 enforceManageTestNetworksPermission();
11345 } else {
11346 enforceAutomotiveDevice();
11347 enforceOemNetworkPreferencesPermission();
11348 validateOemNetworkPreferences(preference);
11349 }
James Mattis45d81842021-01-10 14:24:24 -080011350
James Mattis45d81842021-01-10 14:24:24 -080011351 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
11352 new Pair<>(preference, listener)));
11353 }
11354
James Mattisfa270db2021-05-31 17:11:10 -070011355 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000011356 * Sets the specified UIDs to get/receive the VPN as the only default network.
11357 *
11358 * Calling this will overwrite the existing network preference for this session, and the
11359 * specified UIDs won't get any default network when no VPN is connected.
11360 *
11361 * @param session The VPN session which manages the passed UIDs.
11362 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
11363 * setting for this session if the array is empty. Null is not allowed, the
11364 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
11365 * @hide
11366 */
11367 @Override
11368 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
11369 Objects.requireNonNull(ranges);
11370 enforceNetworkStackOrSettingsPermission();
11371 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
11372 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
11373 throw new IllegalArgumentException(
11374 "setVpnNetworkPreference: Passed UID ranges overlap");
11375 }
11376
11377 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
11378 new VpnNetworkPreferenceInfo(session,
11379 new ArraySet<UidRange>(Arrays.asList(ranges)))));
11380 }
11381
11382 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
11383 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
11384
11385 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
11386 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
11387
11388 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
11389 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
11390 // Finally, rematch.
11391 rematchAllNetworksAndRequests();
11392 }
11393
11394 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
11395 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
11396 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11397 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
11398 final List<NetworkRequest> requests = new ArrayList<>();
11399 // Request VPN only, so other networks won't be the fallback options when VPN is not
11400 // connected temporarily.
11401 requests.add(createVpnRequest());
11402 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
11403 setNetworkRequestUids(requests, uidRanges);
11404 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
11405 }
11406 return nris;
11407 }
11408
11409 /**
James Mattisfa270db2021-05-31 17:11:10 -070011410 * Check the validity of an OEM network preference to be used for testing purposes.
11411 * @param preference the preference to validate
11412 * @return true if this is a valid OEM network preference test request.
11413 */
11414 private boolean isValidTestOemNetworkPreference(
11415 @NonNull final OemNetworkPreferences preference) {
11416 // Allow for clearing of an existing OemNetworkPreference used for testing.
11417 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
11418 // changes after this check is complete. This is an unlikely scenario as calling of this API
11419 // is controlled by the OEM therefore the added complexity is not worth adding given those
11420 // circumstances. That said, it is an edge case to be aware of hence this comment.
11421 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
11422 && isTestOemNetworkPreference(mOemNetworkPreferences);
11423 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
11424 }
11425
11426 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
11427 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
11428 return prefMap.size() == 1
11429 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
11430 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
11431 }
11432
James Mattis45d81842021-01-10 14:24:24 -080011433 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
11434 for (@OemNetworkPreferences.OemNetworkPreference final int pref
11435 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070011436 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
11437 throw new IllegalArgumentException(
11438 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
11439 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080011440 }
11441 }
11442 }
11443
11444 private void handleSetOemNetworkPreference(
11445 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011446 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080011447 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11448 if (DBG) {
11449 log("set OEM network preferences :" + preference.toString());
11450 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011451
James Mattiscb1e0362021-04-06 17:07:42 -070011452 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000011453 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
11454 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
11455 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080011456 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080011457
11458 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011459 try {
11460 listener.onComplete();
11461 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080011462 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011463 }
James Mattis45d81842021-01-10 14:24:24 -080011464 }
11465 }
11466
paulhu74128522021-09-28 02:29:03 +000011467 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080011468 // Skip the requests which are set by other network preference. Because the uid range rules
11469 // should stay in netd.
11470 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080011471 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080011472 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080011473 }
11474
James Mattis3ce3d3c2021-02-09 18:18:28 -080011475 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
11476 ensureRunningOnConnectivityServiceThread();
11477 mDefaultNetworkRequests.addAll(nris);
11478 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
11479 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080011480 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000011481 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
11482 nrisToRegister.addAll(
11483 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
11484 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011485 }
11486
11487 /**
11488 * All current requests that are tracking the default network need to be assessed as to whether
11489 * or not the current set of per-application default requests will be changing their default
11490 * network. If so, those requests will need to be updated so that they will send callbacks for
11491 * default network changes at the appropriate time. Additionally, those requests tracking the
11492 * default that were previously updated by this flow will need to be reassessed.
11493 * @return the nris which will need to be updated.
11494 */
11495 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
11496 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
11497 // Get the distinct nris to check since for multilayer requests, it is possible to have the
11498 // same nri in the map's values for each of its NetworkRequest objects.
11499 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080011500 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011501 // Include this nri if it is currently being tracked.
11502 if (isPerAppTrackedNri(nri)) {
11503 defaultCallbackRequests.add(nri);
11504 continue;
11505 }
11506 // We only track callbacks for requests tracking the default.
11507 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
11508 continue;
11509 }
11510 // Include this nri if it will be tracked by the new per-app default requests.
11511 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011512 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080011513 if (isNriGoingToBeTracked) {
11514 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080011515 }
11516 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080011517 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080011518 }
11519
James Mattis3ce3d3c2021-02-09 18:18:28 -080011520 /**
11521 * Create nris for those network requests that are currently tracking the default network that
11522 * are being controlled by a per-application default.
11523 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
11524 * foundation when creating the nri. Important items include the calling uid's original
11525 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
11526 * requests are assumed to have already been validated as needing to be updated.
11527 * @return the Set of nris to use when registering network requests.
11528 */
11529 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
11530 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
11531 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
11532 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
11533 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011534 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011535
Chalard Jean9473c982021-07-29 20:03:04 +090011536 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080011537 if (trackingNri == mDefaultRequest) {
11538 callbackRequestsToRegister.add(new NetworkRequestInfo(
11539 callbackRequest,
11540 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
11541 continue;
11542 }
11543
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011544 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011545 callbackRequestsToRegister.add(new NetworkRequestInfo(
11546 callbackRequest,
11547 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011548 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090011549 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080011550 }
11551 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080011552 }
11553
Chalard Jean17215832021-03-01 14:06:28 +090011554 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
11555 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090011556 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011557 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090011558 }
11559 }
11560
James Mattis45d81842021-01-10 14:24:24 -080011561 /**
11562 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
11563 */
11564 @VisibleForTesting
11565 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011566 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080011567 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011568 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080011569 final SparseArray<Set<Integer>> uids =
11570 createUidsFromOemNetworkPreferences(preference);
11571 for (int i = 0; i < uids.size(); i++) {
11572 final int key = uids.keyAt(i);
11573 final Set<Integer> value = uids.valueAt(i);
11574 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
11575 // No need to add an nri without any requests.
11576 if (0 == nri.mRequests.size()) {
11577 continue;
11578 }
11579 nris.add(nri);
11580 }
11581
11582 return nris;
11583 }
11584
11585 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
11586 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070011587 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080011588 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080011589 final List<UserHandle> users =
11590 mContext.getSystemService(UserManager.class).getUserHandles(true);
11591 if (null == users || users.size() == 0) {
11592 if (VDBG || DDBG) {
11593 log("No users currently available for setting the OEM network preference.");
11594 }
James Mattisb6b6a432021-06-01 22:30:36 -070011595 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080011596 }
James Mattis45d81842021-01-10 14:24:24 -080011597 for (final Map.Entry<String, Integer> entry :
11598 preference.getNetworkPreferences().entrySet()) {
11599 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070011600 // Add the rules for all users as this policy is device wide.
11601 for (final UserHandle user : users) {
11602 try {
11603 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
11604 if (!prefToUids.contains(pref)) {
11605 prefToUids.put(pref, new ArraySet<>());
11606 }
11607 prefToUids.get(pref).add(uid);
11608 } catch (PackageManager.NameNotFoundException e) {
11609 // Although this may seem like an error scenario, it is ok that uninstalled
11610 // packages are sent on a network preference as the system will watch for
11611 // package installations associated with this network preference and update
11612 // accordingly. This is done to minimize race conditions on app install.
11613 continue;
James Mattis45d81842021-01-10 14:24:24 -080011614 }
James Mattis45d81842021-01-10 14:24:24 -080011615 }
11616 }
James Mattisb6b6a432021-06-01 22:30:36 -070011617 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080011618 }
11619
11620 private NetworkRequestInfo createNriFromOemNetworkPreferences(
11621 @OemNetworkPreferences.OemNetworkPreference final int preference,
11622 @NonNull final Set<Integer> uids) {
11623 final List<NetworkRequest> requests = new ArrayList<>();
11624 // Requests will ultimately be evaluated by order of insertion therefore it matters.
11625 switch (preference) {
11626 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
11627 requests.add(createUnmeteredNetworkRequest());
11628 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070011629 requests.add(createDefaultInternetRequestForTransport(
11630 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080011631 break;
11632 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
11633 requests.add(createUnmeteredNetworkRequest());
11634 requests.add(createOemPaidNetworkRequest());
11635 break;
11636 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
11637 requests.add(createOemPaidNetworkRequest());
11638 break;
11639 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
11640 requests.add(createOemPrivateNetworkRequest());
11641 break;
James Mattisfa270db2021-05-31 17:11:10 -070011642 case OEM_NETWORK_PREFERENCE_TEST:
11643 requests.add(createUnmeteredNetworkRequest());
11644 requests.add(createTestNetworkRequest());
11645 requests.add(createDefaultRequest());
11646 break;
11647 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
11648 requests.add(createTestNetworkRequest());
11649 break;
James Mattis45d81842021-01-10 14:24:24 -080011650 default:
11651 // This should never happen.
11652 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
11653 + " called with invalid preference of " + preference);
11654 }
11655
James Mattisfa270db2021-05-31 17:11:10 -070011656 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090011657 for (final int uid : uids) {
11658 ranges.add(new UidRange(uid, uid));
11659 }
11660 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080011661 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080011662 }
11663
11664 private NetworkRequest createUnmeteredNetworkRequest() {
11665 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11666 .addCapability(NET_CAPABILITY_NOT_METERED)
11667 .addCapability(NET_CAPABILITY_VALIDATED);
11668 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
11669 }
11670
11671 private NetworkRequest createOemPaidNetworkRequest() {
11672 // NET_CAPABILITY_OEM_PAID is a restricted capability.
11673 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11674 .addCapability(NET_CAPABILITY_OEM_PAID)
11675 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11676 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11677 }
11678
11679 private NetworkRequest createOemPrivateNetworkRequest() {
11680 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
11681 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11682 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
11683 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11684 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11685 }
11686
11687 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070011688 final NetworkCapabilities netcap = new NetworkCapabilities();
11689 netcap.addCapability(NET_CAPABILITY_INTERNET);
11690 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
11691 return netcap;
11692 }
11693
11694 private NetworkRequest createTestNetworkRequest() {
11695 final NetworkCapabilities netcap = new NetworkCapabilities();
11696 netcap.clearAll();
11697 netcap.addTransportType(TRANSPORT_TEST);
11698 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080011699 }
James Mattis47db0582021-01-01 14:13:35 -080011700 }
markchien738ad912021-12-09 18:15:45 +080011701
11702 @Override
11703 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
11704 enforceNetworkStackOrSettingsPermission();
11705
11706 try {
11707 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011708 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011709 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011710 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011711 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011712 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011713 throw new IllegalStateException(e);
11714 }
11715 }
11716
11717 @Override
11718 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
11719 enforceNetworkStackOrSettingsPermission();
11720
11721 try {
11722 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011723 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011724 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011725 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011726 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011727 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011728 throw new IllegalStateException(e);
11729 }
11730 }
markchiene1561fa2021-12-09 22:00:56 +080011731
11732 @Override
markchien3c04e662022-03-22 16:29:56 +080011733 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080011734 enforceNetworkStackOrSettingsPermission();
11735
markchien3c04e662022-03-22 16:29:56 +080011736 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
11737 int firewallRule = getFirewallRuleType(chain, rule);
11738
11739 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
11740 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
11741 }
11742
markchiene1561fa2021-12-09 22:00:56 +080011743 try {
markchien3c04e662022-03-22 16:29:56 +080011744 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011745 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080011746 throw new IllegalStateException(e);
11747 }
11748 }
markchien98a6f952022-01-13 23:43:53 +080011749
Motomu Utsumi900b8062023-01-19 16:16:49 +090011750 @Override
11751 public int getUidFirewallRule(final int chain, final int uid) {
11752 enforceNetworkStackOrSettingsPermission();
11753 return mBpfNetMaps.getUidRule(chain, uid);
11754 }
11755
markchien3c04e662022-03-22 16:29:56 +080011756 private int getFirewallRuleType(int chain, int rule) {
11757 final int defaultRule;
11758 switch (chain) {
11759 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000011760 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
11761 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000011762 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080011763 defaultRule = FIREWALL_RULE_ALLOW;
11764 break;
11765 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
11766 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
11767 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
11768 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
11769 defaultRule = FIREWALL_RULE_DENY;
11770 break;
11771 default:
11772 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
11773 }
11774 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
11775
11776 return rule;
11777 }
11778
markchien98a6f952022-01-13 23:43:53 +080011779 @Override
11780 public void setFirewallChainEnabled(final int chain, final boolean enable) {
11781 enforceNetworkStackOrSettingsPermission();
11782
11783 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011784 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011785 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080011786 throw new IllegalStateException(e);
11787 }
11788 }
11789
markchien00a0bed2022-01-13 23:46:13 +080011790 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011791 public boolean getFirewallChainEnabled(final int chain) {
11792 enforceNetworkStackOrSettingsPermission();
11793
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000011794 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011795 }
11796
11797 @Override
markchien00a0bed2022-01-13 23:46:13 +080011798 public void replaceFirewallChain(final int chain, final int[] uids) {
11799 enforceNetworkStackOrSettingsPermission();
11800
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000011801 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080011802 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080011803
11804 @Override
11805 public IBinder getCompanionDeviceManagerProxyService() {
11806 enforceNetworkStackPermission(mContext);
11807 return mCdmps;
11808 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070011809}