blob: e0d28f37cb1944d1a1a8de3d5c8f151c69a5c1c0 [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;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090037import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090038import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090039import static android.net.ConnectivityManager.TYPE_MOBILE;
40import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
41import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
42import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
43import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
44import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
45import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
46import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
47import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
48import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070049import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090050import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070051import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090052import static android.net.ConnectivityManager.TYPE_WIFI;
53import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070054import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070055import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080056import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080057import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080058import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070059import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080060import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen53f08952015-06-16 14:27:36 -040061import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090062import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090063import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090064import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090065import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090066import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
67import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060068import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090069import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080070import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090071import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080072import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
73import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080074import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090075import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Roshan Pius98f59ec2021-02-23 08:47:39 -080076import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
77import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
78import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090079import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090080import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060081import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070082import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080083import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090084import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070085import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
86import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +090087import static android.net.shared.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070088import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080089import static android.os.Process.VPN_UID;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +090090import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070091import static android.system.OsConstants.IPPROTO_TCP;
92import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey07e19362017-10-27 17:22:59 -060093
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +090094import static com.android.net.module.util.DeviceConfigUtils.TETHERING_MODULE_NAME;
95
Cody Kesting83bb5fa2020-01-05 14:06:39 -080096import static java.util.Map.Entry;
97
Chalard Jean5b639762020-03-09 21:25:37 +090098import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +000099import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800100import android.annotation.Nullable;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800101import android.annotation.TargetApi;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800102import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800103import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700104import android.app.PendingIntent;
junyulaie7c7d2a2021-01-26 15:29:15 +0800105import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700106import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800107import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800108import android.content.ContentResolver;
109import android.content.Context;
110import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700111import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800112import android.content.pm.PackageManager;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700113import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900114import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900115import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700116import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800117import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800118import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800119import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900120import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800121import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900122import android.net.ConnectivityManager.RestrictBackgroundStatus;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900123import android.net.ConnectivityResources;
paulhu90a7a512021-03-17 17:19:09 +0800124import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900125import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800126import android.net.DnsResolverServiceManager;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900127import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800128import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800129import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800130import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800131import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800132import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900133import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900134import android.net.INetworkMonitor;
135import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900136import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900137import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700138import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800139import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900140import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900141import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900142import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800143import android.net.LinkProperties;
Charles He9369e612017-05-15 17:07:18 +0100144import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800145import android.net.NativeNetworkConfig;
146import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800147import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700148import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700149import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900150import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700151import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800152import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700153import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900154import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900155import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000156import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900157import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700158import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900159import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700160import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900161import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700162import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800163import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900164import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700165import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000166import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800167import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900168import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800169import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400170import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700171import android.net.QosCallbackException;
172import android.net.QosFilter;
173import android.net.QosSocketFilter;
174import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700175import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800176import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800177import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800178import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900179import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400180import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800181import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800182import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400183import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800184import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900185import android.net.VpnTransportInfo;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900186import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900187import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800188import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900189import android.net.networkstack.ModuleNetworkStackClient;
190import android.net.networkstack.NetworkStackClientBase;
paulhu7c0a2e62021-01-08 00:51:49 +0800191import android.net.resolv.aidl.DnsHealthEventParcel;
192import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
193import android.net.resolv.aidl.Nat64PrefixEventParcel;
194import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900195import android.net.shared.PrivateDnsConfig;
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900196import android.net.util.MultinetworkPolicyTracker;
lucaslinb961efc2021-01-21 02:03:17 +0800197import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800198import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800199import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700200import android.os.Bundle;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800201import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700202import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700203import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800204import android.os.Looper;
205import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700206import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700207import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900208import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800209import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700210import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700211import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800212import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700213import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900214import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900215import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700216import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700217import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400218import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800219import android.provider.Settings;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900220import android.sysprop.NetworkProperties;
Wink Saville32506bc2013-06-29 21:10:57 -0700221import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700222import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800223import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900224import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000225import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600226import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900227import android.util.Pair;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700228import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700229import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800230
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900231import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400232import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400233import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700234import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900235import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800236import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900237import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800238import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900239import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900240import com.android.net.module.util.DeviceConfigUtils;
Chalard Jean79162542020-08-19 16:07:22 +0900241import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
242import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900243import com.android.net.module.util.LocationPermissionChecker;
lifrade6c2a2021-03-04 14:08:08 +0800244import com.android.net.module.util.NetworkCapabilitiesUtils;
paulhudf23d662021-01-25 18:53:17 +0800245import com.android.net.module.util.PermissionUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000246import com.android.net.module.util.netlink.InetDiagMessage;
Chalard Jean7284daa2019-05-30 14:58:29 +0900247import com.android.server.connectivity.AutodestructReference;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900248import com.android.server.connectivity.ConnectivityFlags;
Erik Kline32120082017-12-13 19:40:49 +0900249import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500250import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900251import com.android.server.connectivity.FullScore;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900252import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100253import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700254import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700255import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600256import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900257import com.android.server.connectivity.NetworkNotificationManager;
258import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900259import com.android.server.connectivity.NetworkOffer;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900260import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700261import com.android.server.connectivity.PermissionMonitor;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800262import com.android.server.connectivity.ProfileNetworkPreferenceList;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900263import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700264import com.android.server.connectivity.QosCallbackTracker;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600265
Josh Gao461a1222020-06-16 15:58:11 -0700266import libcore.io.IoUtils;
267
The Android Open Source Project28527d22009-03-03 19:31:44 -0800268import java.io.FileDescriptor;
269import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900270import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700271import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700272import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900273import java.net.InetSocketAddress;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700274import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700275import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700276import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700277import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800278import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900279import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800280import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700281import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700282import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700283import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700284import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900285import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700286import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900287import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600288import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900289import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600290import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900291import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800292
293/**
294 * @hide
295 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800296public class ConnectivityService extends IConnectivityManager.Stub
297 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900298 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800299
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900300 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900301 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900302 private static final String NETWORK_ARG = "networks";
303 private static final String REQUEST_ARG = "requests";
Erik Klined364a242017-05-12 16:52:48 +0900304
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900305 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900306 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
307 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800308
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900309 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700310
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100311 /**
312 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
313 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800314 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100315 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
316 * (preferably via runtime resource overlays).
317 */
318 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
319 "http://connectivitycheck.gstatic.com/generate_204";
320
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700321 // TODO: create better separation between radio types and network types
322
Robert Greenwalt2034b912009-08-12 16:08:25 -0700323 // how long to wait before switching back to a radio's default network
324 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
325 // system property that can override the above value
326 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
327 "android.telephony.apn-restore";
328
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900329 // How long to wait before putting up a "This network doesn't have an Internet connection,
330 // connect anyway?" dialog after the user selects a network that doesn't validate.
331 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
332
junyulai0ac374f2020-12-14 18:41:52 +0800333 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900334 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
335 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800336 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700337
338 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900339 @VisibleForTesting
340 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700341
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900342 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700343 @VisibleForTesting
344 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900345
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900346 @VisibleForTesting
347 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800348 @VisibleForTesting
349 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900350 // True if the cell radio of the device is capable of time-sharing.
351 @VisibleForTesting
352 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900353
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800354 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800355 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800356 private final int mReleasePendingIntentDelayMs;
357
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900358 private MockableSystemProperties mSystemProperties;
359
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000360 @VisibleForTesting
361 protected final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700362
Chalard Jean9473c982021-07-29 20:03:04 +0900363 @VisibleForTesting
364 final PerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700365 @VisibleForTesting
366 final PerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700367
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900368 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700369
junyulaif2c67e42018-08-07 19:50:45 +0800370 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000371 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
372 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800373 */
Sudheer Shanka9967d462021-03-18 19:09:25 +0000374 private SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800375
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900376 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900377 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000378 // The Context is created for UserHandle.ALL.
379 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900380 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900381 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700382 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700383 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800384
Chenbo Feng15416292018-11-08 17:36:21 -0800385 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800386 protected IDnsResolver mDnsResolver;
387 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800388 protected INetd mNetd;
junyulaie7c7d2a2021-01-26 15:29:15 +0800389 private NetworkStatsManager mStatsManager;
paulhu9a9f71b2020-12-29 18:15:13 +0800390 private NetworkPolicyManager mPolicyManager;
lucaslin66f44212021-02-23 01:12:55 +0800391 private final NetdCallback mNetdCallback;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700392
Benedict Wong493e04b2018-11-09 14:45:34 -0800393 /**
394 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
395 * instances.
396 */
397 @GuardedBy("mTNSLock")
398 private TestNetworkService mTNS;
399
400 private final Object mTNSLock = new Object();
401
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700402 private String mCurrentTcpBufferSizes;
403
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900404 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
lifraf3a3492021-03-10 13:58:14 +0800405 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900406
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500407 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400408 // Tear down networks that have no chance (e.g. even if validated) of becoming
409 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500410 // all networks have been rematched against all NetworkRequests.
411 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400412 // Don't reap networks. This should be passed when some networks have not yet been
413 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500414 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900415 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500416
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900417 private enum UnneededFor {
418 LINGER, // Determine whether this network is unneeded and should be lingered.
419 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
420 }
421
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700422 /**
paulhuaa0743d2021-05-26 21:56:03 +0800423 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800424 * should have priority. The order is passed to netd which will use it together
425 * with UID ranges to generate the corresponding IP rule. This serves to
426 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800427 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800428 * Order ints passed to netd must be in the 0~999 range. Larger values code for
paulhuaa0743d2021-05-26 21:56:03 +0800429 * a lower priority, {@see NativeUidRangeConfig}
paulhue9913722021-05-26 15:19:20 +0800430 *
paulhu48291862021-07-14 14:53:57 +0800431 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
432 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800433 */
paulhu48291862021-07-14 14:53:57 +0800434 // Bound for the lowest valid preference order.
435 static final int PREFERENCE_ORDER_LOWEST = 999;
436 // Used when sending to netd to code for "no order".
437 static final int PREFERENCE_ORDER_NONE = 0;
438 // Order for requests that don't code for a per-app preference. As it is
439 // out of the valid range, the corresponding order should be
440 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800441 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800442 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
443 // Order for the default internet request. Since this must always have the
paulhuaa0743d2021-05-26 21:56:03 +0800444 // lowest priority, its value is larger than the largest acceptable value. As
paulhu48291862021-07-14 14:53:57 +0800445 // it is out of the valid range, the corresponding order should be
446 // PREFERENCE_ORDER_NONE when sending to netd.
447 static final int PREFERENCE_ORDER_DEFAULT = 1000;
paulhuaa0743d2021-05-26 21:56:03 +0800448 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800449 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
450 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800451 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800452 static final int PREFERENCE_ORDER_OEM = 10;
453 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800454 // See {@link #setProfileNetworkPreference}.
455 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800456 static final int PREFERENCE_ORDER_PROFILE = 20;
457 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800458 // better scores are connected.
459 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800460 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800461 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
paulhue9913722021-05-26 15:19:20 +0800462
463 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700464 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700465 * from one net to another. Clear happens when we get a new
466 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
467 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700468 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700469 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700470
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700471 /**
472 * used internally to reload global proxy settings
473 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700474 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700475
Robert Greenwalt34848c02011-03-25 13:09:25 -0700476 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400477 * PAC manager has received new port.
478 */
479 private static final int EVENT_PROXY_HAS_CHANGED = 16;
480
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700481 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900482 * used internally when registering NetworkProviders
483 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700484 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900485 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700486
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700487 /**
488 * used internally when registering NetworkAgents
489 * obj = Messenger
490 */
491 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
492
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700493 /**
494 * used to add a network request
495 * includes a NetworkRequestInfo
496 */
497 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
498
499 /**
500 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900501 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700502 * cancel it.
503 * includes a NetworkRequestInfo
504 */
505 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
506
507 /**
508 * used to add a network listener - no request
509 * includes a NetworkRequestInfo
510 */
511 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
512
513 /**
514 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400515 * arg1 = UID of caller
516 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700517 */
518 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
519
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700520 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900521 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700522 * obj = Messenger
523 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900524 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700525
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700526 /**
527 * used internally to expire a wakelock when transitioning
528 * from one net to another. Expire happens when we fail to find
529 * a new network (typically after 1 minute) -
530 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
531 * a replacement network.
532 */
533 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
534
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700535 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800536 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400537 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800538 */
539 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
540
541 /**
542 * used to remove a pending intent and its associated network request.
543 * arg1 = UID of caller
544 * obj = PendingIntent
545 */
546 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
547
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900548 /**
549 * used to specify whether a network should be used even if unvalidated.
550 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
551 * arg2 = whether to remember this choice in the future (1 or 0)
552 * obj = network
553 */
554 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
555
556 /**
557 * used to ask the user to confirm a connection to an unvalidated network.
558 * obj = network
559 */
560 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700561
Erik Kline05f2b402015-04-30 12:58:40 +0900562 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700563 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900564 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700565 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900566
Paul Jensenc8873fc2015-06-17 14:15:39 -0400567 /**
568 * used to add a network listener with a pending intent
569 * obj = NetworkRequestInfo
570 */
571 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
572
Hugo Benichid6b510a2017-04-06 17:22:18 +0900573 /**
574 * used to specify whether a network should not be penalized when it becomes unvalidated.
575 */
576 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
577
578 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700579 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900580 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700581 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900582
Erik Kline31b4a9e2018-01-11 21:07:29 +0900583 // Handle changes in Private DNS settings.
584 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
585
dalyk1720e542018-03-05 12:42:22 -0500586 // Handle private DNS validation status updates.
587 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
588
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900589 /**
590 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
591 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800592 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
593 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
594 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900595 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900596 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900597
598 /**
599 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
600 * config was resolved.
601 * obj = PrivateDnsConfig
602 * arg2 = netid
603 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900604 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900605
606 /**
607 * Request ConnectivityService display provisioning notification.
608 * arg1 = Whether to make the notification visible.
609 * arg2 = NetID.
610 * obj = Intent to be launched when notification selected by user, null if !arg1.
611 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900612 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900613
614 /**
lucaslin2240ef62019-03-12 13:08:03 +0800615 * Used to specify whether a network should be used even if connectivity is partial.
616 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
617 * false)
618 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
619 * obj = network
620 */
lucaslin444d43a2020-02-20 16:56:59 +0800621 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800622
623 /**
lucasline117e2e2019-10-22 18:27:33 +0800624 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
625 * Both of the arguments are bitmasks, and the value of bits come from
626 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
627 * arg1 = A bitmask to describe which probes are completed.
628 * arg2 = A bitmask to describe which probes are successful.
629 */
lucaslin444d43a2020-02-20 16:56:59 +0800630 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800631
632 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900633 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
634 * arg1 = unused
635 * arg2 = netId
636 * obj = captive portal data
637 */
lucaslin444d43a2020-02-20 16:56:59 +0800638 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900639
640 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900641 * Used by setRequireVpnForUids.
642 * arg1 = whether the specified UID ranges are required to use a VPN.
643 * obj = Array of UidRange objects.
644 */
645 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
646
647 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900648 * Used internally when setting the default networks for OemNetworkPreferences.
649 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800650 */
651 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
652
653 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800654 * Used to indicate the system default network becomes active.
655 */
656 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
657
658 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900659 * Used internally when setting a network preference for a user profile.
660 * obj = Pair<ProfileNetworkPreference, Listener>
661 */
662 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
663
664 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000665 * Event to specify that reasons for why an uid is blocked changed.
666 * arg1 = uid
667 * arg2 = blockedReasons
668 */
669 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
670
671 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900672 * Event to register a new network offer
673 * obj = NetworkOffer
674 */
675 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
676
677 /**
678 * Event to unregister an existing network offer
679 * obj = INetworkOfferCallback
680 */
681 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
682
683 /**
paulhu51f77dc2021-06-07 02:34:20 +0000684 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
685 */
686 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
687
688 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800689 * Event to set temporary allow bad wifi within a limited time to override
690 * {@code config_networkAvoidBadWifi}.
691 */
692 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
693
694 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900695 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
696 * should be shown.
697 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900698 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900699
700 /**
701 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
702 * should be hidden.
703 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900704 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900705
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800706 /**
707 * The maximum alive time to allow bad wifi configuration for testing.
708 */
709 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
710
Hugo Benichi47011212017-03-30 10:46:05 +0900711 private static String eventName(int what) {
712 return sMagicDecoderRing.get(what, Integer.toString(what));
713 }
714
paulhua10d8212020-11-10 15:32:56 +0800715 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900716 final DnsResolverServiceManager dsm = context.getSystemService(
717 DnsResolverServiceManager.class);
718 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800719 }
720
Cody Kesting73708bf2019-12-18 10:57:50 -0800721 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900722 @VisibleForTesting
723 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700724 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700725 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700726 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700727 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800728 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
729 @VisibleForTesting
730 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
731
Erik Kline32120082017-12-13 19:40:49 +0900732 private final DnsManager mDnsManager;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900733 private final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700734
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400735 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800736 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400737
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700738 private PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800739 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700740
Chalard Jean5d70ba42018-06-07 16:44:04 +0900741 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
742 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000743 @VisibleForTesting
744 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400745
Erik Kline05f2b402015-04-30 12:58:40 +0900746 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700747
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400748 private UserManager mUserManager;
749
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700750 // the set of network types that can only be enabled by system/sig apps
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900751 private List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700752
Valentin Iftime9fa35092019-09-24 13:32:13 +0200753 private Set<String> mWolSupportedInterfaces;
754
Roshan Pius08c94fb2020-01-16 12:17:17 -0800755 private final TelephonyManager mTelephonyManager;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800756 private final AppOpsManager mAppOpsManager;
757
758 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400759
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900760 private KeepaliveTracker mKeepaliveTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700761 private QosCallbackTracker mQosCallbackTracker;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900762 private NetworkNotificationManager mNotifier;
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +0900763 private LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900764
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700765 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800766 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700767
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900768 // Sequence number for NetworkProvider IDs.
769 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
770 NetworkProvider.FIRST_PROVIDER_ID);
771
Erik Klineedf878b2015-07-09 18:24:03 +0900772 // NetworkRequest activity String log entries.
773 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
774 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
775
Hugo Benichid159fdd2016-07-11 11:05:12 +0900776 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900777 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900778 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
779
Hugo Benichi47011212017-03-30 10:46:05 +0900780 private static final int MAX_WAKELOCK_LOGS = 20;
781 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900782 private int mTotalWakelockAcquisitions = 0;
783 private int mTotalWakelockReleases = 0;
784 private long mTotalWakelockDurationMs = 0;
785 private long mMaxWakelockDurationMs = 0;
786 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900787
Hugo Benichi208c0102016-07-28 17:53:06 +0900788 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900789
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700790 @GuardedBy("mBandwidthRequests")
791 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
792
Erik Kline95ecfee2016-10-02 18:02:14 +0900793 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900794 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900795
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900796 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800797 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
798 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800799
Robert Greenwalt802c1102014-06-02 15:32:02 -0700800 /**
801 * Implements support for the legacy "one network per network type" model.
802 *
803 * We used to have a static array of NetworkStateTrackers, one for each
804 * network type, but that doesn't work any more now that we can have,
805 * for example, more that one wifi network. This class stores all the
806 * NetworkAgentInfo objects that support a given type, but the legacy
807 * API will only see the first one.
808 *
809 * It serves two main purposes:
810 *
811 * 1. Provide information about "the network for a given type" (since this
812 * API only supports one).
813 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
814 * the first network for a given type changes, or if the default network
815 * changes.
816 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900817 @VisibleForTesting
818 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900819
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900820 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900821 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900822
Robert Greenwalt802c1102014-06-02 15:32:02 -0700823 /**
824 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
825 * Each list holds references to all NetworkAgentInfos that are used to
826 * satisfy requests for that network type.
827 *
828 * This array is built out at startup such that an unsupported network
829 * doesn't get an ArrayList instance, making this a tristate:
830 * unsupported, supported but not active and active.
831 *
832 * The actual lists are populated when we scan the network types that
833 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900834 *
835 * Threading model:
836 * - addSupportedType() is only called in the constructor
837 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
838 * They are therefore not thread-safe with respect to each other.
839 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
840 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900841 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900842 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700843 */
Hugo Benichi389633f2016-06-21 09:48:07 +0900844 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900845 @NonNull
846 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700847
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900848 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
849 // an entry have no timer (equivalent to -1). Lazily loaded.
850 @NonNull
851 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
852
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900853 LegacyTypeTracker(@NonNull ConnectivityService service) {
854 mService = service;
855 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700856 }
857
Chiachang Wang3bc52762021-11-25 14:17:57 +0800858 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
859 // addressed.
860 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900861 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
862 final PackageManager pm = ctx.getPackageManager();
863 if (pm.hasSystemFeature(FEATURE_WIFI)) {
864 addSupportedType(TYPE_WIFI);
865 }
866 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
867 addSupportedType(TYPE_WIFI_P2P);
868 }
869 if (tm.isDataCapable()) {
870 // Telephony does not have granular support for these types: they are either all
871 // supported, or none is supported
872 addSupportedType(TYPE_MOBILE);
873 addSupportedType(TYPE_MOBILE_MMS);
874 addSupportedType(TYPE_MOBILE_SUPL);
875 addSupportedType(TYPE_MOBILE_DUN);
876 addSupportedType(TYPE_MOBILE_HIPRI);
877 addSupportedType(TYPE_MOBILE_FOTA);
878 addSupportedType(TYPE_MOBILE_IMS);
879 addSupportedType(TYPE_MOBILE_CBS);
880 addSupportedType(TYPE_MOBILE_IA);
881 addSupportedType(TYPE_MOBILE_EMERGENCY);
882 }
883 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
884 addSupportedType(TYPE_BLUETOOTH);
885 }
886 if (pm.hasSystemFeature(FEATURE_WATCH)) {
887 // TYPE_PROXY is only used on Wear
888 addSupportedType(TYPE_PROXY);
889 }
890 // Ethernet is often not specified in the configs, although many devices can use it via
891 // USB host adapters. Add it as long as the ethernet service is here.
892 if (ctx.getSystemService(Context.ETHERNET_SERVICE) != null) {
893 addSupportedType(TYPE_ETHERNET);
894 }
895
896 // Always add TYPE_VPN as a supported type
897 addSupportedType(TYPE_VPN);
898 }
899
900 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700901 if (mTypeLists[type] != null) {
902 throw new IllegalStateException(
903 "legacy list for type " + type + "already initialized");
904 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900905 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -0700906 }
907
Robert Greenwalt802c1102014-06-02 15:32:02 -0700908 public boolean isTypeSupported(int type) {
909 return isNetworkTypeValid(type) && mTypeLists[type] != null;
910 }
911
912 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +0900913 synchronized (mTypeLists) {
914 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
915 return mTypeLists[type].get(0);
916 }
Robert Greenwalt802c1102014-06-02 15:32:02 -0700917 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900918 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700919 }
920
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900921 public int getRestoreTimerForType(int type) {
922 synchronized (mTypeLists) {
923 if (mRestoreTimers == null) {
924 mRestoreTimers = loadRestoreTimers();
925 }
926 return mRestoreTimers.getOrDefault(type, -1);
927 }
928 }
929
930 private ArrayMap<Integer, Integer> loadRestoreTimers() {
931 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900932 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900933 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
934 for (final String config : configs) {
935 final String[] splits = TextUtils.split(config, ",");
936 if (splits.length != 2) {
937 logwtf("Invalid restore timer token count: " + config);
938 continue;
939 }
940 try {
941 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
942 } catch (NumberFormatException e) {
943 logwtf("Invalid restore timer number format: " + config, e);
944 }
945 }
946 return ret;
947 }
948
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -0700949 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +0900950 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900951 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +0900952 log("Sending " + state
953 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +0900954 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900955 }
956 }
957
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900958 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
959 // network type, to preserve previous behaviour.
960 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
961 if (vpnNai != mService.getLegacyLockdownNai()) return;
962
963 if (vpnNai.declaredUnderlyingNetworks == null
964 || vpnNai.declaredUnderlyingNetworks.length != 1) {
965 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
966 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
967 return;
968 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +0900969 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900970 vpnNai.declaredUnderlyingNetworks[0]);
971 if (underlyingNai == null) return;
972
973 final int type = underlyingNai.networkInfo.getType();
974 final DetailedState state = DetailedState.CONNECTED;
975 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
976 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
977 }
978
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900979 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -0700980 public void add(int type, NetworkAgentInfo nai) {
981 if (!isTypeSupported(type)) {
982 return; // Invalid network type.
983 }
984 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
985
986 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
987 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700988 return;
989 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900990 synchronized (mTypeLists) {
991 list.add(nai);
992 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +0900993
Chalard Jean5b409c72021-02-04 13:12:59 +0900994 // Send a broadcast if this is the first network of its type or if it's the default.
995 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900996
997 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
998 // to preserve previous behaviour.
999 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001000 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001001 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1002 mService.sendLegacyNetworkBroadcast(nai, state, type);
1003 }
1004
1005 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1006 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001007 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001008 }
1009
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001010 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001011 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001012 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1013 if (list == null || list.isEmpty()) {
1014 return;
1015 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001016 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001017
Hugo Benichi389633f2016-06-21 09:48:07 +09001018 synchronized (mTypeLists) {
1019 if (!list.remove(nai)) {
1020 return;
1021 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001022 }
1023
Lorenzo Colitti49767722015-05-01 00:30:10 +09001024 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001025 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1026 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001027 }
1028
1029 if (!list.isEmpty() && wasFirstNetwork) {
1030 if (DBG) log("Other network available for type " + type +
1031 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001032 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001033 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001034 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001035 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001036 }
1037 }
1038
1039 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001040 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1041 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001042 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001043 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001044 }
1045 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001046
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001047 // send out another legacy broadcast - currently only used for suspend/unsuspend
1048 // toggle
1049 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001050 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001051 final DetailedState state = nai.networkInfo.getDetailedState();
1052 for (int type = 0; type < mTypeLists.length; type++) {
1053 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001054 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001055 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001056 if (isFirst || contains && isDefault) {
1057 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001058 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001059 }
1060 }
1061 }
1062
Robert Greenwalt94e22142014-07-30 16:31:24 -07001063 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001064 pw.println("mLegacyTypeTracker:");
1065 pw.increaseIndent();
1066 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001067 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001068 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001069 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001070 pw.println();
1071 pw.println("Current state:");
1072 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001073 synchronized (mTypeLists) {
1074 for (int type = 0; type < mTypeLists.length; type++) {
1075 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1076 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001077 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001078 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001079 }
1080 }
1081 pw.decreaseIndent();
1082 pw.decreaseIndent();
1083 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001084 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001085 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001086 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001087
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001088 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001089 /**
1090 * Helper class which parses out priority arguments and dumps sections according to their
1091 * priority. If priority arguments are omitted, function calls the legacy dump command.
1092 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001093 private class LocalPriorityDump {
1094 private static final String PRIORITY_ARG = "--dump-priority";
1095 private static final String PRIORITY_ARG_HIGH = "HIGH";
1096 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1097
1098 LocalPriorityDump() {}
1099
1100 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1101 doDump(fd, pw, new String[] {DIAG_ARG});
1102 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001103 }
1104
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001105 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1106 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001107 }
1108
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001109 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1110 if (args == null) {
1111 dumpNormal(fd, pw, args);
1112 return;
1113 }
1114
1115 String priority = null;
1116 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1117 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1118 argIndex++;
1119 priority = args[argIndex];
1120 }
1121 }
1122
1123 if (PRIORITY_ARG_HIGH.equals(priority)) {
1124 dumpHigh(fd, pw);
1125 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1126 dumpNormal(fd, pw, args);
1127 } else {
1128 // ConnectivityService publishes binder service using publishBinderService() with
1129 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001130 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1131 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001132 // TODO: Integrate into signal dump.
1133 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001134 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001135 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001136 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001137
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001138 /**
Daniel Brightf9e945b2020-06-15 16:10:01 -07001139 * Keeps track of the number of requests made under different uids.
1140 */
1141 public static class PerUidCounter {
1142 private final int mMaxCountPerUid;
1143
1144 // Map from UID to number of NetworkRequests that UID has filed.
James Mattis20a4a8b2021-03-28 17:41:09 -07001145 @VisibleForTesting
Daniel Brightf9e945b2020-06-15 16:10:01 -07001146 @GuardedBy("mUidToNetworkRequestCount")
James Mattis20a4a8b2021-03-28 17:41:09 -07001147 final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
Daniel Brightf9e945b2020-06-15 16:10:01 -07001148
1149 /**
1150 * Constructor
1151 *
1152 * @param maxCountPerUid the maximum count per uid allowed
1153 */
1154 public PerUidCounter(final int maxCountPerUid) {
1155 mMaxCountPerUid = maxCountPerUid;
1156 }
1157
1158 /**
1159 * Increments the request count of the given uid. Throws an exception if the number
1160 * of open requests for the uid exceeds the value of maxCounterPerUid which is the value
1161 * passed into the constructor. see: {@link #PerUidCounter(int)}.
1162 *
1163 * @throws ServiceSpecificException with
1164 * {@link ConnectivityManager.Errors.TOO_MANY_REQUESTS} if the number of requests for
1165 * the uid exceed the allowed number.
1166 *
1167 * @param uid the uid that the request was made under
1168 */
1169 public void incrementCountOrThrow(final int uid) {
1170 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001171 incrementCountOrThrow(uid, 1 /* numToIncrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001172 }
1173 }
1174
James Mattis20a4a8b2021-03-28 17:41:09 -07001175 private void incrementCountOrThrow(final int uid, final int numToIncrement) {
1176 final int newRequestCount =
1177 mUidToNetworkRequestCount.get(uid, 0) + numToIncrement;
Chalard Jean9473c982021-07-29 20:03:04 +09001178 if (newRequestCount >= mMaxCountPerUid
1179 // HACK : the system server is allowed to go over the request count limit
1180 // when it is creating requests on behalf of another app (but not itself,
1181 // so it can still detect its own request leaks). This only happens in the
1182 // per-app API flows in which case the old requests for that particular
1183 // UID will be removed soon.
1184 // TODO : instead of this hack, addPerAppDefaultNetworkRequests and other
1185 // users of transact() should unregister the requests to decrease the count
1186 // before they increase it again by creating a new NRI. Then remove the
1187 // transact() method.
1188 && (Process.myUid() == uid || Process.myUid() != Binder.getCallingUid())) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001189 throw new ServiceSpecificException(
Chalard Jean9473c982021-07-29 20:03:04 +09001190 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
1191 "Uid " + uid + " exceeded its allotted requests limit");
James Mattis20a4a8b2021-03-28 17:41:09 -07001192 }
1193 mUidToNetworkRequestCount.put(uid, newRequestCount);
1194 }
1195
Daniel Brightf9e945b2020-06-15 16:10:01 -07001196 /**
1197 * Decrements the request count of the given uid.
1198 *
1199 * @param uid the uid that the request was made under
1200 */
1201 public void decrementCount(final int uid) {
1202 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001203 decrementCount(uid, 1 /* numToDecrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001204 }
1205 }
James Mattis20a4a8b2021-03-28 17:41:09 -07001206
1207 private void decrementCount(final int uid, final int numToDecrement) {
1208 final int newRequestCount =
1209 mUidToNetworkRequestCount.get(uid, 0) - numToDecrement;
1210 if (newRequestCount < 0) {
1211 logwtf("BUG: too small request count " + newRequestCount + " for UID " + uid);
1212 } else if (newRequestCount == 0) {
1213 mUidToNetworkRequestCount.delete(uid);
1214 } else {
1215 mUidToNetworkRequestCount.put(uid, newRequestCount);
1216 }
1217 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07001218 }
1219
1220 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001221 * Dependencies of ConnectivityService, for injection in tests.
1222 */
1223 @VisibleForTesting
1224 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001225 public int getCallingUid() {
1226 return Binder.getCallingUid();
1227 }
1228
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001229 /**
1230 * Get system properties to use in ConnectivityService.
1231 */
1232 public MockableSystemProperties getSystemProperties() {
1233 return new MockableSystemProperties();
1234 }
1235
1236 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001237 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1238 */
1239 public ConnectivityResources getResources(@NonNull Context ctx) {
1240 return new ConnectivityResources(ctx);
1241 }
1242
1243 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001244 * Create a HandlerThread to use in ConnectivityService.
1245 */
1246 public HandlerThread makeHandlerThread() {
1247 return new HandlerThread("ConnectivityServiceThread");
1248 }
1249
1250 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001251 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001252 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001253 public NetworkStackClientBase getNetworkStack() {
1254 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001255 }
1256
1257 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001258 * @see ProxyTracker
1259 */
1260 public ProxyTracker makeProxyTracker(@NonNull Context context,
1261 @NonNull Handler connServiceHandler) {
1262 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1263 }
1264
1265 /**
1266 * @see NetIdManager
1267 */
1268 public NetIdManager makeNetIdManager() {
1269 return new NetIdManager();
1270 }
1271
1272 /**
1273 * @see NetworkUtils#queryUserAccess(int, int)
1274 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001275 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1276 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001277 }
1278
1279 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001280 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1281 * requires CAP_NET_ADMIN, which the unit tests do not have.
1282 */
1283 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1284 InetSocketAddress remote) {
1285 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1286 }
1287
1288 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001289 * @see MultinetworkPolicyTracker
1290 */
1291 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1292 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1293 return new MultinetworkPolicyTracker(c, h, r);
1294 }
1295
Aaron Huang330a4c02020-10-27 03:36:19 +08001296 /**
1297 * @see BatteryStatsManager
1298 */
1299 public void reportNetworkInterfaceForTransports(Context context, String iface,
1300 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001301 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001302 context.getSystemService(BatteryStatsManager.class);
1303 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1304 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001305
1306 public boolean getCellular464XlatEnabled() {
1307 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1308 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001309
1310 /**
1311 * @see PendingIntent#intentFilterEquals
1312 */
1313 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1314 return a.intentFilterEquals(b);
1315 }
1316
1317 /**
1318 * @see LocationPermissionChecker
1319 */
1320 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1321 return new LocationPermissionChecker(context);
1322 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001323
1324 /**
1325 * @see DeviceConfigUtils#isFeatureEnabled
1326 */
1327 public boolean isFeatureEnabled(Context context, String name, boolean defaultEnabled) {
1328 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, name,
1329 TETHERING_MODULE_NAME, defaultEnabled);
1330 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001331 }
1332
junyulaie7c7d2a2021-01-26 15:29:15 +08001333 public ConnectivityService(Context context) {
1334 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001335 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1336 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001337 }
1338
1339 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001340 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1341 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001342 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001343
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001344 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001345 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001346 mSystemProperties = mDeps.getSystemProperties();
1347 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001348 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001349 mResources = deps.getResources(mContext);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001350 mNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_UID);
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09001351 mSystemNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001352
Hugo Benichi208c0102016-07-28 17:53:06 +09001353 mMetricsLog = logger;
Chalard Jean96a4f4b2019-12-10 22:16:53 +09001354 mNetworkRanker = new NetworkRanker();
James Mattis45d81842021-01-10 14:24:24 -08001355 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1356 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001357 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001358 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001359 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001360 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1361 mDefaultNetworkRequests.add(mDefaultRequest);
1362 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001363
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001364 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001365 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001366
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001367 // The default WiFi request is a background request so that apps using WiFi are
1368 // migrated to a better network (typically ethernet) when one comes up, instead
1369 // of staying on WiFi forever.
1370 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1371 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1372
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001373 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1374 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1375 NetworkRequest.Type.BACKGROUND_REQUEST);
1376
Chalard Jean0702f982021-09-16 21:50:07 +09001377 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1378 // TODO: Consider making the timer customizable.
1379 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1380 mCellularRadioTimesharingCapable =
1381 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1382
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001383 mHandlerThread = mDeps.makeHandlerThread();
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001384 mHandlerThread.start();
1385 mHandler = new InternalHandler(mHandlerThread.getLooper());
1386 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001387 mConnectivityDiagnosticsHandler =
1388 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001389
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001390 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001391 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001392
junyulaie7c7d2a2021-01-26 15:29:15 +08001393 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001394 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001395 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001396 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001397
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001398 mNetd = netd;
Wink Saville32506bc2013-06-29 21:10:57 -07001399 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001400 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001401 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001402
Sudheer Shanka9967d462021-03-18 19:09:25 +00001403 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001404 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1405 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001406 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001407
1408 final PowerManager powerManager = (PowerManager) context.getSystemService(
1409 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001410 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001411 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001412
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001413 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1414 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001415 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001416 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001417 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001418 mProtectedNetworks.add(p);
1419 } else {
1420 if (DBG) loge("Ignoring protectedNetwork " + p);
1421 }
1422 }
1423
soma, kawata29444ae2019-05-23 09:30:40 +09001424 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1425
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001426 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -07001427
James Mattis02220e22021-03-13 19:27:21 -08001428 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001429 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001430 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001431 final IntentFilter userIntentFilter = new IntentFilter();
1432 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1433 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1434 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1435 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001436
James Mattis02220e22021-03-13 19:27:21 -08001437 // Listen to package add/removes for netd
1438 final IntentFilter packageIntentFilter = new IntentFilter();
1439 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1440 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1441 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1442 packageIntentFilter.addDataScheme("package");
1443 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001444 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001445
lucaslind5c2d072021-02-20 18:59:47 +08001446 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001447
lucaslin66f44212021-02-23 01:12:55 +08001448 mNetdCallback = new NetdCallback();
1449 try {
1450 mNetd.registerUnsolicitedEventListener(mNetdCallback);
1451 } catch (RemoteException | ServiceSpecificException e) {
1452 loge("Error registering event listener :" + e);
1453 }
1454
Erik Kline05f2b402015-04-30 12:58:40 +09001455 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1456 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001457
junyulai7e06ad42019-03-04 22:45:36 +08001458 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001459 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001460 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001461
1462 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001463 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001464 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1465 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001466 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001467 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1468 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001469
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001470 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001471 mContext, mHandler, () -> updateAvoidBadWifi());
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001472 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001473
Chiachang Wangc1215d32020-10-20 15:38:58 +08001474 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001475 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001476
Chalard Jean28018572020-12-21 18:36:52 +09001477 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1478 // request that doesn't allow fallback to the default network. It should never be visible
1479 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1480 // arguments like the handler or the DnsResolver.
1481 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001482 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001483 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001484 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001485 new LinkProperties(), new NetworkCapabilities(),
1486 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001487 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1488 mLingerDelayMs, mQosCallbackTracker, mDeps);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001489 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001490
Chalard Jean46adcf32018-04-18 20:18:38 +09001491 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001492 return createDefaultNetworkCapabilitiesForUidRange(new UidRange(uid, uid));
1493 }
1494
1495 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRange(
1496 @NonNull final UidRange uids) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001497 final NetworkCapabilities netCap = new NetworkCapabilities();
1498 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001499 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001500 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Chiachang Wang8156c4e2021-03-19 00:45:39 +00001501 netCap.setUids(UidRange.toIntRanges(Collections.singleton(uids)));
Chalard Jean46adcf32018-04-18 20:18:38 +09001502 return netCap;
1503 }
1504
James Mattis45d81842021-01-10 14:24:24 -08001505 private NetworkRequest createDefaultRequest() {
1506 return createDefaultInternetRequestForTransport(
1507 TYPE_NONE, NetworkRequest.Type.REQUEST);
1508 }
1509
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001510 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001511 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001512 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001513 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001514 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001515 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001516 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001517 netCap.addTransportType(transportType);
1518 }
James Mattis45d81842021-01-10 14:24:24 -08001519 return createNetworkRequest(type, netCap);
1520 }
1521
1522 private NetworkRequest createNetworkRequest(
1523 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001524 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001525 }
1526
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001527 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1528 NetworkRequest.Type type) {
1529 final NetworkCapabilities netCap = new NetworkCapabilities();
1530 netCap.clearAll();
1531 netCap.addCapability(capability);
1532 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1533 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1534 }
1535
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001536 // Used only for testing.
1537 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001538 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001539 // changing ContentResolver to make registerContentObserver non-final).
1540 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1541 // by subclassing SettingsObserver.
1542 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001543 void updateAlwaysOnNetworks() {
1544 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001545 }
1546
Erik Kline9a62f012018-03-21 07:18:33 -07001547 // See FakeSettingsProvider comment above.
1548 @VisibleForTesting
1549 void updatePrivateDnsSettings() {
1550 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1551 }
1552
paulhu51f77dc2021-06-07 02:34:20 +00001553 @VisibleForTesting
1554 void updateMobileDataPreferredUids() {
1555 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1556 }
1557
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09001558 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, int id) {
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001559 final boolean enable = mContext.getResources().getBoolean(id);
1560 handleAlwaysOnNetworkRequest(networkRequest, enable);
1561 }
1562
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001563 private void handleAlwaysOnNetworkRequest(
1564 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001565 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001566 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001567 handleAlwaysOnNetworkRequest(networkRequest, enable);
1568 }
1569
1570 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001571 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001572 if (enable == isEnabled) {
1573 return; // Nothing to do.
1574 }
1575
1576 if (enable) {
1577 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001578 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001579 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001580 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001581 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001582 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1583 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001584 }
1585 }
1586
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001587 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001588 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1589 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1590 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1591 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001592 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1593 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001594 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001595 }
1596
paulhu51f77dc2021-06-07 02:34:20 +00001597 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001598 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001599 private void registerSettingsCallbacks() {
1600 // Watch for global HTTP proxy changes.
1601 mSettingsObserver.observe(
1602 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1603 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1604
1605 // Watch for whether or not to keep mobile data always on.
1606 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001607 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001608 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1609
1610 // Watch for whether or not to keep wifi always on.
1611 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001612 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001613 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001614
1615 // Watch for mobile data preferred uids changes.
1616 mSettingsObserver.observe(
1617 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1618 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001619 }
1620
Erik Kline31b4a9e2018-01-11 21:07:29 +09001621 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001622 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1623 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001624 }
1625 }
1626
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001627 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001628 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1629 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001630 return mNextNetworkRequestId++;
1631 }
1632
junyulai74f9a8b2018-06-13 15:00:37 +08001633 @VisibleForTesting
1634 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001635 if (network == null) {
1636 return null;
1637 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001638 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001639 }
1640
1641 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001642 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001643 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001644 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001645 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001646
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001647 // TODO: determine what to do when more than one VPN applies to |uid|.
1648 private NetworkAgentInfo getVpnForUid(int uid) {
1649 synchronized (mNetworkForNetId) {
1650 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1651 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
1652 if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) {
1653 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001654 }
1655 }
1656 }
1657 return null;
1658 }
1659
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001660 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001661 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001662 final NetworkAgentInfo nai = getVpnForUid(uid);
1663 if (nai != null) return nai.declaredUnderlyingNetworks;
1664 return null;
1665 }
1666
Lorenzo Colittia7574052021-01-19 01:33:05 +09001667 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001668 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001669
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001670 final Network[] networks = getVpnUnderlyingNetworks(uid);
1671 if (networks != null) {
1672 // getUnderlyingNetworks() returns:
1673 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1674 // empty array => the VPN explicitly said "no default network".
1675 // non-empty array => the VPN specified one or more default networks; we use the
1676 // first one.
1677 if (networks.length > 0) {
1678 nai = getNetworkAgentInfoForNetwork(networks[0]);
1679 } else {
1680 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001681 }
1682 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001683 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001684 }
1685
1686 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001687 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001688 */
paulhu7aeba372020-12-30 00:42:19 +08001689 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1690 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001691 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001692 if (ignoreBlocked) {
1693 return false;
1694 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001695 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001696 final long ident = Binder.clearCallingIdentity();
1697 try {
1698 final boolean metered = nc == null ? true : nc.isMetered();
1699 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1700 } finally {
1701 Binder.restoreCallingIdentity(ident);
1702 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001703 }
1704
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001705 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001706 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1707 return;
1708 }
Hugo Benichi47011212017-03-30 10:46:05 +09001709 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001710 synchronized (mBlockedAppUids) {
1711 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001712 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001713 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001714 blocked = false;
1715 } else {
1716 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001717 }
1718 }
Hugo Benichi47011212017-03-30 10:46:05 +09001719 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1720 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1721 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001722 }
1723
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001724 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001725 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1726 return;
1727 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001728 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001729 final int requestId = nri.getActiveRequest() != null
1730 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001731 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001732 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001733 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001734 }
1735
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001736 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001737 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001738 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001739 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001740 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001741 @NonNull
1742 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1743 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001744 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1745 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1746 // but only exists if an app asks about them or requests them. Ensure the requesting app
1747 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001748 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001749 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1750 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1751 null /* extraInfo */);
1752 }
1753 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001754 return filtered;
1755 }
1756
1757 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1758 boolean ignoreBlocked) {
1759 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1760 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001761 }
1762
1763 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001764 * Return NetworkInfo for the active (i.e., connected) network interface.
1765 * It is assumed that at most one network is active at a time. If more
1766 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001767 * @return the info for the active network, or {@code null} if none is
1768 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001769 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001770 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001771 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001772 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001773 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001774 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1775 if (nai == null) return null;
1776 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1777 maybeLogBlockedNetworkInfo(networkInfo, uid);
1778 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001779 }
1780
Paul Jensen1f567382015-02-13 14:18:39 -05001781 @Override
1782 public Network getActiveNetwork() {
1783 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001784 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00001785 }
1786
1787 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001788 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001789 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001790 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001791 }
1792
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001793 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001794 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1795 if (vpnNai != null) {
1796 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1797 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1798 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09001799 }
Paul Jensen1f567382015-02-13 14:18:39 -05001800 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001801
James Mattis2516da32021-01-31 17:06:19 -08001802 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001803 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1804 ignoreBlocked)) {
1805 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001806 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001807 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05001808 }
1809
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001810 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001811 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001812 PermissionUtils.enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001813 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1814 if (nai == null) return null;
1815 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001816 }
1817
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001818 /** Returns a NetworkInfo object for a network that doesn't exist. */
1819 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1820 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1821 getNetworkTypeName(networkType), "" /* subtypeName */);
1822 info.setIsAvailable(true);
1823 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1824 // background data is restricted.
1825 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1826 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1827 ? DetailedState.BLOCKED
1828 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001829 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1830 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001831 return info;
1832 }
1833
Lorenzo Colittia7574052021-01-19 01:33:05 +09001834 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001835 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1836 return null;
1837 }
1838 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001839 if (nai == null) {
1840 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001841 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001842 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1843 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001844 }
1845
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001846 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001847 public NetworkInfo getNetworkInfo(int networkType) {
1848 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001849 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001850 if (getVpnUnderlyingNetworks(uid) != null) {
1851 // A VPN is active, so we may need to return one of its underlying networks. This
1852 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09001853 // getNetworkAgentInfoForUid.
1854 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1855 if (nai == null) return null;
1856 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1857 if (networkInfo.getType() == networkType) {
1858 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001859 }
1860 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001861 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001862 }
1863
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001864 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001865 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001866 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001867 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001868 if (nai == null) return null;
1869 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001870 }
1871
1872 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001873 public NetworkInfo[] getAllNetworkInfo() {
1874 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08001875 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04001876 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1877 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001878 NetworkInfo info = getNetworkInfo(networkType);
1879 if (info != null) {
1880 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001881 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001882 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001883 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001884 }
1885
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001886 @Override
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001887 public Network getNetworkForType(int networkType) {
1888 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001889 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1890 return null;
1891 }
1892 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1893 if (nai == null) {
1894 return null;
1895 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001896 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001897 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
1898 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001899 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001900 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001901 }
1902
1903 @Override
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001904 public Network[] getAllNetworks() {
1905 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001906 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04001907 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001908 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04001909 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001910 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04001911 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001912 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001913 }
1914
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001915 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08001916 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001917 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001918 // The basic principle is: if an app's traffic could possibly go over a
1919 // network, without the app doing anything multinetwork-specific,
1920 // (hence, by "default"), then include that network's capabilities in
1921 // the array.
1922 //
1923 // In the normal case, app traffic only goes over the system's default
1924 // network connection, so that's the only network returned.
1925 //
1926 // With a VPN in force, some app traffic may go into the VPN, and thus
1927 // over whatever underlying networks the VPN specifies, while other app
1928 // traffic may go over the system default network (e.g.: a split-tunnel
1929 // VPN, or an app disallowed by the VPN), so the set of networks
1930 // returned includes the VPN's underlying networks and the system
1931 // default.
1932 enforceAccessPermission();
1933
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001934 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001935
James Mattis2516da32021-01-31 17:06:19 -08001936 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
1937 if (!nri.isBeingSatisfied()) {
1938 continue;
1939 }
1940 final NetworkAgentInfo nai = nri.getSatisfier();
1941 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
1942 if (null != nc
1943 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
1944 && !result.containsKey(nai.network)) {
1945 result.put(
1946 nai.network,
1947 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08001948 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08001949 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
1950 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08001951 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001952 }
1953
Lorenzo Colittidfab3032020-12-15 00:49:41 +09001954 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09001955 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08001956 if (null != networks) {
1957 for (final Network network : networks) {
1958 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
1959 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08001960 result.put(
1961 network,
1962 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08001963 nc,
1964 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08001965 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08001966 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001967 }
1968 }
1969 }
1970
1971 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1972 out = result.values().toArray(out);
1973 return out;
1974 }
1975
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001976 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001977 public boolean isNetworkSupported(int networkType) {
1978 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001979 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001980 }
1981
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001982 /**
1983 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08001984 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001985 * @return the ip properties for the active network, or {@code null} if
1986 * none is active
1987 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001988 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001989 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001990 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001991 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001992 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1993 if (nai == null) return null;
1994 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09001995 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001996 }
1997
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001998 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001999 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002000 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002001 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002002 final LinkProperties lp = getLinkProperties(nai);
2003 if (lp == null) return null;
2004 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002005 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002006 }
2007
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002008 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002009 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002010 public LinkProperties getLinkProperties(Network network) {
2011 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002012 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2013 if (lp == null) return null;
2014 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002015 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002016 }
2017
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002018 @Nullable
2019 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002020 if (nai == null) {
2021 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002022 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002023 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002024 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002025 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002026 }
2027
Qingxi Lib2748102020-01-08 12:51:49 -08002028 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2029 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2030 }
2031
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002032 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002033 if (nai == null) return null;
2034 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002035 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002036 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002037 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002038 }
2039
2040 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002041 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2042 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002043 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002044 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002045 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002046 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002047 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002048 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002049 }
2050
Qingxi Libb8da982020-01-17 17:54:27 -08002051 @VisibleForTesting
2052 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002053 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002054 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002055 if (!checkSettingsPermission(callerPid, callerUid)) {
2056 newNc.setUids(null);
2057 newNc.setSSID(null);
lucaslin6adf5ac2021-10-19 15:04:56 +08002058 newNc.setUnderlyingNetworks(null);
Chalard Jean46adcf32018-04-18 20:18:38 +09002059 }
Etan Cohen107ae952018-12-30 17:59:59 -08002060 if (newNc.getNetworkSpecifier() != null) {
2061 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2062 }
Cody Kesting5ab1f552020-03-16 18:15:28 -07002063 newNc.setAdministratorUids(new int[0]);
Benedict Wong53de25f2021-03-24 14:01:51 -07002064 if (!checkAnyPermissionOf(
2065 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
junyulai2217bec2021-04-14 23:33:31 +08002066 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002067 }
Qingxi Libb8da982020-01-17 17:54:27 -08002068
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002069 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002070 }
2071
Roshan Pius98f59ec2021-02-23 08:47:39 -08002072 /**
2073 * Wrapper used to cache the permission check results performed for the corresponding
2074 * app. This avoid performing multiple permission checks for different fields in
2075 * NetworkCapabilities.
2076 * Note: This wrapper does not support any sort of invalidation and thus must not be
2077 * persistent or long-lived. It may only be used for the time necessary to
2078 * compute the redactions required by one particular NetworkCallback or
2079 * synchronous call.
2080 */
2081 private class RedactionPermissionChecker {
2082 private final int mCallingPid;
2083 private final int mCallingUid;
2084 @NonNull private final String mCallingPackageName;
2085 @Nullable private final String mCallingAttributionTag;
2086
2087 private Boolean mHasLocationPermission = null;
2088 private Boolean mHasLocalMacAddressPermission = null;
2089 private Boolean mHasSettingsPermission = null;
2090
2091 RedactionPermissionChecker(int callingPid, int callingUid,
2092 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2093 mCallingPid = callingPid;
2094 mCallingUid = callingUid;
2095 mCallingPackageName = callingPackageName;
2096 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002097 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002098
2099 private boolean hasLocationPermissionInternal() {
2100 final long token = Binder.clearCallingIdentity();
2101 try {
2102 return mLocationPermissionChecker.checkLocationPermission(
2103 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2104 null /* message */);
2105 } finally {
2106 Binder.restoreCallingIdentity(token);
2107 }
2108 }
2109
2110 /**
2111 * Returns whether the app holds location permission or not (might return cached result
2112 * if the permission was already checked before).
2113 */
2114 public boolean hasLocationPermission() {
2115 if (mHasLocationPermission == null) {
2116 // If there is no cached result, perform the check now.
2117 mHasLocationPermission = hasLocationPermissionInternal();
2118 }
2119 return mHasLocationPermission;
2120 }
2121
2122 /**
2123 * Returns whether the app holds local mac address permission or not (might return cached
2124 * result if the permission was already checked before).
2125 */
2126 public boolean hasLocalMacAddressPermission() {
2127 if (mHasLocalMacAddressPermission == null) {
2128 // If there is no cached result, perform the check now.
2129 mHasLocalMacAddressPermission =
2130 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2131 }
2132 return mHasLocalMacAddressPermission;
2133 }
2134
2135 /**
2136 * Returns whether the app holds settings permission or not (might return cached
2137 * result if the permission was already checked before).
2138 */
2139 public boolean hasSettingsPermission() {
2140 if (mHasSettingsPermission == null) {
2141 // If there is no cached result, perform the check now.
2142 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2143 }
2144 return mHasSettingsPermission;
2145 }
2146 }
2147
2148 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2149 @NetworkCapabilities.NetCapability long redaction) {
2150 return (redactions & redaction) != 0;
2151 }
2152
2153 /**
2154 * Use the provided |applicableRedactions| to check the receiving app's
2155 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2156 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2157 * before being sent to the corresponding app.
2158 */
2159 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2160 @NetworkCapabilities.RedactionType long applicableRedactions,
2161 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2162 boolean includeLocationSensitiveInfo) {
2163 long redactions = applicableRedactions;
2164 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2165 if (includeLocationSensitiveInfo
2166 && redactionPermissionChecker.hasLocationPermission()) {
2167 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2168 }
2169 }
2170 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2171 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2172 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2173 }
2174 }
2175 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2176 if (redactionPermissionChecker.hasSettingsPermission()) {
2177 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2178 }
2179 }
2180 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002181 }
2182
Qingxi Lib2748102020-01-08 12:51:49 -08002183 @VisibleForTesting
2184 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002185 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002186 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002187 int callingPid, int callingUid, @NonNull String callingPkgName,
2188 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002189 if (nc == null) {
2190 return null;
2191 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002192 // Avoid doing location permission check if the transport info has no location sensitive
2193 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002194 final RedactionPermissionChecker redactionPermissionChecker =
2195 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2196 callingAttributionTag);
2197 final long redactions = retrieveRequiredRedactions(
2198 nc.getApplicableRedactions(), redactionPermissionChecker,
2199 includeLocationSensitiveInfo);
2200 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002201 // Reset owner uid if not destined for the owner app.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002202 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002203 newNc.setOwnerUid(INVALID_UID);
2204 return newNc;
2205 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002206 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2207 if (nc.hasTransport(TRANSPORT_VPN)) {
2208 // Owner UIDs already checked above. No need to re-check.
2209 return newNc;
2210 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002211 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2212 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002213 // compatibility for older apps.
2214 if (!includeLocationSensitiveInfo
2215 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002216 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002217 newNc.setOwnerUid(INVALID_UID);
2218 return newNc;
2219 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002220 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002221 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002222 newNc.setOwnerUid(INVALID_UID);
2223 }
Qingxi Lib2748102020-01-08 12:51:49 -08002224 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002225 }
2226
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002227 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2228 LinkProperties lp, int callerPid, int callerUid) {
2229 if (lp == null) return new LinkProperties();
2230
2231 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2232 final boolean needsSanitization =
2233 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2234 if (!needsSanitization) {
2235 return new LinkProperties(lp);
2236 }
2237
2238 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002239 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002240 }
2241
2242 final LinkProperties newLp = new LinkProperties(lp);
2243 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2244 // object gets parceled.
2245 newLp.setCaptivePortalApiUrl(null);
2246 newLp.setCaptivePortalData(null);
2247 return newLp;
2248 }
2249
Roshan Pius08c94fb2020-01-16 12:17:17 -08002250 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2251 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002252 // There is no need to track the effective UID of the request here. If the caller
2253 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002254 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002255 // Unprivileged apps can only pass in null or their own UID.
2256 if (nc.getUids() == null) {
2257 // If the caller passes in null, the callback will also match networks that do not
2258 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2259 // In this case, redact everything in the request immediately. This ensures that the
2260 // app is not able to get any redacted information by filing an unredacted request
2261 // and observing whether the request matches something.
2262 if (nc.getNetworkSpecifier() != null) {
2263 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2264 }
2265 } else {
2266 nc.setSingleUid(callerUid);
2267 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002268 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002269 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002270 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002271
2272 // Clear owner UID; this can never come from an app.
2273 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002274 }
2275
Chalard Jean38354d12018-03-20 19:13:57 +09002276 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002277 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002278 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2279 }
2280 }
2281
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002282 @Override
2283 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2284 enforceAccessPermission();
2285 final int callerUid = Binder.getCallingUid();
2286 final long token = Binder.clearCallingIdentity();
2287 try {
2288 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2289 } finally {
2290 Binder.restoreCallingIdentity(token);
2291 }
2292 }
2293
junyulaiebd15162021-03-03 12:09:05 +08002294 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002295 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002296 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002297 // This contains IMSI details, so make sure the caller is privileged.
paulhudf23d662021-01-25 18:53:17 +08002298 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002299
Serik Beketayev05130302021-01-15 16:47:25 -08002300 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002301 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002302 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2303 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002304 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002305 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002306 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002307 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2308 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002309 }
2310 }
2311 return result.toArray(new NetworkState[result.size()]);
2312 }
2313
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002314 @Override
junyulaiebd15162021-03-03 12:09:05 +08002315 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002316 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002317 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002318 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002319
2320 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2321 for (Network network : getAllNetworks()) {
2322 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Junyu Laiddecb662021-08-17 08:44:36 +00002323 if (nai != null && nai.everConnected) {
junyulaiebd15162021-03-03 12:09:05 +08002324 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2325 // NetworkCapabilities, which may contain UIDs of apps to which the
2326 // network applies. Should the UIDs be cleared so as not to leak or
2327 // interfere ?
2328 result.add(nai.getNetworkStateSnapshot());
2329 }
2330 }
2331 return result;
2332 }
2333
2334 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002335 public boolean isActiveNetworkMetered() {
2336 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002337
Qingxi Lib2748102020-01-08 12:51:49 -08002338 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002339 if (caps != null) {
2340 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2341 } else {
2342 // Always return the most conservative value
2343 return true;
2344 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002345 }
2346
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002347 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002348 * Ensures that the system cannot call a particular method.
2349 */
2350 private boolean disallowedBecauseSystemCaller() {
2351 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002352 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2353 // for devices launched with Q and above. However, existing devices upgrading to Q and
2354 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002355 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002356 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002357 log("This method exists only for app backwards compatibility"
2358 + " and must not be called by system services.");
2359 return true;
2360 }
2361 return false;
2362 }
2363
paulhub2c28682021-08-18 18:35:54 +08002364 private int getAppUid(final String app, final UserHandle user) {
2365 final PackageManager pm =
2366 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2367 final long token = Binder.clearCallingIdentity();
2368 try {
2369 return pm.getPackageUid(app, 0 /* flags */);
2370 } catch (PackageManager.NameNotFoundException e) {
2371 return -1;
2372 } finally {
2373 Binder.restoreCallingIdentity(token);
2374 }
2375 }
2376
2377 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2378 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2379 if (getAppUid(packageName, user) != callingUid) {
2380 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2381 }
2382 }
2383
Lorenzo Colitti23862912018-09-28 11:31:55 +09002384 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002385 * Ensure that a network route exists to deliver traffic to the specified
2386 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002387 * @param networkType the type of the network over which traffic to the
2388 * specified host is to be routed
2389 * @param hostAddress the IP address of the host to which the route is
2390 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002391 * @return {@code true} on success, {@code false} on failure
2392 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002393 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002394 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2395 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002396 if (disallowedBecauseSystemCaller()) {
2397 return false;
2398 }
paulhub2c28682021-08-18 18:35:54 +08002399 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002400 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002401 if (mProtectedNetworks.contains(networkType)) {
paulhu8e96a752019-08-12 16:25:11 +08002402 enforceConnectivityRestrictedNetworksPermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002403 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002404
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002405 InetAddress addr;
2406 try {
2407 addr = InetAddress.getByAddress(hostAddress);
2408 } catch (UnknownHostException e) {
2409 if (DBG) log("requestRouteToHostAddress got " + e.toString());
2410 return false;
2411 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002412
The Android Open Source Project28527d22009-03-03 19:31:44 -08002413 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002414 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002415 return false;
2416 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002417
2418 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2419 if (nai == null) {
2420 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
2421 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2422 } else {
2423 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2424 }
2425 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002426 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002427
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002428 DetailedState netState;
2429 synchronized (nai) {
2430 netState = nai.networkInfo.getDetailedState();
2431 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002432
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002433 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002434 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002435 log("requestRouteToHostAddress on down network "
2436 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002437 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002438 }
2439 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002440 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002441
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002442 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002443 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002444 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002445 LinkProperties lp;
2446 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002447 synchronized (nai) {
2448 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002449 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002450 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002451 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002452 if (DBG) {
2453 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2454 }
Wink Saville32506bc2013-06-29 21:10:57 -07002455 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002456 } finally {
2457 Binder.restoreCallingIdentity(token);
2458 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002459 }
2460
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002461 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002462 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002463 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002464 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002465 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002466 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002467 if (bestRoute.getGateway().equals(addr)) {
2468 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002469 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002470 } else {
2471 // if we will connect to this through another route, add a direct route
2472 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002473 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002474 }
2475 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002476 if (DBG) log("Adding legacy route " + bestRoute +
2477 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002478
2479 final String dst = bestRoute.getDestinationLinkAddress().toString();
2480 final String nextHop = bestRoute.hasGateway()
2481 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002482 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002483 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2484 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002485 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002486 return false;
2487 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002488 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002489 }
2490
paulhu7c0a2e62021-01-08 00:51:49 +08002491 class DnsResolverUnsolicitedEventCallback extends
2492 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002493 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002494 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002495 try {
2496 mHandler.sendMessage(mHandler.obtainMessage(
2497 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002498 new PrivateDnsValidationUpdate(event.netId,
2499 InetAddresses.parseNumericAddress(event.ipAddress),
2500 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002501 } catch (IllegalArgumentException e) {
2502 loge("Error parsing ip address in validation event");
2503 }
2504 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002505
2506 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002507 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2508 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002509 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2510 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2511 // event callback for certain nai. e.g. cellular. Register here to pass to
2512 // NetworkMonitor instead.
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002513 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allow one
2514 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2515 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002516 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002517 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002518 }
2519 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002520
2521 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002522 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2523 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2524 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002525 }
dalyk1720e542018-03-05 12:42:22 -05002526
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002527 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002528 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002529 return this.VERSION;
2530 }
2531
2532 @Override
2533 public String getInterfaceHash() {
2534 return this.HASH;
2535 }
paulhu7c0a2e62021-01-08 00:51:49 +08002536 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002537
2538 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002539 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2540 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002541
paulhu7c0a2e62021-01-08 00:51:49 +08002542 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002543 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002544 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002545 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002546 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002547 }
2548 }
2549
Sudheer Shanka9967d462021-03-18 19:09:25 +00002550 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002551 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002552 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002553 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2554 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002555 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002556 };
2557
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002558 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002559 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002560 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002561 }
2562
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002563 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002564 for (String permission : permissions) {
2565 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002566 return true;
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002567 }
2568 }
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002569 return false;
2570 }
2571
paulhu1a407652019-03-22 16:35:06 +08002572 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2573 for (String permission : permissions) {
2574 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2575 return true;
2576 }
2577 }
2578 return false;
2579 }
2580
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002581 private void enforceAnyPermissionOf(String... permissions) {
2582 if (!checkAnyPermissionOf(permissions)) {
2583 throw new SecurityException("Requires one of the following permissions: "
2584 + String.join(", ", permissions) + ".");
2585 }
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002586 }
2587
Paul Jensen83f5d572014-08-29 09:54:01 -04002588 private void enforceInternetPermission() {
2589 mContext.enforceCallingOrSelfPermission(
2590 android.Manifest.permission.INTERNET,
2591 "ConnectivityService");
2592 }
2593
The Android Open Source Project28527d22009-03-03 19:31:44 -08002594 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002595 mContext.enforceCallingOrSelfPermission(
2596 android.Manifest.permission.ACCESS_NETWORK_STATE,
2597 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002598 }
2599
paulhua6ee2122021-02-22 15:40:43 +08002600 /**
2601 * Performs a strict and comprehensive check of whether a calling package is allowed to
2602 * change the state of network, as the condition differs for pre-M, M+, and
2603 * privileged/preinstalled apps. The caller is expected to have either the
2604 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2605 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2606 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2607 * permission and cannot be revoked. See http://b/23597341
2608 *
2609 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2610 * of this app will be updated to the current time.
2611 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002612 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002613 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2614 == PackageManager.PERMISSION_GRANTED) {
2615 return;
2616 }
2617
2618 if (callingPkg == null) {
2619 throw new SecurityException("Calling package name is null.");
2620 }
2621
2622 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2623 final int uid = mDeps.getCallingUid();
2624 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2625 callingPkg, callingAttributionTag, null /* message */);
2626
2627 if (mode == AppOpsManager.MODE_ALLOWED) {
2628 return;
2629 }
2630
2631 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2632 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2633 return;
2634 }
2635
2636 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2637 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2638 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002639 }
2640
Charles He9369e612017-05-15 17:07:18 +01002641 private void enforceSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002642 enforceAnyPermissionOf(
Charles He9369e612017-05-15 17:07:18 +01002643 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002644 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002645 }
2646
paulhu8e96a752019-08-12 16:25:11 +08002647 private void enforceNetworkFactoryPermission() {
paulhub6ba8e82020-03-04 09:43:41 +08002648 enforceAnyPermissionOf(
paulhu8e96a752019-08-12 16:25:11 +08002649 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002650 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002651 }
2652
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002653 private void enforceNetworkFactoryOrSettingsPermission() {
2654 enforceAnyPermissionOf(
2655 android.Manifest.permission.NETWORK_SETTINGS,
2656 android.Manifest.permission.NETWORK_FACTORY,
2657 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2658 }
2659
2660 private void enforceNetworkFactoryOrTestNetworksPermission() {
2661 enforceAnyPermissionOf(
2662 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2663 android.Manifest.permission.NETWORK_FACTORY,
2664 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2665 }
2666
Chalard Jean9a396cc2018-02-21 18:43:54 +09002667 private boolean checkSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002668 return checkAnyPermissionOf(
2669 android.Manifest.permission.NETWORK_SETTINGS,
2670 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002671 }
2672
2673 private boolean checkSettingsPermission(int pid, int uid) {
2674 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002675 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2676 || PERMISSION_GRANTED == mContext.checkPermission(
2677 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002678 }
2679
paulhu8e96a752019-08-12 16:25:11 +08002680 private void enforceNetworkStackOrSettingsPermission() {
2681 enforceAnyPermissionOf(
2682 android.Manifest.permission.NETWORK_SETTINGS,
2683 android.Manifest.permission.NETWORK_STACK,
2684 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2685 }
2686
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002687 private void enforceNetworkStackSettingsOrSetup() {
2688 enforceAnyPermissionOf(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002689 android.Manifest.permission.NETWORK_SETTINGS,
2690 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002691 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002692 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002693 }
2694
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002695 private void enforceAirplaneModePermission() {
2696 enforceAnyPermissionOf(
2697 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2698 android.Manifest.permission.NETWORK_SETTINGS,
2699 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2700 android.Manifest.permission.NETWORK_STACK,
2701 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2702 }
2703
James Mattis8378aec2021-01-26 14:05:36 -08002704 private void enforceOemNetworkPreferencesPermission() {
2705 mContext.enforceCallingOrSelfPermission(
2706 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2707 "ConnectivityService");
2708 }
2709
James Mattisfa270db2021-05-31 17:11:10 -07002710 private void enforceManageTestNetworksPermission() {
2711 mContext.enforceCallingOrSelfPermission(
2712 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2713 "ConnectivityService");
2714 }
2715
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002716 private boolean checkNetworkStackPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002717 return checkAnyPermissionOf(
2718 android.Manifest.permission.NETWORK_STACK,
2719 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002720 }
2721
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002722 private boolean checkNetworkStackPermission(int pid, int uid) {
2723 return checkAnyPermissionOf(pid, uid,
2724 android.Manifest.permission.NETWORK_STACK,
2725 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2726 }
2727
paulhu1a407652019-03-22 16:35:06 +08002728 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2729 return checkAnyPermissionOf(pid, uid,
2730 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002731 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2732 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002733 }
2734
Hugo Benichibd0cc762016-07-19 15:59:27 +09002735 private void enforceConnectivityRestrictedNetworksPermission() {
2736 try {
2737 mContext.enforceCallingOrSelfPermission(
2738 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2739 "ConnectivityService");
2740 return;
2741 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
paulhu8e96a752019-08-12 16:25:11 +08002742 // TODO: Remove this fallback check after all apps have declared
2743 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2744 mContext.enforceCallingOrSelfPermission(
2745 android.Manifest.permission.CONNECTIVITY_INTERNAL,
2746 "ConnectivityService");
Hugo Benichibd0cc762016-07-19 15:59:27 +09002747 }
2748
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002749 private void enforceKeepalivePermission() {
Lorenzo Colittif25beee2015-09-08 13:21:48 +09002750 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002751 }
2752
Roshan Pius98f59ec2021-02-23 08:47:39 -08002753 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2754 return PERMISSION_GRANTED == mContext.checkPermission(
2755 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2756 }
2757
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002758 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002759 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002760 }
2761
2762 private void sendInetConditionBroadcast(NetworkInfo info) {
2763 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2764 }
2765
Wink Saville4f0de1e2011-08-04 15:01:58 -07002766 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002767 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002768 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002769 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002770 if (info.isFailover()) {
2771 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2772 info.setFailover(false);
2773 }
2774 if (info.getReason() != null) {
2775 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2776 }
2777 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002778 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2779 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002780 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002781 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002782 return intent;
2783 }
2784
2785 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2786 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2787 }
2788
Chiachang Wang3bc52762021-11-25 14:17:57 +08002789 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
2790 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002791 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09002792 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09002793 if (!mSystemReady
2794 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002795 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002796 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002797 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002798 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002799 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002800 }
2801
Dianne Hackborn66dd0332015-12-09 17:22:26 -08002802 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07002803 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002804 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07002805 final NetworkInfo ni = intent.getParcelableExtra(
2806 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08002807 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2808 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2809 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08002810 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002811 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07002812 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00002813 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002814 } finally {
2815 Binder.restoreCallingIdentity(ident);
2816 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002817 }
2818 }
2819
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002820 /**
Aaron Huang96011892020-06-27 07:18:23 +08002821 * Called by SystemServer through ConnectivityManager when the system is ready.
2822 */
2823 @Override
2824 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002825 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08002826 throw new SecurityException("Calling Uid is not system uid.");
2827 }
2828 systemReadyInternal();
2829 }
2830
2831 /**
2832 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002833 */
2834 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08002835 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09002836 // Load flags after PackageManager is ready to query module version
2837 mFlags.loadFlags(mDeps, mContext);
2838
Aaron Huang9a57acf2020-12-08 10:03:29 +08002839 // Since mApps in PermissionMonitor needs to be populated first to ensure that
2840 // listening network request which is sent by MultipathPolicyTracker won't be added
2841 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
2842 // be called after PermissionMonitor#startMonitoring().
2843 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
2844 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
2845 // to ensure the tracking will be initialized correctly.
paulhuc62d3c22019-11-19 17:55:31 +08002846 mPermissionMonitor.startMonitoring();
Chalard Jeane4f9bd92018-06-08 12:47:42 +09002847 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08002848 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002849
Hugo Benichie5220992017-04-26 14:53:28 +09002850 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002851 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002852 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07002853 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002854 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002855 }
2856 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002857
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002858 // Create network requests for always-on networks.
2859 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00002860
2861 // Update mobile data preference if necessary.
2862 // Note that empty uid list can be skip here only because no uid rules applied before system
2863 // ready. Normally, the empty uid list means to clear the uids rules on netd.
2864 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
2865 updateMobileDataPreferredUids();
2866 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002867 }
2868
The Android Open Source Project28527d22009-03-03 19:31:44 -08002869 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002870 * Start listening for default data network activity state changes.
2871 */
2872 @Override
2873 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08002874 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002875 }
2876
2877 /**
2878 * Stop listening for default data network activity state changes.
2879 */
2880 @Override
2881 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08002882 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002883 }
2884
2885 /**
2886 * Check whether the default network radio is currently active.
2887 */
2888 @Override
2889 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08002890 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002891 }
2892
2893 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09002894 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09002895 * and set it on it's iface.
2896 */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002897 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2898 final String iface = newLp.getInterfaceName();
2899 final int mtu = newLp.getMtu();
Pierre Imai07c53a32016-02-08 16:01:40 +09002900 if (oldLp == null && mtu == 0) {
2901 // Silently ignore unset MTU value.
2902 return;
2903 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002904 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2905 if (VDBG) log("identical MTU - not setting");
2906 return;
2907 }
paulhucbbc3db2019-03-08 16:35:20 +08002908 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002909 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002910 return;
2911 }
sy.yun4aa73922013-09-02 05:24:09 +09002912
w19976e714f1d2014-08-05 15:18:11 -07002913 // Cannot set MTU without interface name
2914 if (TextUtils.isEmpty(iface)) {
2915 loge("Setting MTU size with null iface.");
2916 return;
2917 }
2918
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002919 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09002920 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08002921 mNetd.interfaceSetMtu(iface, mtu);
2922 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08002923 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002924 }
2925 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002926
Chenbo Feng15416292018-11-08 17:36:21 -08002927 @VisibleForTesting
2928 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04002929
lucaslin821c9782018-11-28 19:27:52 +08002930 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002931 String[] values = null;
2932 if (tcpBufferSizes != null) {
2933 values = tcpBufferSizes.split(",");
2934 }
2935
2936 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07002937 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002938 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2939 values = tcpBufferSizes.split(",");
2940 }
2941
2942 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2943
2944 try {
Aaron Huang6616df32020-10-30 22:04:25 +08002945 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002946
Chenbo Feng15416292018-11-08 17:36:21 -08002947 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2948 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2949 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002950 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08002951 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002952 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002953 }
2954 }
2955
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07002956 @Override
2957 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09002958 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07002959 NETWORK_RESTORE_DELAY_PROP_NAME);
2960 if(restoreDefaultNetworkDelayStr != null &&
2961 restoreDefaultNetworkDelayStr.length() != 0) {
2962 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01002963 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002964 } catch (NumberFormatException e) {
2965 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002966 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002967 // if the system property isn't set, use the value for the apn type
2968 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2969
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09002970 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
2971 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002972 }
2973 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002974 }
2975
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002976 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2977 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2978 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09002979 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08002980 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002981 // Start gathering diagnostic information.
2982 netDiags.add(new NetworkDiagnostics(
2983 nai.network,
2984 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08002985 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002986 DIAG_TIME_MS));
2987 }
2988
2989 for (NetworkDiagnostics netDiag : netDiags) {
2990 pw.println();
2991 netDiag.waitForMeasurements();
2992 netDiag.dump(pw);
2993 }
2994 }
2995
The Android Open Source Project28527d22009-03-03 19:31:44 -08002996 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09002997 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
2998 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08002999 if (!checkDumpPermission(mContext, TAG, writer)) return;
3000
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003001 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003002 }
3003
lucaslin99473f62020-12-10 15:10:54 +08003004 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3005 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3006 != PackageManager.PERMISSION_GRANTED) {
3007 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003008 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003009 + " due to missing android.permission.DUMP permission");
3010 return false;
3011 } else {
3012 return true;
3013 }
3014 }
3015
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003016 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003017 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003018
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003019 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003020 dumpNetworkDiagnostics(pw);
3021 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003022 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003023 dumpNetworks(pw);
3024 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003025 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003026 dumpNetworkRequests(pw);
3027 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003028 }
Erik Kline9647f382015-06-05 17:47:34 +09003029
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003030 pw.print("NetworkProviders for:");
3031 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
3032 pw.print(" " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003033 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09003034 pw.println();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003035 pw.println();
3036
Chalard Jean5b409c72021-02-04 13:12:59 +09003037 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003038 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003039 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003040 pw.println("none");
3041 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003042 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003043 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003044 pw.println();
3045
James Mattis8b298a02021-06-01 22:34:04 -07003046 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003047 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003048 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003049 pw.decreaseIndent();
3050 pw.println();
3051
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003052 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003053 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003054 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003055 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003056 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003057
junyulaif2c67e42018-08-07 19:50:45 +08003058 pw.println("Status for known UIDs:");
3059 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003060 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003061 for (int i = 0; i < size; i++) {
3062 // Don't crash if the array is modified while dumping in bugreports.
3063 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003064 final int uid = mUidBlockedReasons.keyAt(i);
3065 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3066 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003067 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003068 } catch (ArrayIndexOutOfBoundsException e) {
3069 pw.println(" ArrayIndexOutOfBoundsException");
3070 } catch (ConcurrentModificationException e) {
3071 pw.println(" ConcurrentModificationException");
3072 }
3073 }
3074 pw.println();
3075 pw.decreaseIndent();
3076
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003077 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003078 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003079 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003080 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003081 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003082
Robert Greenwalt94e22142014-07-30 16:31:24 -07003083 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003084
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003085 pw.println();
markchien5e866652019-09-30 14:40:57 +08003086 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003087
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003088 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003089 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003090
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003091 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003092
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003093 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003094 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003095 pw.println("mNetworkRequestInfoLogs (most recent first):");
3096 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003097 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003098 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003099
3100 pw.println();
3101 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3102 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003103 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003104 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003105
3106 pw.println();
3107 pw.println("NetTransition WakeLock activity (most recent first):");
3108 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003109 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3110 pw.println("total releases: " + mTotalWakelockReleases);
3111 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3112 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3113 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3114 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3115 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3116 }
James Mattiscb1e0362021-04-06 17:07:42 -07003117 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003118
3119 pw.println();
3120 pw.println("bandwidth update requests (by uid):");
3121 pw.increaseIndent();
3122 synchronized (mBandwidthRequests) {
3123 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3124 pw.println("[" + mBandwidthRequests.keyAt(i)
3125 + "]: " + mBandwidthRequests.valueAt(i));
3126 }
3127 }
3128 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003129 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003130
James Mattiscb1e0362021-04-06 17:07:42 -07003131 pw.println();
3132 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3133 pw.increaseIndent();
3134 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003135 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003136 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003137
3138 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003139
3140 pw.println();
3141 pw.println("Permission Monitor:");
3142 pw.increaseIndent();
3143 mPermissionMonitor.dump(pw);
3144 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003145
3146 pw.println();
3147 pw.println("Legacy network activity:");
3148 pw.increaseIndent();
3149 mNetworkActivityTracker.dump(pw);
3150 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003151 }
3152
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003153 private void dumpNetworks(IndentingPrintWriter pw) {
3154 for (NetworkAgentInfo nai : networksSortedById()) {
3155 pw.println(nai.toString());
3156 pw.increaseIndent();
3157 pw.println(String.format(
3158 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3159 nai.numForegroundNetworkRequests(),
3160 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3161 nai.numBackgroundNetworkRequests(),
3162 nai.numNetworkRequests()));
3163 pw.increaseIndent();
3164 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3165 pw.println(nai.requestAt(i).toString());
3166 }
3167 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003168 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003169 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003170 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003171 pw.decreaseIndent();
3172 pw.decreaseIndent();
3173 }
3174 }
3175
James Mattis8b298a02021-06-01 22:34:04 -07003176 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3177 if (!mProfileNetworkPreferences.isEmpty()) {
3178 pw.println("Profile preferences:");
3179 pw.increaseIndent();
3180 pw.println(mProfileNetworkPreferences.preferences);
3181 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003182 }
James Mattis8b298a02021-06-01 22:34:04 -07003183 if (!mOemNetworkPreferences.isEmpty()) {
3184 pw.println("OEM preferences:");
3185 pw.increaseIndent();
3186 pw.println(mOemNetworkPreferences);
3187 pw.decreaseIndent();
3188 }
3189 if (!mMobileDataPreferredUids.isEmpty()) {
3190 pw.println("Mobile data preferred UIDs:");
3191 pw.increaseIndent();
3192 pw.println(mMobileDataPreferredUids);
3193 pw.decreaseIndent();
3194 }
James Mattis45d81842021-01-10 14:24:24 -08003195
James Mattis8b298a02021-06-01 22:34:04 -07003196 pw.println("Default requests:");
3197 pw.increaseIndent();
3198 dumpPerAppDefaultRequests(pw);
3199 pw.decreaseIndent();
3200 }
3201
3202 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003203 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3204 if (mDefaultRequest == defaultRequest) {
3205 continue;
3206 }
3207
James Mattis8b298a02021-06-01 22:34:04 -07003208 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3209 final String networkOutput;
3210 if (null == satisfier) {
3211 networkOutput = "null";
3212 } else if (mNoServiceNetwork.equals(satisfier)) {
3213 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003214 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003215 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003216 }
James Mattis8b298a02021-06-01 22:34:04 -07003217 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3218 ? "" : " asUid: " + defaultRequest.mAsUid;
3219 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3220 + defaultRequest.mPid + asUidString + "]";
3221 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3222 + " Preference order: " + defaultRequest.mPreferenceOrder
3223 + " Tracked UIDs: " + defaultRequest.getUids();
3224 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003225 }
3226 }
3227
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003228 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003229 NetworkRequestInfo[] infos = null;
3230 while (infos == null) {
3231 try {
3232 infos = requestsSortedById();
3233 } catch (ConcurrentModificationException e) {
3234 // mNetworkRequests should only be accessed from handler thread, except dump().
3235 // As dump() is never called in normal usage, it would be needlessly expensive
3236 // to lock the collection only for its benefit. Instead, retry getting the
3237 // requests if ConcurrentModificationException is thrown during dump().
3238 }
3239 }
3240 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003241 pw.println(nri.toString());
3242 }
3243 }
3244
Chalard Jean524f0b12021-10-25 21:11:56 +09003245 private void dumpAllRequestInfoLogsToLogcat() {
3246 try (PrintWriter logPw = new PrintWriter(new Writer() {
3247 @Override
3248 public void write(final char[] cbuf, final int off, final int len) {
3249 // This method is called with 0-length and 1-length arrays for empty strings
3250 // or strings containing only the DEL character.
3251 if (len <= 1) return;
3252 Log.e(TAG, new String(cbuf, off, len));
3253 }
3254 @Override public void flush() {}
3255 @Override public void close() {}
3256 })) {
3257 mNetworkRequestInfoLogs.dump(logPw);
3258 }
3259 }
3260
Hugo Benichia480ba52018-09-03 08:19:02 +09003261 /**
3262 * Return an array of all current NetworkAgentInfos sorted by network id.
3263 */
3264 private NetworkAgentInfo[] networksSortedById() {
3265 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003266 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003267 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003268 return networks;
3269 }
3270
3271 /**
3272 * Return an array of all current NetworkRequest sorted by request id.
3273 */
James Mattis258ea3c2020-11-15 15:04:40 -08003274 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003275 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003276 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003277 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003278 // Sort the array based off the NRI containing the min requestId in its requests.
3279 Arrays.sort(requests,
3280 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3281 Comparator.comparingInt(req -> req.requestId)).requestId
3282 )
3283 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003284 return requests;
3285 }
3286
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003287 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003288 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003289 if (officialNai != null && officialNai.equals(nai)) return true;
3290 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003291 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003292 " - " + nai);
3293 }
3294 return false;
3295 }
3296
Robert Greenwalt2034b912009-08-12 16:08:25 -07003297 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003298 private class NetworkStateTrackerHandler extends Handler {
3299 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003300 super(looper);
3301 }
3302
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003303 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003304 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3305 final NetworkAgentInfo nai = arg.first;
3306 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003307 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003308 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003309 }
3310 return;
3311 }
3312
3313 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003314 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003315 NetworkCapabilities networkCapabilities = (NetworkCapabilities) arg.second;
lucaslin2240ef62019-03-12 13:08:03 +08003316 if (networkCapabilities.hasConnectivityManagedCapability()) {
Aaron Huang6616df32020-10-30 22:04:25 +08003317 Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003318 }
Chalard Jean5b639762020-03-09 21:25:37 +09003319 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
3320 // Make sure the original object is not mutated. NetworkAgent normally
3321 // makes a copy of the capabilities when sending the message through
3322 // the Messenger, but if this ever changes, not making a defensive copy
3323 // here will give attack vectors to clients using this code path.
3324 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Chiachang Wangc07315a2021-08-10 15:13:39 +08003325 networkCapabilities.restrictCapabilitiesForTestNetwork(nai.creatorUid);
Chalard Jean5b639762020-03-09 21:25:37 +09003326 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003327 processCapabilitiesFromAgent(nai, networkCapabilities);
Hugo Benichibbc15192016-09-15 18:18:48 +09003328 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003329 break;
3330 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003331 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003332 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003333 processLinkPropertiesFromAgent(nai, newLp);
3334 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003335 break;
3336 }
3337 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003338 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003339 updateNetworkInfo(nai, info);
3340 break;
3341 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003342 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003343 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003344 break;
3345 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003346 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003347 if (nai.everConnected) {
3348 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003349 // Note that if the NAI had been connected, this would affect the
3350 // score, and therefore would require re-mixing the score and performing
3351 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003352 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003353 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3354 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003355 // Mark the network as temporarily accepting partial connectivity so that it
3356 // will be validated (and possibly become default) even if it only provides
3357 // partial internet access. Note that if user connects to partial connectivity
3358 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3359 // out of wifi coverage) and if the same wifi is available again, the device
3360 // will auto connect to this wifi even though the wifi has "no internet".
3361 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003362 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003363 break;
3364 }
junyulai011b1f12019-01-03 18:50:15 +08003365 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003366 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003367 break;
3368 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003369 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003370 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003371 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003372
3373 if (isLegacyLockdownNai(nai)
3374 && (underlying == null || underlying.size() != 1)) {
3375 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3376 + " must have exactly one underlying network: " + underlying);
3377 }
3378
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003379 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3380 nai.declaredUnderlyingNetworks = (underlying != null)
3381 ? underlying.toArray(new Network[0]) : null;
3382
3383 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3384 if (DBG) {
3385 log(nai.toShortString() + " changed underlying networks to "
3386 + Arrays.toString(nai.declaredUnderlyingNetworks));
3387 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003388 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003389 notifyIfacesChangedForNetworkStats();
3390 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003391 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003392 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003393 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3394 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3395 nai.teardownDelayMs = msg.arg1;
3396 } else {
3397 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3398 }
Chalard Jean550b5212021-03-05 23:07:53 +09003399 break;
3400 }
3401 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3402 nai.setLingerDuration((int) arg.second);
3403 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003404 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003405 }
3406 }
3407
3408 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
3409 switch (msg.what) {
3410 default:
3411 return false;
lucasline117e2e2019-10-22 18:27:33 +08003412 case EVENT_PROBE_STATUS_CHANGED: {
3413 final Integer netId = (Integer) msg.obj;
3414 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3415 if (nai == null) {
3416 break;
3417 }
3418 final boolean probePrivateDnsCompleted =
3419 ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
3420 final boolean privateDnsBroken =
3421 ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
3422 if (probePrivateDnsCompleted) {
3423 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3424 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003425 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003426 }
3427 // Only show the notification when the private DNS is broken and the
3428 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003429 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003430 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3431 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003432 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003433 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3434 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3435 // private DNS is broken, it means this network is being reevaluated.
3436 // Either probing private DNS is not necessary any more or it hasn't been
3437 // done yet. In either case, the networkCapabilities should be updated to
3438 // reflect the new status.
3439 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003440 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003441 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003442 }
3443 break;
3444 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003445 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003446 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3447
3448 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(results.mNetId);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003449 if (nai == null) break;
3450
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003451 handleNetworkTested(nai, results.mTestResult,
3452 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003453 break;
3454 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003455 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09003456 final int netId = msg.arg2;
Hugo Benichif4210292017-04-21 15:07:12 +09003457 final boolean visible = toBool(msg.arg1);
Erik Kline9a62f012018-03-21 07:18:33 -07003458 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Ondada1452016-10-11 15:10:46 -07003459 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04003460 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3461 nai.lastCaptivePortalDetected = visible;
3462 nai.everCaptivePortalDetected |= visible;
Calvin Ondada1452016-10-11 15:10:46 -07003463 if (nai.lastCaptivePortalDetected &&
paulhu56e09df2021-03-17 20:30:33 +08003464 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3465 == getCaptivePortalMode()) {
Chalard Jean49707572019-12-10 21:07:02 +09003466 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003467 nai.onPreventAutomaticReconnect();
Calvin Ondada1452016-10-11 15:10:46 -07003468 teardownUnneededNetwork(nai);
3469 break;
3470 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003471 updateCapabilitiesForNetwork(nai);
Paul Jensen53f08952015-06-16 14:27:36 -04003472 }
3473 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003474 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003475 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003476 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3477 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003478 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003479 if (nai == null) {
3480 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3481 break;
3482 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003483 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003484 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003485 (PendingIntent) msg.obj,
3486 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003487 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003488 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003489 break;
3490 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003491 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline9a62f012018-03-21 07:18:33 -07003492 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003493 if (nai == null) break;
3494
Erik Kline9a62f012018-03-21 07:18:33 -07003495 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003496 break;
3497 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003498 case EVENT_CAPPORT_DATA_CHANGED: {
3499 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3500 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003501 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003502 break;
3503 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003504 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003505 return true;
3506 }
3507
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003508 private void handleNetworkTested(
3509 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
3510 final boolean wasPartial = nai.partialConnectivity;
3511 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3512 final boolean partialConnectivityChanged =
3513 (wasPartial != nai.partialConnectivity);
3514
3515 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3516 final boolean wasValidated = nai.lastValidated;
Chalard Jean5b409c72021-02-04 13:12:59 +09003517 final boolean wasDefault = isDefaultNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003518
3519 if (DBG) {
3520 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3521 ? " with redirect to " + redirectUrl
3522 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003523 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003524 }
3525 if (valid != nai.lastValidated) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003526 final int oldScore = nai.getCurrentScore();
3527 nai.lastValidated = valid;
3528 nai.everValidated |= valid;
3529 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003530 if (valid) {
3531 handleFreshlyValidatedNetwork(nai);
3532 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3533 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003534 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003535 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003536 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003537 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003538 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003539 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003540 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003541 NotificationType.PRIVATE_DNS_BROKEN);
3542 // If network becomes valid, the hasShownBroken should be reset for
3543 // that network so that the notification will be fired when the private
3544 // DNS is broken again.
3545 nai.networkAgentConfig.hasShownBroken = false;
3546 }
3547 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003548 updateCapabilitiesForNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003549 }
3550 updateInetCondition(nai);
3551 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003552 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003553 nai.onValidationStatusChanged(
3554 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3555 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003556
3557 // If NetworkMonitor detects partial connectivity before
3558 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3559 // immediately. Re-notify partial connectivity silently if no internet
3560 // notification already there.
3561 if (!wasPartial && nai.partialConnectivity) {
3562 // Remove delayed message if there is a pending message.
3563 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3564 handlePromptUnvalidated(nai.network);
3565 }
3566
3567 if (wasValidated && !nai.lastValidated) {
3568 handleNetworkUnvalidated(nai);
3569 }
3570 }
3571
Calvin Ondada1452016-10-11 15:10:46 -07003572 private int getCaptivePortalMode() {
3573 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08003574 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3575 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07003576 }
3577
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003578 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3579 switch (msg.what) {
3580 default:
3581 return false;
3582 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3583 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3584 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3585 handleLingerComplete(nai);
3586 }
3587 break;
3588 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003589 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3590 handleNetworkAgentRegistered(msg);
3591 break;
3592 }
3593 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3594 handleNetworkAgentDisconnected(msg);
3595 break;
3596 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003597 }
3598 return true;
3599 }
3600
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003601 @Override
3602 public void handleMessage(Message msg) {
lifraf3a3492021-03-10 13:58:14 +08003603 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09003604 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003605 maybeHandleNetworkAgentMessage(msg);
3606 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003607 }
3608 }
3609
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003610 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09003611 private final int mNetId;
3612 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003613
3614 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003615 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003616 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003617 }
3618
3619 @Override
3620 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3621 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09003622 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003623 }
3624
3625 @Override
3626 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003627 // Legacy version of notifyNetworkTestedWithExtras.
3628 // Would only be called if the system has a NetworkStack module older than the
3629 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08003630 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003631 }
3632
3633 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003634 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09003635 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3636 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003637 final Message msg = mTrackerHandler.obtainMessage(
3638 EVENT_NETWORK_TESTED,
3639 new NetworkTestedResults(
3640 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003641 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003642
3643 // Invoke ConnectivityReport generation for this Network test event.
3644 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3645 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003646
Cody Kestingf1120be2020-08-03 18:01:40 -07003647 // NetworkMonitor reports the network validation result as a bitmask while
3648 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
3649 // logical value for ConnectivityDiagnostics.
3650 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
3651 p.result);
3652
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003653 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07003654 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003655 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3656 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3657
Aaron Huang959d3642021-01-21 15:47:41 +08003658 ConnectivityReportEvent reportEvent =
3659 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3660 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
3661 ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003662 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003663 }
3664
3665 @Override
3666 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3667 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3668 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09003669 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003670 }
3671
3672 @Override
lucasline117e2e2019-10-22 18:27:33 +08003673 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3674 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3675 EVENT_PROBE_STATUS_CHANGED,
3676 probesCompleted, probesSucceeded, new Integer(mNetId)));
3677 }
3678
3679 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003680 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3681 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3682 EVENT_CAPPORT_DATA_CHANGED,
3683 0, mNetId, data));
3684 }
3685
3686 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003687 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003688 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003689 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003690
3691 final PendingIntent pendingIntent;
3692 // Only the system server can register notifications with package "android"
3693 final long token = Binder.clearCallingIdentity();
3694 try {
paulhu7746e4e2020-06-09 19:07:03 +08003695 pendingIntent = PendingIntent.getBroadcast(
3696 mContext,
3697 0 /* requestCode */,
3698 intent,
3699 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003700 } finally {
3701 Binder.restoreCallingIdentity(token);
3702 }
3703 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3704 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09003705 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003706 }
3707
3708 @Override
3709 public void hideProvisioningNotification() {
3710 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09003711 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003712 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003713
3714 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003715 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003716 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08003717 }
3718
3719 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003720 public int getInterfaceVersion() {
3721 return this.VERSION;
3722 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09003723
3724 @Override
3725 public String getInterfaceHash() {
3726 return this.HASH;
3727 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003728 }
3729
Cody Kestingf1120be2020-08-03 18:01:40 -07003730 /**
3731 * Converts the given NetworkMonitor-specific validation result bitmask to a
3732 * ConnectivityDiagnostics-specific validation result int.
3733 */
3734 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
3735 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
3736 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
3737 }
3738 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
3739 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
3740 }
3741 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
3742 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
3743 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
3744 }
3745
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003746 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07003747 log("Data stall detected with methods: " + p.detectionMethod);
3748
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003749 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07003750 int detectionMethod = 0;
3751 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
3752 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
3753 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
3754 }
3755 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
3756 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
3757 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
3758 p.tcpMetricsCollectionPeriodMillis);
3759 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003760 }
3761
Cody Kestingf53a0752020-04-15 12:33:28 -07003762 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003763 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08003764 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07003765
3766 // NetworkStateTrackerHandler currently doesn't take any actions based on data
3767 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
3768 // the cost of going through two handlers.
3769 mConnectivityDiagnosticsHandler.sendMessage(msg);
3770 }
3771
Cody Kestingb37958e2020-05-15 10:36:01 -07003772 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
3773 return (p.detectionMethod & detectionMethod) != 0;
3774 }
3775
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003776 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
3777 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07003778 }
3779
Erik Klinea73af002018-06-26 18:53:43 +09003780 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
3781 if (nai == null) return;
3782 // If the Private DNS mode is opportunistic, reprogram the DNS servers
3783 // in order to restart a validation pass from within netd.
3784 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3785 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003786 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09003787 }
3788 }
3789
Erik Kline31b4a9e2018-01-11 21:07:29 +09003790 private void handlePrivateDnsSettingsChanged() {
3791 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3792
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003793 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07003794 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003795 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05003796 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3797 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09003798 }
3799 }
3800
Erik Kline9a62f012018-03-21 07:18:33 -07003801 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
3802 // Private DNS only ever applies to networks that might provide
3803 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003804 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09003805
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003806 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07003807 // schedule DNS resolutions. If a DNS resolution is required the
3808 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09003809 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07003810
3811 // With Private DNS bypass support, we can proceed to update the
3812 // Private DNS config immediately, even if we're in strict mode
3813 // and have not yet resolved the provider name into a set of IPs.
3814 updatePrivateDns(nai, cfg);
3815 }
3816
3817 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
3818 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003819 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09003820 }
3821
dalyk1720e542018-03-05 12:42:22 -05003822 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
3823 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
3824 if (nai == null) {
3825 return;
3826 }
3827 mDnsManager.updatePrivateDnsValidation(update);
3828 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3829 }
3830
paulhu7c0a2e62021-01-08 00:51:49 +08003831 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003832 int prefixLength) {
3833 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
3834 if (nai == null) return;
3835
paulhu7c0a2e62021-01-08 00:51:49 +08003836 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
3837 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003838
3839 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08003840 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003841 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003842 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003843 prefixLength);
3844 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003845 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003846 return;
3847 }
3848 }
3849
Lorenzo Colittid523d142020-04-01 20:16:30 +09003850 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003851 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3852 }
3853
Hai Shalome58bdc62021-01-11 18:45:34 -08003854 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003855 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08003856 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003857 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
3858 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3859 }
3860
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003861 /**
junyulai2b6f0c22021-02-03 20:15:30 +08003862 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003863 * @param nai the agent info to update
3864 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08003865 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003866 */
junyulai2b6f0c22021-02-03 20:15:30 +08003867 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
3868 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
3869 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003870 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08003871 // one lingered request, set inactive.
3872 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08003873 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08003874 if (DBG) log("Unsetting inactive " + nai.toShortString());
3875 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003876 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08003877 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003878 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08003879 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
3880 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003881 }
junyulai2b6f0c22021-02-03 20:15:30 +08003882 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003883 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003884 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003885 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003886 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05003887 }
3888
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003889 private void handleNetworkAgentRegistered(Message msg) {
3890 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3891 if (!mNetworkAgentInfos.contains(nai)) {
3892 return;
3893 }
3894
3895 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
3896 if (VDBG) log("NetworkAgent registered");
3897 } else {
3898 loge("Error connecting NetworkAgent");
3899 mNetworkAgentInfos.remove(nai);
3900 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09003901 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003902 synchronized (mNetworkForNetId) {
3903 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003904 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003905 mNetIdManager.releaseNetId(nai.network.getNetId());
3906 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09003907 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003908 }
3909 }
3910 }
Paul Jensend5f53392014-11-25 15:26:53 -05003911
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003912 private void handleNetworkAgentDisconnected(Message msg) {
3913 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07003914 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003915 }
3916
Chalard Jeand9fffc32018-05-11 20:19:20 +09003917 // Destroys a network, remove references to it from the internal state managed by
3918 // ConnectivityService, free its interfaces and clean up.
3919 // Must be called on the Handler thread.
3920 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09003921 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07003922
3923 if (!mNetworkAgentInfos.contains(nai)) return;
3924
Chalard Jeand9fffc32018-05-11 20:19:20 +09003925 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09003926 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003927 }
lucaslinb25c9a62019-02-12 15:30:13 +08003928 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003929 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003930 // A network agent has disconnected.
3931 // TODO - if we move the logic to the network agent (have them disconnect
3932 // because they lost all their requests or because their score isn't good)
3933 // then they would disconnect organically, report their new state and then
3934 // disconnect the channel.
3935 if (nai.networkInfo.isConnected()) {
3936 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3937 null, null);
3938 }
Chalard Jean5b409c72021-02-04 13:12:59 +09003939 final boolean wasDefault = isDefaultNetwork(nai);
3940 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09003941 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09003942 }
3943 notifyIfacesChangedForNetworkStats();
3944 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
3945 // by other networks that are already connected. Perhaps that can be done by
3946 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
3947 // of rematchAllNetworksAndRequests
3948 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08003949 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07003950
3951 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09003952 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
3953 // Disable wakeup packet monitoring for each interface.
3954 wakeupModifyInterface(iface, nai.networkCapabilities, false);
3955 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09003956 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003957 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09003958 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09003959 synchronized (mNetworkForNetId) {
3960 // Remove the NetworkAgent, but don't mark the netId as
3961 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003962 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003963 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09003964 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09003965 // Remove all previously satisfied requests.
3966 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08003967 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09003968 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08003969 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08003970 if (currentNetwork != null
3971 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08003972 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09003973 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
3974 // rematch not to keep disconnected agents instead of setting it here ; this
3975 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08003976 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09003977 for (final NetworkOfferInfo noi : mNetworkOffers) {
3978 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08003979 }
James Mattise3ef1912020-12-20 11:09:58 -08003980
Chalard Jean5b409c72021-02-04 13:12:59 +09003981 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08003982 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09003983 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08003984 // network, because while incorrect this is the closest to the old (also
3985 // incorrect) behavior.
3986 mNetworkActivityTracker.updateDataActivityTracking(
3987 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08003988 ensureNetworkTransitionWakelock(nai.toShortString());
3989 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09003990 }
3991 }
junyulai2b6f0c22021-02-03 20:15:30 +08003992 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08003993 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09003994 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08003995 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09003996 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09003997 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09003998 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003999
4000 // Immediate teardown.
4001 if (nai.teardownDelayMs == 0) {
4002 destroyNetwork(nai);
4003 return;
4004 }
4005
4006 // Delayed teardown.
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304007 if (nai.created) {
4008 try {
4009 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4010 } catch (RemoteException e) {
4011 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4012 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004013 }
4014 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4015 }
4016
4017 private void destroyNetwork(NetworkAgentInfo nai) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004018 if (nai.created) {
4019 // Tell netd to clean up the configuration for this network
4020 // (routing rules, DNS, etc).
4021 // This may be slow as it requires a lot of netd shelling out to ip and
4022 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004023 // after we've rematched networks with requests (which might change the default
4024 // network or service a new request from an app), so network traffic isn't interrupted
4025 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004026 destroyNativeNetwork(nai);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004027 mDnsManager.removeNetwork(nai.network);
4028 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004029 mNetIdManager.releaseNetId(nai.network.getNetId());
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004030 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004031 }
4032
Ken Chen6df7a902021-04-09 15:08:42 +08004033 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004034 try {
4035 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004036 final NativeNetworkConfig config;
4037 if (nai.isVPN()) {
4038 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004039 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004040 return false;
4041 }
4042 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4043 INetd.PERMISSION_NONE,
4044 (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass),
Chiachang Wang9164c102022-01-13 10:54:32 +08004045 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004046 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004047 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
4048 getNetworkPermission(nai.networkCapabilities), /*secure=*/ false,
Chiachang Wangbf6b8792022-01-11 10:48:07 +08004049 VpnManager.TYPE_VPN_NONE, /*excludeLocalRoutes=*/ false);
Luke Huangfdd11f82019-04-09 18:41:49 +08004050 }
Ken Chen6df7a902021-04-09 15:08:42 +08004051 mNetd.networkCreate(config);
4052 mDnsResolver.createNetworkCache(nai.network.getNetId());
4053 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4054 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004055 return true;
4056 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004057 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004058 return false;
4059 }
4060 }
4061
Ken Chen6df7a902021-04-09 15:08:42 +08004062 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004063 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004064 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004065 } catch (RemoteException | ServiceSpecificException e) {
4066 loge("Exception destroying network(networkDestroy): " + e);
4067 }
4068 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004069 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004070 } catch (RemoteException | ServiceSpecificException e) {
4071 loge("Exception destroying network: " + e);
4072 }
4073 }
4074
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004075 // If this method proves to be too slow then we can maintain a separate
4076 // pendingIntent => NetworkRequestInfo map.
4077 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4078 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004079 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4080 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4081 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004082 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004083 return entry.getValue();
4084 }
4085 }
4086 return null;
4087 }
4088
Chalard Jean524f0b12021-10-25 21:11:56 +09004089 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4090 if (SdkLevel.isAtLeastT()) {
4091 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4092 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4093 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4094 // bug is fixed.
4095 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004096 throw new IllegalStateException("This NRI is already registered. New : " + nri
4097 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004098 }
4099 }
4100 }
4101 }
4102
James Mattisf7027322020-12-13 16:28:14 -08004103 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004104 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004105 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4106 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4107 final NetworkRequestInfo existingRequest =
4108 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004109 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004110 if (DBG) {
4111 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4112 + nri.mRequests.get(0) + " because their intents matched.");
4113 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004114 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004115 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004116 }
Erik Kline05f2b402015-04-30 12:58:40 +09004117 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004118 }
4119
James Mattisf7027322020-12-13 16:28:14 -08004120 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004121 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004122 }
4123
James Mattis3ce3d3c2021-02-09 18:18:28 -08004124 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004125 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004126 for (final NetworkRequestInfo nri : nris) {
4127 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004128 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004129 for (final NetworkRequest req : nri.mRequests) {
4130 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004131 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004132 if (req.isListen()) {
4133 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4134 if (req.networkCapabilities.hasSignalStrength()
4135 && network.satisfiesImmutableCapabilitiesOf(req)) {
4136 updateSignalStrengthThresholds(network, "REGISTER", req);
4137 }
James Mattisf7027322020-12-13 16:28:14 -08004138 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004139 }
4140 }
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004141 // If this NRI has a satisfier already, it is replacing an older request that
4142 // has been removed. Track it.
4143 final NetworkRequest activeRequest = nri.getActiveRequest();
4144 if (null != activeRequest) {
4145 // If there is an active request, then for sure there is a satisfier.
4146 nri.getSatisfier().addRequest(activeRequest);
4147 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004148 }
James Mattisf7027322020-12-13 16:28:14 -08004149
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004150 if (mFlags.noRematchAllRequestsOnRegister()) {
4151 rematchNetworksAndRequests(nris);
4152 } else {
4153 rematchAllNetworksAndRequests();
4154 }
James Mattis45d81842021-01-10 14:24:24 -08004155
Chalard Jean0354d8c2021-01-12 10:58:56 +09004156 // Requests that have not been matched to a network will not have been sent to the
4157 // providers, because the old satisfier and the new satisfier are the same (null in this
4158 // case). Send these requests to the providers.
4159 for (final NetworkRequestInfo nri : nris) {
4160 for (final NetworkOfferInfo noi : mNetworkOffers) {
4161 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004162 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004163 }
4164 }
4165
James Mattisf7027322020-12-13 16:28:14 -08004166 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4167 final int callingUid) {
4168 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004169 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004170 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4171 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4172 handleReleaseNetworkRequest(
4173 nri.mRequests.get(0),
4174 callingUid,
4175 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004176 }
4177 }
4178
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004179 // Determines whether the network is the best (or could become the best, if it validated), for
4180 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4181 // on the value of reason:
4182 //
4183 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4184 // then it should be torn down.
4185 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4186 // then it should be lingered.
4187 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004188 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004189
4190 if (!nai.everConnected || nai.isVPN() || nai.isInactive()
4191 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4192 return false;
4193 }
4194
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004195 final int numRequests;
4196 switch (reason) {
4197 case TEARDOWN:
4198 numRequests = nai.numRequestNetworkRequests();
4199 break;
4200 case LINGER:
4201 numRequests = nai.numForegroundNetworkRequests();
4202 break;
4203 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004204 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004205 return true;
4206 }
4207
Chalard Jean947acd42021-03-08 22:29:27 +09004208 if (numRequests > 0) return false;
4209
Paul Jensende49eb12015-06-25 15:30:08 -04004210 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004211 if (reason == UnneededFor.LINGER
4212 && !nri.isMultilayerRequest()
4213 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004214 // Background requests don't affect lingering.
4215 continue;
4216 }
4217
James Mattis3d229892020-11-16 16:46:28 -08004218 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004219 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004220 }
4221 }
Paul Jensende49eb12015-06-25 15:30:08 -04004222 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004223 }
4224
James Mattis3d229892020-11-16 16:46:28 -08004225 private boolean isNetworkPotentialSatisfier(
4226 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4227 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004228 // request, return immediately. For multilayer requests, check to see if any of the
4229 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004230 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4231 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004232 return false;
4233 }
4234 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004235 // This multilayer listen request is satisfied therefore no further requests need to be
4236 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004237 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004238 return false;
4239 }
James Mattis3d229892020-11-16 16:46:28 -08004240 // As non-multilayer listen requests have already returned, the below would only happen
4241 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004242 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004243 continue;
4244 }
4245 // If this Network is already the highest scoring Network for a request, or if
4246 // there is hope for it to become one if it validated, then it is needed.
4247 if (candidate.satisfies(req)) {
4248 // As soon as a network is found that satisfies a request, return. Specifically for
4249 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4250 // is important so as to not evaluate lower priority requests further in
4251 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004252 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4253 ? nri.getSatisfier() : null;
4254 // Note that this catches two important cases:
4255 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4256 // is currently satisfying the request. This is desirable when
4257 // cellular ends up validating but WiFi does not.
4258 // 2. Unvalidated WiFi will not be reaped when validated cellular
4259 // is currently satisfying the request. This is desirable when
4260 // WiFi ends up validating and out scoring cellular.
4261 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004262 }
4263 }
4264
4265 return false;
4266 }
4267
Erik Kline0c04b742016-07-07 16:50:58 +09004268 private NetworkRequestInfo getNriForAppRequest(
4269 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004270 // Looking up the app passed param request in mRequests isn't possible since it may return
4271 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4272 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004273 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4274 // to avoid potential race conditions when validating a package->uid mapping when sending
4275 // the callback on the very low-chance that an application shuts down prior to the callback
4276 // being sent.
4277 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4278 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004279
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004280 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004281 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004282 log(String.format("UID %d attempted to %s for unowned request %s",
4283 callingUid, requestedOperation, nri));
4284 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004285 }
Erik Kline0c04b742016-07-07 16:50:58 +09004286 }
4287
4288 return nri;
4289 }
4290
James Mattisf7027322020-12-13 16:28:14 -08004291 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4292 final String callingMethod) {
4293 if (nri.isMultilayerRequest()) {
4294 throw new IllegalStateException(
4295 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004296 }
4297 }
4298
James Mattisf7027322020-12-13 16:28:14 -08004299 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004300 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004301 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4302 // single NetworkRequest and thus does not apply to multilayer requests.
4303 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4304 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004305 return;
4306 }
James Mattis2516da32021-01-31 17:06:19 -08004307 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004308 return;
4309 }
James Mattisf7027322020-12-13 16:28:14 -08004310 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4311 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004312 }
4313 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004314 callCallbackForRequest(
4315 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004316 }
4317
James Mattisf7027322020-12-13 16:28:14 -08004318 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4319 final int callingUid,
4320 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004321 final NetworkRequestInfo nri =
4322 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4323 if (nri == null) {
4324 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004325 }
James Mattisf7027322020-12-13 16:28:14 -08004326 if (VDBG || (DBG && request.isRequest())) {
4327 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004328 }
4329 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004330 if (callOnUnavailable) {
4331 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4332 }
Erik Kline155a59a2015-11-25 12:49:38 +09004333 }
Erik Kline0c04b742016-07-07 16:50:58 +09004334
James Mattisa076c532020-12-02 14:12:41 -08004335 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004336 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004337 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004338 if (null == mNetworkRequests.remove(req)) {
4339 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4340 continue;
4341 }
James Mattisa076c532020-12-02 14:12:41 -08004342 if (req.isListen()) {
4343 removeListenRequestFromNetworks(req);
4344 }
4345 }
James Mattis8f036802021-06-20 16:26:01 -07004346 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004347 if (mDefaultNetworkRequests.remove(nri)) {
4348 // If this request was one of the defaults, then the UID rules need to be updated
4349 // WARNING : if the app(s) for which this network request is the default are doing
4350 // traffic, this will kill their connected sockets, even if an equivalent request
4351 // is going to be reinstated right away ; unconnected traffic will go on the default
4352 // until the new default is set, which will happen very soon.
4353 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4354 // remove ranges for those requests that won't have a replacement
4355 final NetworkAgentInfo satisfier = nri.getSatisfier();
4356 if (null != satisfier) {
4357 try {
paulhu0e79d952021-06-09 16:11:35 +08004358 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4359 satisfier.network.getNetId(),
4360 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004361 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004362 } catch (RemoteException e) {
4363 loge("Exception setting network preference default network", e);
4364 }
4365 }
4366 }
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09004367 nri.decrementRequestCount();
Erik Kline0c04b742016-07-07 16:50:58 +09004368 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004369 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004370
4371 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004372 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004373 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004374 }
4375 }
4376
Chalard Jean0354d8c2021-01-12 10:58:56 +09004377 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4378 // needed for this offer.
4379 for (final NetworkOfferInfo noi : mNetworkOffers) {
4380 for (final NetworkRequest req : nri.mRequests) {
4381 if (req.isRequest() && noi.offer.neededFor(req)) {
4382 noi.offer.onNetworkUnneeded(req);
4383 }
4384 }
4385 }
James Mattisa076c532020-12-02 14:12:41 -08004386 }
4387
James Mattis3ce3d3c2021-02-09 18:18:28 -08004388 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4389 for (final NetworkRequestInfo nri : nris) {
4390 if (mDefaultRequest == nri) {
4391 // Make sure we never remove the default request.
4392 continue;
4393 }
4394 handleRemoveNetworkRequest(nri);
4395 }
4396 }
4397
James Mattisa076c532020-12-02 14:12:41 -08004398 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4399 // listens don't have a singular affected Network. Check all networks to see
4400 // if this listen request applies and remove it.
4401 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4402 nai.removeRequest(req.requestId);
4403 if (req.networkCapabilities.hasSignalStrength()
4404 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4405 updateSignalStrengthThresholds(nai, "RELEASE", req);
4406 }
4407 }
4408 }
4409
4410 /**
4411 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4412 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4413 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4414 */
4415 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4416 boolean wasKept = false;
4417 final NetworkAgentInfo nai = nri.getSatisfier();
4418 if (nai != null) {
4419 final int requestLegacyType = nri.getActiveRequest().legacyType;
4420 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4421 nai.removeRequest(nri.getActiveRequest().requestId);
4422 if (VDBG || DDBG) {
4423 log(" Removing from current network " + nai.toShortString()
4424 + ", leaving " + nai.numNetworkRequests() + " requests.");
4425 }
4426 // If there are still lingered requests on this network, don't tear it down,
4427 // but resume lingering instead.
4428 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004429 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004430 notifyNetworkLosing(nai, now);
4431 }
4432 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4433 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4434 teardownUnneededNetwork(nai);
4435 } else {
4436 wasKept = true;
4437 }
James Mattisa076c532020-12-02 14:12:41 -08004438 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4439 // Went from foreground to background.
4440 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004441 }
4442
Erik Kline0c04b742016-07-07 16:50:58 +09004443 // Maintain the illusion. When this request arrived, we might have pretended
4444 // that a network connected to serve it, even though the network was already
4445 // connected. Now that this request has gone away, we might have to pretend
4446 // that the network disconnected. LegacyTypeTracker will generate that
4447 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004448 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004449 boolean doRemove = true;
4450 if (wasKept) {
4451 // check if any of the remaining requests for this network are for the
4452 // same legacy type - if so, don't remove the nai
4453 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4454 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004455 if (otherRequest.legacyType == requestLegacyType
4456 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004457 if (DBG) log(" still have other legacy request - leaving");
4458 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004459 }
4460 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004461 }
4462
Erik Kline0c04b742016-07-07 16:50:58 +09004463 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004464 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004465 }
4466 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004467 }
4468 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004469
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004470 private PerUidCounter getRequestCounter(NetworkRequestInfo nri) {
4471 return checkAnyPermissionOf(
4472 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4473 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4474 }
4475
Lorenzo Colittid6459092016-07-04 12:55:44 +09004476 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004477 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004478 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004479 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004480 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004481 }
4482
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004483 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004484 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4485 enforceNetworkStackSettingsOrSetup();
4486 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4487 encodeBool(accept), encodeBool(always), network));
4488 }
4489
4490 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004491 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004492 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004493 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4494 }
4495
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004496 @Override
4497 public void setTestAllowBadWifiUntil(long timeMs) {
4498 enforceSettingsPermission();
4499 if (!Build.isDebuggable()) {
4500 throw new IllegalStateException("Does not support in non-debuggable build");
4501 }
4502
4503 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4504 throw new IllegalArgumentException("It should not exceed "
4505 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4506 }
4507
4508 mHandler.sendMessage(
4509 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
4510 }
4511
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004512 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4513 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4514 " accept=" + accept + " always=" + always);
4515
4516 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4517 if (nai == null) {
4518 // Nothing to do.
4519 return;
4520 }
4521
4522 if (nai.everValidated) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004523 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004524 return;
4525 }
4526
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004527 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08004528 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004529 }
4530
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004531 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4532 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004533 // If network becomes partial connectivity and user already accepted to use this
4534 // network, we should respect the user's option and don't need to popup the
4535 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004536 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004537 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004538 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004539 }
4540
4541 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004542 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004543 }
4544
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004545 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04004546 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004547 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09004548 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04004549 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004550 }
4551
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004552 }
4553
lucaslin2240ef62019-03-12 13:08:03 +08004554 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4555 boolean always) {
4556 if (DBG) {
4557 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4558 + " always=" + always);
4559 }
4560
4561 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4562 if (nai == null) {
4563 // Nothing to do.
4564 return;
4565 }
4566
4567 if (nai.lastValidated) {
4568 // The network validated while the dialog box was up. Take no action.
4569 return;
4570 }
4571
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004572 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4573 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004574 }
4575
4576 // TODO: Use the current design or save the user choice into IpMemoryStore.
4577 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004578 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08004579 }
4580
4581 if (!accept) {
4582 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004583 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08004584 // Tear down the network.
4585 teardownUnneededNetwork(nai);
4586 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08004587 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4588 // result in a partial connectivity result which will be processed by
4589 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08004590 //
4591 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4592 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004593 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08004594 }
4595 }
4596
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004597 private void handleSetAvoidUnvalidated(Network network) {
4598 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4599 if (nai == null || nai.lastValidated) {
4600 // Nothing to do. The network either disconnected or revalidated.
4601 return;
4602 }
4603 if (!nai.avoidUnvalidated) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004604 nai.avoidUnvalidated = true;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004605 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004606 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004607 }
4608 }
4609
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004610 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09004611 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004612 mHandler.sendMessageDelayed(
4613 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4614 PROMPT_UNVALIDATED_DELAY_MS);
4615 }
4616
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004617 @Override
4618 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08004619 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004620 mHandler.post(() -> {
4621 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4622 if (nai == null) return;
4623 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004624 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004625 });
4626 }
4627
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004628 /**
4629 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4630 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004631 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004632 * @param appExtras Bundle to use as intent extras for the captive portal application.
4633 * Must be treated as opaque to avoid preventing the captive portal app to
4634 * update its arguments.
4635 */
4636 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004637 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08004638 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4639 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004640
4641 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4642 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004643 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4644 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004645 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4646
lucaslin75ff7022020-12-17 04:14:35 +08004647 final long token = Binder.clearCallingIdentity();
4648 try {
4649 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4650 } finally {
4651 Binder.restoreCallingIdentity(token);
4652 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004653 }
4654
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004655 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4656 private final Network mNetwork;
4657
4658 private CaptivePortalImpl(Network network) {
4659 mNetwork = network;
4660 }
4661
4662 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004663 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004664 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
4665 enforceSettingsPermission();
4666 }
4667
Chiachang Wang938bfba2020-01-09 13:50:55 +08004668 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004669 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004670 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004671 }
4672
4673 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08004674 public void appRequest(final int request) {
4675 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4676 if (nm == null) return;
4677
4678 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08004679 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09004680 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08004681 }
4682 }
4683
4684 @Nullable
4685 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
4686 // getNetworkAgentInfoForNetwork is thread-safe
4687 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4688 if (nai == null) return null;
4689
4690 // nai.networkMonitor() is thread-safe
4691 return nai.networkMonitor();
4692 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004693 }
4694
Hugo Benichic9048bc2016-09-14 23:23:08 +00004695 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004696 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09004697 }
4698
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004699 /**
4700 * Return whether the device should maintain continuous, working connectivity by switching away
4701 * from WiFi networks having no connectivity.
4702 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
4703 */
4704 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004705 if (!checkNetworkStackPermission()) {
4706 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
4707 }
4708 return avoidBadWifi();
4709 }
4710
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004711 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09004712 ensureRunningOnConnectivityServiceThread();
4713 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004714 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09004715 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004716 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09004717 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
4718 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
4719 for (final NetworkOfferInfo noi : offersToUpdate) {
4720 updateOfferScore(noi.offer);
4721 }
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004722 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004723 }
4724
Erik Kline95ecfee2016-10-02 18:02:14 +09004725 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004726 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004727 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004728 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004729 if (!configRestrict) {
4730 pw.println("Bad Wi-Fi avoidance: unrestricted");
4731 return;
4732 }
4733
4734 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
4735 pw.increaseIndent();
4736 pw.println("Config restrict: " + configRestrict);
4737
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004738 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004739 String description;
4740 // Can't use a switch statement because strings are legal case labels, but null is not.
4741 if ("0".equals(value)) {
4742 description = "get stuck";
4743 } else if (value == null) {
4744 description = "prompt";
4745 } else if ("1".equals(value)) {
4746 description = "avoid";
4747 } else {
4748 description = value + " (?)";
4749 }
4750 pw.println("User setting: " + description);
4751 pw.println("Network overrides:");
4752 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09004753 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004754 if (nai.avoidUnvalidated) {
Chalard Jean49707572019-12-10 21:07:02 +09004755 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004756 }
4757 }
4758 pw.decreaseIndent();
4759 pw.decreaseIndent();
4760 }
4761
paulhu7746e4e2020-06-09 19:07:03 +08004762 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
4763 // unify the method.
4764 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
4765 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
4766 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
4767 return settingsComponent != null
4768 ? settingsComponent.getPackageName() : "com.android.settings";
4769 }
4770
lucaslinb1e8e382019-01-24 15:55:30 +08004771 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004772 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004773 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004774 switch (type) {
4775 case NO_INTERNET:
4776 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004777 // High priority because it is only displayed for explicitly selected networks.
4778 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004779 break;
lucasline117e2e2019-10-22 18:27:33 +08004780 case PRIVATE_DNS_BROKEN:
4781 action = Settings.ACTION_WIRELESS_SETTINGS;
4782 // High priority because we should let user know why there is no internet.
4783 highPriority = true;
4784 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004785 case LOST_INTERNET:
4786 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004787 // High priority because it could help the user avoid unexpected data usage.
4788 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004789 break;
lucaslin2240ef62019-03-12 13:08:03 +08004790 case PARTIAL_CONNECTIVITY:
4791 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004792 // Don't bother the user with a high-priority notification if the network was not
4793 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004794 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08004795 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004796 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004797 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004798 return;
4799 }
4800
4801 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08004802 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08004803 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08004804 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08004805 // Some OEMs have their own Settings package. Thus, need to get the current using
4806 // Settings package name instead of just use default name "com.android.settings".
4807 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
4808 intent.setClassName(settingsPkgName,
4809 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08004810 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004811
paulhu2af50222020-10-11 22:52:27 +08004812 PendingIntent pendingIntent = PendingIntent.getActivity(
4813 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08004814 0 /* requestCode */,
4815 intent,
paulhu2af50222020-10-11 22:52:27 +08004816 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004817
Serik Beketayevec8ad212020-12-07 22:43:07 -08004818 mNotifier.showNotification(
4819 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004820 }
4821
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004822 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
4823 // Don't prompt if the network is validated, and don't prompt on captive portals
4824 // because we're already prompting the user to sign in.
4825 if (nai.everValidated || nai.everCaptivePortalDetected) {
4826 return false;
4827 }
4828
4829 // If a network has partial connectivity, always prompt unless the user has already accepted
4830 // partial connectivity and selected don't ask again. This ensures that if the device
4831 // automatically connects to a network that has partial Internet access, the user will
4832 // always be able to use it, either because they've already chosen "don't ask again" or
4833 // because we have prompt them.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004834 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004835 return true;
4836 }
4837
4838 // If a network has no Internet access, only prompt if the network was explicitly selected
4839 // and if the user has not already told us to use the network regardless of whether it
4840 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004841 if (nai.networkAgentConfig.explicitlySelected
4842 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004843 return true;
4844 }
4845
4846 return false;
4847 }
4848
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004849 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09004850 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004851 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4852
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004853 if (nai == null || !shouldPromptUnvalidated(nai)) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004854 return;
4855 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09004856
4857 // Stop automatically reconnecting to this network in the future. Automatically connecting
4858 // to a network that provides no or limited connectivity is not useful, because the user
4859 // cannot use that network except through the notification shown by this method, and the
4860 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004861 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09004862
lucaslin2240ef62019-03-12 13:08:03 +08004863 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
4864 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
4865 // popup the notification immediately when the network is partial connectivity.
4866 if (nai.partialConnectivity) {
lucasline0118ab2019-03-21 11:59:22 +08004867 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08004868 } else {
4869 showNetworkNotification(nai, NotificationType.NO_INTERNET);
4870 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004871 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004872
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004873 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
4874 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09004875 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07004876
lucaslin2240ef62019-03-12 13:08:03 +08004877 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4878 return;
4879 }
4880
4881 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08004882 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004883 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004884 }
4885
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004886 @Override
4887 public int getMultipathPreference(Network network) {
4888 enforceAccessPermission();
4889
4890 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06004891 if (nai != null && nai.networkCapabilities
4892 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004893 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
4894 }
4895
Aaron Huang9a57acf2020-12-08 10:03:29 +08004896 final NetworkPolicyManager netPolicyManager =
4897 mContext.getSystemService(NetworkPolicyManager.class);
4898
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09004899 final long token = Binder.clearCallingIdentity();
4900 final int networkPreference;
4901 try {
4902 networkPreference = netPolicyManager.getMultipathPreference(network);
4903 } finally {
4904 Binder.restoreCallingIdentity(token);
4905 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08004906 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09004907 return networkPreference;
4908 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004909 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
4910 }
4911
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004912 @Override
4913 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09004914 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004915 }
4916
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004917 private class InternalHandler extends Handler {
4918 public InternalHandler(Looper looper) {
4919 super(looper);
4920 }
4921
4922 @Override
4923 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004924 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07004925 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004926 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09004927 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07004928 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004929 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004930 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09004931 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07004932 break;
4933 }
Jason Monka69f1b02013-10-10 14:02:51 -04004934 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08004935 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
4936 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04004937 break;
4938 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09004939 case EVENT_REGISTER_NETWORK_PROVIDER: {
4940 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07004941 break;
4942 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09004943 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
4944 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004945 break;
4946 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09004947 case EVENT_REGISTER_NETWORK_OFFER: {
4948 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
4949 break;
4950 }
4951 case EVENT_UNREGISTER_NETWORK_OFFER: {
4952 final NetworkOfferInfo offer =
4953 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
4954 if (null != offer) {
4955 handleUnregisterNetworkOffer(offer);
4956 }
4957 break;
4958 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004959 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004960 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
4961 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
4962 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004963 break;
4964 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004965 case EVENT_REGISTER_NETWORK_REQUEST:
4966 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09004967 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004968 break;
4969 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004970 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
4971 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004972 handleRegisterNetworkRequestWithIntent(msg);
4973 break;
4974 }
Erik Kline155a59a2015-11-25 12:49:38 +09004975 case EVENT_TIMEOUT_NETWORK_REQUEST: {
4976 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
4977 handleTimedOutNetworkRequest(nri);
4978 break;
4979 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004980 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
4981 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
4982 break;
4983 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004984 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08004985 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
4986 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004987 break;
4988 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004989 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09004990 Network network = (Network) msg.obj;
4991 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004992 break;
4993 }
lucaslin2240ef62019-03-12 13:08:03 +08004994 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
4995 Network network = (Network) msg.obj;
4996 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
4997 toBool(msg.arg2));
4998 break;
4999 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005000 case EVENT_SET_AVOID_UNVALIDATED: {
5001 handleSetAvoidUnvalidated((Network) msg.obj);
5002 break;
5003 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005004 case EVENT_PROMPT_UNVALIDATED: {
5005 handlePromptUnvalidated((Network) msg.obj);
5006 break;
5007 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005008 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5009 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005010 break;
5011 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005012 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005013 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005014 mKeepaliveTracker.handleStartKeepalive(msg);
5015 break;
5016 }
5017 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005018 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005019 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5020 int slot = msg.arg1;
5021 int reason = msg.arg2;
5022 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
5023 break;
5024 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005025 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5026 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5027 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005028 break;
5029 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005030 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5031 handlePrivateDnsSettingsChanged();
5032 break;
dalyk1720e542018-03-05 12:42:22 -05005033 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5034 handlePrivateDnsValidationUpdate(
5035 (PrivateDnsValidationUpdate) msg.obj);
5036 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005037 case EVENT_UID_BLOCKED_REASON_CHANGED:
5038 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005039 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005040 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5041 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5042 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005043 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005044 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5045 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005046 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005047 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005048 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005049 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005050 final Pair<List<ProfileNetworkPreferenceList.Preference>,
5051 IOnCompleteListener> arg =
5052 (Pair<List<ProfileNetworkPreferenceList.Preference>,
5053 IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005054 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005055 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005056 }
lucaslin1193a5d2021-01-21 02:04:15 +08005057 case EVENT_REPORT_NETWORK_ACTIVITY:
5058 mNetworkActivityTracker.handleReportNetworkActivity();
5059 break;
paulhu51f77dc2021-06-07 02:34:20 +00005060 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5061 handleMobileDataPreferredUidsChanged();
5062 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005063 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5064 final long timeMs = ((Long) msg.obj).longValue();
5065 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5066 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005067 }
5068 }
5069 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005070
Lorenzo Colittid6459092016-07-04 12:55:44 +09005071 @Override
markchien5776f962019-12-16 20:15:20 +08005072 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005073 public int getLastTetherError(String iface) {
markchien5776f962019-12-16 20:15:20 +08005074 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5075 Context.TETHERING_SERVICE);
5076 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005077 }
5078
Lorenzo Colittid6459092016-07-04 12:55:44 +09005079 @Override
markchien5776f962019-12-16 20:15:20 +08005080 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005081 public String[] getTetherableIfaces() {
markchien5776f962019-12-16 20:15:20 +08005082 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5083 Context.TETHERING_SERVICE);
5084 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005085 }
5086
Lorenzo Colittid6459092016-07-04 12:55:44 +09005087 @Override
markchien5776f962019-12-16 20:15:20 +08005088 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005089 public String[] getTetheredIfaces() {
markchien5776f962019-12-16 20:15:20 +08005090 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5091 Context.TETHERING_SERVICE);
5092 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005093 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005094
markchien5776f962019-12-16 20:15:20 +08005095
Lorenzo Colittid6459092016-07-04 12:55:44 +09005096 @Override
markchien5776f962019-12-16 20:15:20 +08005097 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005098 public String[] getTetheringErroredIfaces() {
markchien5776f962019-12-16 20:15:20 +08005099 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5100 Context.TETHERING_SERVICE);
5101
5102 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005103 }
5104
Lorenzo Colittid6459092016-07-04 12:55:44 +09005105 @Override
markchien5776f962019-12-16 20:15:20 +08005106 @Deprecated
5107 public String[] getTetherableUsbRegexs() {
5108 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5109 Context.TETHERING_SERVICE);
5110
5111 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005112 }
5113
Udam Saini8f7d6a72017-06-07 12:06:28 -07005114 @Override
markchien5776f962019-12-16 20:15:20 +08005115 @Deprecated
5116 public String[] getTetherableWifiRegexs() {
5117 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5118 Context.TETHERING_SERVICE);
5119 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005120 }
5121
Robert Greenwalte0b00512014-07-02 09:59:16 -07005122 // Called when we lose the default network and have no replacement yet.
5123 // This will automatically be cleared after X seconds or a new default network
5124 // becomes CONNECTED, whichever happens first. The timer is started by the
5125 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005126 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005127 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005128 if (mNetTransitionWakeLock.isHeld()) {
5129 return;
5130 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005131 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005132 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5133 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005134 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005135 mWakelockLogs.log("ACQUIRE for " + forWhom);
5136 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005137 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005138 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005139 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005140 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005141
Hugo Benichi471b62a2017-03-30 23:18:10 +09005142 // Called when we gain a new default network to release the network transition wakelock in a
5143 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5144 // message is cancelled.
5145 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005146 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005147 if (!mNetTransitionWakeLock.isHeld()) {
5148 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005149 }
5150 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005151 // Cancel self timeout on wakelock hold.
5152 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5153 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5154 mHandler.sendMessageDelayed(msg, 1000);
5155 }
5156
5157 // Called when either message of ensureNetworkTransitionWakelock or
5158 // scheduleReleaseNetworkTransitionWakelock is processed.
5159 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5160 String event = eventName(eventId);
5161 synchronized (this) {
5162 if (!mNetTransitionWakeLock.isHeld()) {
5163 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005164 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005165 return;
5166 }
5167 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005168 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5169 mTotalWakelockDurationMs += lockDuration;
5170 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5171 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005172 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005173 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005174 }
5175
Robert Greenwalt986c7412010-09-08 15:24:47 -07005176 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005177 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005178 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005179 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005180 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005181 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005182 }
5183
Lorenzo Colittid6459092016-07-04 12:55:44 +09005184 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005185 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005186 enforceAccessPermission();
5187 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005188 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005189 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005190
5191 final NetworkAgentInfo nai;
5192 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005193 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005194 } else {
5195 nai = getNetworkAgentInfoForNetwork(network);
5196 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005197
5198 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005199 mHandler.obtainMessage(
5200 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005201 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005202
Hugo Benichid6b510a2017-04-06 17:22:18 +09005203 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005204 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005205 if (nai == null
5206 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005207 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005208 return;
5209 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005210 // Revalidate if the app report does not match our current validated state.
Hugo Benichie9d321b2017-04-06 16:01:44 +09005211 if (hasConnectivity == nai.lastValidated) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005212 mConnectivityDiagnosticsHandler.sendMessage(
5213 mConnectivityDiagnosticsHandler.obtainMessage(
5214 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5215 new ReportedNetworkConnectivityInfo(
5216 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005217 return;
5218 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005219 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005220 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005221 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005222 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005223 // Validating a network that has not yet connected could result in a call to
5224 // rematchNetworkAndRequests() which is not meant to work on such networks.
5225 if (!nai.everConnected) {
5226 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005227 }
paulhu7aeba372020-12-30 00:42:19 +08005228 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5229 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005230 return;
5231 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005232
5233 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5234 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5235 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5236 // completed.
5237 mConnectivityDiagnosticsHandler.sendMessage(
5238 mConnectivityDiagnosticsHandler.obtainMessage(
5239 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5240 new ReportedNetworkConnectivityInfo(
5241 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005242 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005243 }
5244
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005245 // TODO: call into netd.
5246 private boolean queryUserAccess(int uid, Network network) {
5247 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5248 if (nai == null) return false;
5249
5250 // Any UID can use its default network.
5251 if (nai == getDefaultNetworkForUid(uid)) return true;
5252
5253 // Privileged apps can use any network.
5254 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5255 return true;
5256 }
5257
5258 // An unprivileged UID can use a VPN iff the VPN applies to it.
5259 if (nai.isVPN()) {
5260 return nai.networkCapabilities.appliesToUid(uid);
5261 }
5262
5263 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5264 // sockets, i.e., if it is the owner.
5265 final NetworkAgentInfo vpn = getVpnForUid(uid);
5266 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5267 && uid != vpn.networkCapabilities.getOwnerUid()) {
5268 return false;
5269 }
5270
5271 // The UID's permission must be at least sufficient for the network. Since the restricted
5272 // permission was already checked above, that just leaves background networks.
5273 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5274 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5275 }
5276
5277 // Unrestricted network. Anyone gets to use it.
5278 return true;
5279 }
5280
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005281 /**
5282 * Returns information about the proxy a certain network is using. If given a null network, it
5283 * it will return the proxy for the bound network for the caller app or the default proxy if
5284 * none.
5285 *
5286 * @param network the network we want to get the proxy information for.
5287 * @return Proxy information if a network has a proxy configured, or otherwise null.
5288 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005289 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005290 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005291 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005292 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005293 if (network == null) {
5294 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005295 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005296 true);
5297 if (activeNetwork == null) {
5298 return null;
5299 }
5300 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005301 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005302 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5303 // caller may not have.
5304 return getLinkPropertiesProxyInfo(network);
5305 }
5306 // No proxy info available if the calling UID does not have network access.
5307 return null;
5308 }
5309
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005310
5311 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005312 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5313 if (nai == null) return null;
5314 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005315 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5316 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005317 }
5318 }
5319
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005320 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005321 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhudf23d662021-01-25 18:53:17 +08005322 PermissionUtils.enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005323 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005324 }
5325
Chalard Jean777e2e52018-06-07 18:02:37 +09005326 @Override
5327 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005328 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005329 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005330 }
5331
Jason Monk4d5e20f2014-04-25 15:00:09 -04005332 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005333 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005334 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005335 proxy = null;
5336 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005337 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005338 }
5339
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005340 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5341 // when any network changes proxy.
5342 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5343 // multi-network world where an app might be bound to a non-default network.
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005344 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensenc0618a62014-12-10 15:12:18 -05005345 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5346 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5347
Chalard Jean7d97afc2018-06-07 17:41:29 +09005348 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005349 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005350 }
5351 }
5352
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005353 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005354 final private HashMap<Uri, Integer> mUriEventMap;
5355 final private Context mContext;
5356 final private Handler mHandler;
5357
5358 SettingsObserver(Context context, Handler handler) {
5359 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005360 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005361 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005362 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005363 }
5364
Erik Kline05f2b402015-04-30 12:58:40 +09005365 void observe(Uri uri, int what) {
5366 mUriEventMap.put(uri, what);
5367 final ContentResolver resolver = mContext.getContentResolver();
5368 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005369 }
5370
5371 @Override
5372 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005373 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005374 }
5375
5376 @Override
5377 public void onChange(boolean selfChange, Uri uri) {
5378 final Integer what = mUriEventMap.get(uri);
5379 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005380 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005381 } else {
5382 loge("No matching event to send for URI=" + uri);
5383 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005384 }
5385 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005386
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005387 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005388 Log.d(TAG, s);
5389 }
5390
5391 private static void logw(String s) {
5392 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005393 }
5394
Daniel Brightf9e945b2020-06-15 16:10:01 -07005395 private static void logwtf(String s) {
5396 Log.wtf(TAG, s);
5397 }
5398
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005399 private static void logwtf(String s, Throwable t) {
5400 Log.wtf(TAG, s, t);
5401 }
5402
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005403 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005404 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005405 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005406
Hugo Benichi39621362017-02-11 17:04:43 +09005407 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005408 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005409 }
5410
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005411 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005412 * Return the information of all ongoing VPNs.
5413 *
5414 * <p>This method is used to update NetworkStatsService.
5415 *
5416 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08005417 */
junyulai2050bed2021-01-23 09:46:34 +08005418 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005419 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09005420 if (mLockdownEnabled) {
5421 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08005422 }
junyulai2050bed2021-01-23 09:46:34 +08005423 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005424 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08005425 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005426 if (info != null) {
5427 infoList.add(info);
5428 }
5429 }
junyulai2050bed2021-01-23 09:46:34 +08005430 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08005431 }
5432
5433 /**
5434 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00005435 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08005436 */
junyulai2050bed2021-01-23 09:46:34 +08005437 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005438 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08005439 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5440 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09005441 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5442 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5443 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08005444 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5445 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00005446 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00005447 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08005448 }
5449 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005450
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005451 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005452
5453 List<String> interfaces = new ArrayList<>();
5454 for (Network network : underlyingNetworks) {
5455 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5456 if (underlyingNai == null) continue;
5457 LinkProperties lp = underlyingNai.linkProperties;
5458 for (String iface : lp.getAllInterfaceNames()) {
5459 if (!TextUtils.isEmpty(iface)) {
5460 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00005461 }
5462 }
Benedict Wong34857f82019-06-12 17:46:15 +00005463 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005464
5465 if (interfaces.isEmpty()) return null;
5466
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005467 // Must be non-null or NetworkStatsService will crash.
5468 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5469 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08005470 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08005471 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005472
junyulai2050bed2021-01-23 09:46:34 +08005473 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5474 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08005475 }
5476
James Mattisd31bdfa2020-12-23 16:37:26 -08005477 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08005478 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5479 Network[] underlyingNetworks) {
5480 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005481 if (underlyingNetworks == null && defaultNetwork != null) {
5482 // null underlying networks means to track the default.
5483 underlyingNetworks = new Network[] { defaultNetwork };
5484 }
5485 return underlyingNetworks;
5486 }
5487
5488 // Returns true iff |network| is an underlying network of |nai|.
5489 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5490 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5491 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09005492 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08005493 final Network[] underlying = underlyingNetworksOrDefault(
5494 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005495 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005496 }
5497
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005498 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005499 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005500 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005501 * When underlying networks change, such networks may have to update capabilities to reflect
5502 * things like the metered bit, their transports, and so on. The capabilities are calculated
5503 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005504 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005505 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005506 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005507 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005508 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005509 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005510 }
5511 }
5512 }
5513
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005514 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5515 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5516 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5517 // a VPN is not up.
5518 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5519 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5520 for (UidRange range : blockedUidRanges) {
5521 if (range.contains(uid)) return true;
5522 }
5523 return false;
5524 }
5525
5526 @Override
5527 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08005528 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005529 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5530 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5531 }
5532
5533 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5534 if (DBG) {
5535 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5536 + Arrays.toString(ranges));
5537 }
5538 // Cannot use a Set since the list of UID ranges might contain duplicates.
5539 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5540 for (int i = 0; i < ranges.length; i++) {
5541 if (requireVpn) {
5542 newVpnBlockedUidRanges.add(ranges[i]);
5543 } else {
5544 newVpnBlockedUidRanges.remove(ranges[i]);
5545 }
5546 }
5547
5548 try {
5549 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5550 } catch (RemoteException | ServiceSpecificException e) {
5551 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5552 + Arrays.toString(ranges) + "): netd command failed: " + e);
5553 }
5554
5555 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5556 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00005557 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5558 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005559 }
5560
5561 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5562 }
5563
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07005564 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005565 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08005566 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005567 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01005568 }
5569
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005570 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5571 return mLockdownEnabled
5572 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5573 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00005574 }
5575
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005576 private NetworkAgentInfo getLegacyLockdownNai() {
5577 if (!mLockdownEnabled) {
5578 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005579 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005580 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005581 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5582 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005583
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005584 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005585 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5586 // a local variable. There is no need to make a copy because its contents cannot change.
5587 final Network[] underlying = nai.declaredUnderlyingNetworks;
5588 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005589 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005590 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005591
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005592 // The legacy lockdown VPN always uses the default network.
5593 // If the VPN's underlying network is no longer the current default network, it means that
5594 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005595 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5596 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005597 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005598 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005599 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005600 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005601
5602 return nai;
5603 };
5604
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005605 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5606 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5607 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005608 private DetailedState getLegacyLockdownState(DetailedState origState) {
5609 if (origState != DetailedState.CONNECTED) {
5610 return origState;
5611 }
5612 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5613 ? DetailedState.CONNECTING
5614 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005615 }
5616
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005617 private void filterForLegacyLockdown(NetworkInfo ni) {
5618 if (!mLockdownEnabled || !ni.isConnected()) return;
5619 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5620 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5621 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5622 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5623 // network, this time with a state of CONNECTED.
5624 //
5625 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5626 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5627 // is not too far off the truth, since an always-on VPN, when not connected, is always
5628 // trying to reconnect.
5629 if (getLegacyLockdownNai() == null) {
5630 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5631 }
5632 }
5633
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005634 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005635 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04005636 String action) {
paulhu8e96a752019-08-12 16:25:11 +08005637 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09005638 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5639 return;
5640 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04005641 final long ident = Binder.clearCallingIdentity();
5642 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09005643 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09005644 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09005645 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04005646 } finally {
5647 Binder.restoreCallingIdentity(ident);
5648 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005649 }
Wink Savillecb117d32013-08-29 14:57:08 -07005650
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005651 @Override
5652 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01005653 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005654 final long ident = Binder.clearCallingIdentity();
5655 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005656 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09005657 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005658 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5659 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08005660 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005661 } finally {
5662 Binder.restoreCallingIdentity(ident);
5663 }
5664 }
5665
James Mattis02220e22021-03-13 19:27:21 -08005666 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005667 mPermissionMonitor.onUserAdded(user);
James Mattisae9aeb02021-03-01 17:09:11 -08005668 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5669 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5670 }
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005671 }
5672
James Mattis02220e22021-03-13 19:27:21 -08005673 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005674 mPermissionMonitor.onUserRemoved(user);
Chalard Jean0f57a492021-03-09 21:09:20 +09005675 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005676 handleSetProfileNetworkPreference(
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08005677 List.of(new ProfileNetworkPreferenceList.Preference(user, null, true)),
Chalard Jean0f57a492021-03-09 21:09:20 +09005678 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08005679 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5680 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5681 }
junyulaid91e7052020-08-28 13:44:33 +08005682 }
5683
James Mattis02220e22021-03-13 19:27:21 -08005684 private void onPackageChanged(@NonNull final String packageName) {
5685 // This is necessary in case a package is added or removed, but also when it's replaced to
5686 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5687 // as one in the preferences, then it should follow the same routing as that other package,
5688 // which means updating the rules is never to be needed in this case (whether it joins or
5689 // leaves a UID with a preference).
5690 if (isMappedInOemNetworkPreference(packageName)) {
5691 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5692 }
5693 }
5694
5695 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005696 @Override
5697 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09005698 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005699 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005700 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08005701
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005702 // User should be filled for below intents, check the existence.
5703 if (user == null) {
5704 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5705 return;
5706 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005707
Lorenzo Colitticd675292021-02-04 17:32:07 +09005708 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005709 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005710 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005711 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09005712 } else {
junyulaid91e7052020-08-28 13:44:33 +08005713 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005714 }
5715 }
5716 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07005717
James Mattis02220e22021-03-13 19:27:21 -08005718 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5719 @Override
5720 public void onReceive(Context context, Intent intent) {
5721 ensureRunningOnConnectivityServiceThread();
5722 switch (intent.getAction()) {
5723 case Intent.ACTION_PACKAGE_ADDED:
5724 case Intent.ACTION_PACKAGE_REMOVED:
5725 case Intent.ACTION_PACKAGE_REPLACED:
5726 onPackageChanged(intent.getData().getSchemeSpecificPart());
5727 break;
5728 default:
5729 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5730 }
5731 }
5732 };
5733
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005734 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005735 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005736
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005737 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005738 public final String name;
5739 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005740 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005741 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005742
lifraf3a3492021-03-10 13:58:14 +08005743 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5744 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005745 this.name = name;
5746 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005747 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005748 mDeathRecipient = deathRecipient;
5749
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005750 if (mDeathRecipient == null) {
5751 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005752 }
5753 }
5754
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005755 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005756 try {
5757 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5758 } catch (RemoteException e) {
5759 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005760 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005761 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005762 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005763
James Mattis4fce5d12020-11-12 15:53:42 -08005764 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
5765 for (int i = 0; i < requests.size(); i++) {
5766 ensureNetworkRequestHasType(requests.get(i));
5767 }
5768 }
5769
Lorenzo Colitti70964d32016-07-05 01:22:13 +09005770 private void ensureNetworkRequestHasType(NetworkRequest request) {
5771 if (request.type == NetworkRequest.Type.NONE) {
5772 throw new IllegalArgumentException(
5773 "All NetworkRequests in ConnectivityService must have a type");
5774 }
5775 }
5776
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005777 /**
5778 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08005779 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005780 */
James Mattis258ea3c2020-11-15 15:04:40 -08005781 @VisibleForTesting
5782 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08005783 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
5784 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08005785 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08005786
James Mattisa076c532020-12-02 14:12:41 -08005787 // mSatisfier and mActiveRequest rely on one another therefore set them together.
5788 void setSatisfier(
5789 @Nullable final NetworkAgentInfo satisfier,
5790 @Nullable final NetworkRequest activeRequest) {
5791 mSatisfier = satisfier;
5792 mActiveRequest = activeRequest;
5793 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005794
James Mattisd31bdfa2020-12-23 16:37:26 -08005795 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005796 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09005797 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08005798 private NetworkAgentInfo mSatisfier;
5799 NetworkAgentInfo getSatisfier() {
5800 return mSatisfier;
5801 }
5802
5803 // The request in mRequests assigned to a network agent. This is null if none of the
5804 // requests in mRequests can be satisfied. This member has the constraint of only being
5805 // accessible on the handler thread.
5806 @Nullable
5807 private NetworkRequest mActiveRequest;
5808 NetworkRequest getActiveRequest() {
5809 return mActiveRequest;
5810 }
5811
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005812 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08005813 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08005814 @Nullable
5815 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005816
5817 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08005818 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005819 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005820 final int mPid;
5821 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08005822 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005823 @Nullable
5824 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005825
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005826 // Counter keeping track of this NRI.
5827 final PerUidCounter mPerUidCounter;
5828
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005829 // Effective UID of this request. This is different from mUid when a privileged process
5830 // files a request on behalf of another UID. This UID is used to determine blocked status,
5831 // UID matching, and so on. mUid above is used for permission checks and to enforce the
5832 // maximum limit of registered callbacks per UID.
5833 final int mAsUid;
5834
paulhu48291862021-07-14 14:53:57 +08005835 // Preference order of this request.
5836 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08005837
James Mattis3ce3d3c2021-02-09 18:18:28 -08005838 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
5839 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
5840 // maintained for keying off of. This is only a concern when the original nri
5841 // mNetworkRequests changes which happens currently for apps that register callbacks to
5842 // track the default network. In those cases, the nri is updated to have mNetworkRequests
5843 // that match the per-app default nri that currently tracks the calling app's uid so that
5844 // callbacks are fired at the appropriate time. When the callbacks fire,
5845 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
5846 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
5847 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
5848 @NonNull
5849 private final NetworkRequest mNetworkRequestForCallback;
5850 NetworkRequest getNetworkRequestForCallback() {
5851 return mNetworkRequestForCallback;
5852 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005853
James Mattisd31bdfa2020-12-23 16:37:26 -08005854 /**
5855 * Get the list of UIDs this nri applies to.
5856 */
5857 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00005858 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08005859 // networkCapabilities.getUids() returns a defensive copy.
5860 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00005861 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
5862 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08005863 }
5864
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005865 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
5866 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08005867 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08005868 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08005869 }
5870
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005871 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08005872 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08005873 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005874 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08005875 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08005876 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005877 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08005878 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005879 mBinder = null;
5880 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005881 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005882 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005883 mPerUidCounter = getRequestCounter(this);
5884 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005885 /**
5886 * Location sensitive data not included in pending intent. Only included in
5887 * {@link NetworkCallback}.
5888 */
5889 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005890 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08005891 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005892 }
5893
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005894 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08005895 @Nullable final IBinder binder,
5896 @NetworkCallback.Flag int callbackFlags,
5897 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005898 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
5899 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08005900 }
5901
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005902 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08005903 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08005904 @Nullable final IBinder binder,
5905 @NetworkCallback.Flag int callbackFlags,
5906 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005907 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08005908 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08005909 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08005910 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08005911 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005912 mBinder = binder;
5913 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005914 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005915 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005916 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005917 mPerUidCounter = getRequestCounter(this);
5918 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005919 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005920 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08005921 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07005922 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005923 }
5924
James Mattis3ce3d3c2021-02-09 18:18:28 -08005925 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
5926 @NonNull final List<NetworkRequest> r) {
5927 super();
5928 ensureAllNetworkRequestsHaveType(r);
5929 mRequests = initializeRequests(r);
5930 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005931 final NetworkAgentInfo satisfier = nri.getSatisfier();
5932 if (null != satisfier) {
5933 // If the old NRI was satisfied by an NAI, then it may have had an active request.
5934 // The active request is necessary to figure out what callbacks to send, in
5935 // particular then a network updates its capabilities.
5936 // As this code creates a new NRI with a new set of requests, figure out which of
5937 // the list of requests should be the active request. It is always the first
5938 // request of the list that can be satisfied by the satisfier since the order of
5939 // requests is a priority order.
5940 // Note even in the presence of a satisfier there may not be an active request,
5941 // when the satisfier is the no-service network.
5942 NetworkRequest activeRequest = null;
5943 for (final NetworkRequest candidate : r) {
5944 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
5945 activeRequest = candidate;
5946 break;
5947 }
5948 }
5949 setSatisfier(satisfier, activeRequest);
5950 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08005951 mMessenger = nri.mMessenger;
5952 mBinder = nri.mBinder;
5953 mPid = nri.mPid;
5954 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005955 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08005956 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09005957 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005958 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005959 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08005960 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08005961 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07005962 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08005963 }
5964
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005965 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08005966 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08005967 }
5968
paulhue9913722021-05-26 15:19:20 +08005969 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08005970 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08005971 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08005972 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08005973 }
5974
James Mattis2516da32021-01-31 17:06:19 -08005975 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
5976 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
5977 // false.
5978 boolean isBeingSatisfied() {
5979 return (null != mSatisfier && null != mActiveRequest);
5980 }
5981
James Mattis3d229892020-11-16 16:46:28 -08005982 boolean isMultilayerRequest() {
5983 return mRequests.size() > 1;
5984 }
5985
James Mattis45d81842021-01-10 14:24:24 -08005986 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
5987 // Creating a defensive copy to prevent the sender from modifying the list being
5988 // reflected in the return value of this method.
5989 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08005990 return Collections.unmodifiableList(tempRequests);
5991 }
5992
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005993 void decrementRequestCount() {
5994 mPerUidCounter.decrementCount(mUid);
5995 }
5996
James Mattisb1392002021-03-31 13:57:52 -07005997 void linkDeathRecipient() {
5998 if (null != mBinder) {
5999 try {
6000 mBinder.linkToDeath(this, 0);
6001 } catch (RemoteException e) {
6002 binderDied();
6003 }
6004 }
6005 }
6006
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006007 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006008 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006009 try {
6010 mBinder.unlinkToDeath(this, 0);
6011 } catch (NoSuchElementException e) {
6012 // Temporary workaround for b/194394697 pending analysis of additional logs
6013 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6014 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006015 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006016 }
6017
paulhu48291862021-07-14 14:53:57 +08006018 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6019 // Compare two preference orders.
6020 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006021 }
6022
paulhu48291862021-07-14 14:53:57 +08006023 int getPreferenceOrderForNetd() {
6024 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6025 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6026 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006027 }
paulhu48291862021-07-14 14:53:57 +08006028 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006029 }
6030
James Mattis4fce5d12020-11-12 15:53:42 -08006031 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006032 public void binderDied() {
6033 log("ConnectivityService NetworkRequestInfo binderDied(" +
Chalard Jean524f0b12021-10-25 21:11:56 +09006034 "uid/pid:" + mUid + "/" + mPid + ", " + mRequests + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09006035 // As an immutable collection, mRequests cannot change by the time the
6036 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6037 // is acceptable. Use handleReleaseNetworkRequest and not directly
6038 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6039 // the app already unregistered the request.
6040 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6041 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006042 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006043
James Mattis4fce5d12020-11-12 15:53:42 -08006044 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006045 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006046 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6047 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006048 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006049 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006050 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006051 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006052 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006053 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006054 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006055 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006056 }
6057
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006058 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
6059 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
6060 if (badCapability != null) {
6061 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenee52d232015-06-16 15:11:58 -04006062 }
6063 }
6064
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006065 // This checks that the passed capabilities either do not request a
6066 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006067 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006068 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006069 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006070 throw new SecurityException("Insufficient permissions to request a specific SSID");
6071 }
paulhu1a407652019-03-22 16:35:06 +08006072
6073 if (nc.hasSignalStrength()
6074 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6075 throw new SecurityException(
6076 "Insufficient permissions to request a specific signal strength");
6077 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006078 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006079
junyulai2217bec2021-04-14 23:33:31 +08006080 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006081 enforceNetworkFactoryPermission();
6082 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006083 }
6084
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006085 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006086 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006087 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006088 // mNetworkRequests may contain the same value multiple times in case of
6089 // multilayer requests. It won't matter in this case because the thresholds
6090 // will then be the same and be deduplicated as they enter the `thresholds` set.
6091 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006092 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6093 for (final NetworkRequest req : nri.mRequests) {
6094 if (req.networkCapabilities.hasSignalStrength()
6095 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6096 thresholds.add(req.networkCapabilities.getSignalStrength());
6097 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006098 }
6099 }
6100 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006101 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006102 }
6103
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006104 private void updateSignalStrengthThresholds(
6105 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006106 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006107
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006108 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006109 String detail;
6110 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6111 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6112 } else {
6113 detail = reason;
6114 }
6115 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006116 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006117 }
6118
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006119 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006120 }
6121
Etan Cohen1b6d4182017-04-03 17:42:34 -07006122 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
6123 if (nc == null) {
6124 return;
6125 }
6126 NetworkSpecifier ns = nc.getNetworkSpecifier();
6127 if (ns == null) {
6128 return;
6129 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006130 if (ns instanceof MatchAllNetworkSpecifier) {
6131 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6132 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006133 }
6134
lucasline117e2e2019-10-22 18:27:33 +08006135 private void ensureValid(NetworkCapabilities nc) {
6136 ensureValidNetworkSpecifier(nc);
6137 if (nc.isPrivateDnsBroken()) {
6138 throw new IllegalArgumentException("Can't request broken private DNS");
6139 }
6140 }
6141
Chiachang Wang3bc52762021-11-25 14:17:57 +08006142 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6143 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006144 private boolean isTargetSdkAtleast(int version, int callingUid,
6145 @NonNull String callingPackageName) {
6146 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006147 final PackageManager pm =
6148 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006149 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006150 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006151 if (callingVersion < version) return false;
6152 } catch (PackageManager.NameNotFoundException e) { }
6153 return true;
6154 }
6155
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006156 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006157 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006158 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006159 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006160 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006161 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006162 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6163 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006164 throw new SecurityException("Insufficient permissions to specify legacy type");
6165 }
markchienfac84a22020-03-18 21:16:15 +08006166 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006167 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006168 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006169 // Privileged callers can track the default network of another UID by passing in a UID.
6170 if (asUid != Process.INVALID_UID) {
6171 enforceSettingsPermission();
6172 } else {
6173 asUid = callingUid;
6174 }
junyulaiad010792021-01-11 16:53:38 +08006175 final NetworkRequest.Type reqType;
6176 try {
6177 reqType = NetworkRequest.Type.values()[reqTypeInt];
6178 } catch (ArrayIndexOutOfBoundsException e) {
6179 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6180 }
6181 switch (reqType) {
6182 case TRACK_DEFAULT:
6183 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006184 // is unused and will be replaced by ones appropriate for the UID (usually, the
6185 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006186 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006187 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006188 enforceAccessPermission();
6189 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006190 case TRACK_SYSTEM_DEFAULT:
6191 enforceSettingsPermission();
6192 networkCapabilities = new NetworkCapabilities(defaultNc);
6193 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006194 case BACKGROUND_REQUEST:
6195 enforceNetworkStackOrSettingsPermission();
6196 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006197 case REQUEST:
6198 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6199 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6200 callingAttributionTag);
6201 // TODO: this is incorrect. We mark the request as metered or not depending on
6202 // the state of the app when the request is filed, but we never change the
6203 // request if the app changes network state. http://b/29964605
6204 enforceMeteredApnPolicy(networkCapabilities);
6205 break;
junyulai1b1c8742021-03-12 20:05:08 +08006206 case LISTEN_FOR_BEST:
6207 enforceAccessPermission();
6208 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6209 break;
junyulaiad010792021-01-11 16:53:38 +08006210 default:
6211 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006212 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006213 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006214 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006215 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006216
junyulai1b1c8742021-03-12 20:05:08 +08006217 // Enforce FOREGROUND if the caller does not have permission to use background network.
6218 if (reqType == LISTEN_FOR_BEST) {
6219 restrictBackgroundRequestForCaller(networkCapabilities);
6220 }
6221
6222 // Set the UID range for this request to the single UID of the requester, unless the
6223 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006224 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6225 // are no visible methods to set the UIDs, an app could use reflection to try and get
6226 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006227 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006228 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6229 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006230
Etan Cohen85000162017-02-05 10:42:27 -08006231 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006232 throw new IllegalArgumentException("Bad timeout specified");
6233 }
lucasline117e2e2019-10-22 18:27:33 +08006234 ensureValid(networkCapabilities);
Etan Cohen9786d922015-11-18 10:56:15 -08006235
James Mattis3ce3d3c2021-02-09 18:18:28 -08006236 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006237 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006238 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006239 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006240 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006241 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006242
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006243 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6244 // copied from the default request above. (This is necessary to ensure, for example, that
6245 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6246 // changes don't alter request matching.
6247 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6248 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006249 throw new IllegalStateException(
6250 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006251 + networkCapabilities + " vs. " + defaultNc);
6252 }
6253
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006254 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006255 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006256 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006257 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006258 }
6259 return networkRequest;
6260 }
6261
James Mattis3ce3d3c2021-02-09 18:18:28 -08006262 /**
6263 * Return the nri to be used when registering a network request. Specifically, this is used with
6264 * requests registered to track the default request. If there is currently a per-app default
6265 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6266 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006267 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6268 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006269 * @param nr the network request for the nri.
6270 * @param msgr the messenger for the nri.
6271 * @param binder the binder for the nri.
6272 * @param callingAttributionTag the calling attribution tag for the nri.
6273 * @return the nri to register.
6274 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006275 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006276 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006277 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006278 @Nullable String callingAttributionTag) {
6279 final List<NetworkRequest> requests;
6280 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6281 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006282 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006283 } else {
6284 requests = Collections.singletonList(nr);
6285 }
Roshan Pius951c0032020-12-22 15:10:42 -08006286 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006287 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006288 }
6289
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006290 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
6291 String callingPackageName, String callingAttributionTag) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006292 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichibd0cc762016-07-19 15:59:27 +09006293 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006294 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006295 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006296 }
6297 }
6298
fenglu3f357402015-03-20 11:29:56 -07006299 @Override
fenglub00f4882015-04-21 17:12:05 -07006300 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006301 enforceAccessPermission();
6302 NetworkAgentInfo nai = null;
6303 if (network == null) {
6304 return false;
6305 }
6306 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006307 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006308 }
6309 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006310 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006311 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006312 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006313 Integer uidReqs = mBandwidthRequests.get(uid);
6314 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006315 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006316 }
6317 mBandwidthRequests.put(uid, ++uidReqs);
6318 }
fenglu3f357402015-03-20 11:29:56 -07006319 return true;
6320 }
6321 return false;
6322 }
6323
Felipe Leme0a5ae422016-06-20 16:36:29 -07006324 private boolean isSystem(int uid) {
6325 return uid < Process.FIRST_APPLICATION_UID;
6326 }
fenglu3f357402015-03-20 11:29:56 -07006327
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006328 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006329 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006330 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006331 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006332 return;
6333 }
Hugo Benichi39621362017-02-11 17:04:43 +09006334 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6335 // Policy already enforced.
6336 return;
6337 }
paulhuaf50d7d2020-12-24 19:47:34 +08006338 final long ident = Binder.clearCallingIdentity();
6339 try {
6340 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6341 // If UID is restricted, don't allow them to bring up metered APNs.
6342 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6343 }
6344 } finally {
6345 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006346 }
6347 }
6348
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006349 @Override
6350 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006351 PendingIntent operation, @NonNull String callingPackageName,
6352 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006353 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006354 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006355 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006356 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6357 callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006358 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006359 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006360 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006361 Binder.getCallingPid(), callingUid, callingPackageName);
Etan Cohen1b6d4182017-04-03 17:42:34 -07006362 ensureValidNetworkSpecifier(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006363 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6364 callingUid, callingPackageName);
Etan Cohen89134542017-04-03 12:17:51 -07006365
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006366 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006367 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006368 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6369 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006370 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006371 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6372 nri));
6373 return networkRequest;
6374 }
6375
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006376 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6377 mHandler.sendMessageDelayed(
6378 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006379 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006380 }
6381
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006382 @Override
6383 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006384 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006385 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006386 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006387 }
6388
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006389 // In order to implement the compatibility measure for pre-M apps that call
6390 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6391 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6392 // This ensures it has permission to do so.
6393 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6394 if (nc == null) {
6395 return false;
6396 }
6397 int[] transportTypes = nc.getTransportTypes();
6398 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6399 return false;
6400 }
6401 try {
6402 mContext.enforceCallingOrSelfPermission(
6403 android.Manifest.permission.ACCESS_WIFI_STATE,
6404 "ConnectivityService");
6405 } catch (SecurityException e) {
6406 return false;
6407 }
6408 return true;
6409 }
6410
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006411 @Override
6412 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08006413 Messenger messenger, IBinder binder,
6414 @NetworkCallback.Flag int callbackFlags,
6415 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006416 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006417 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6418 enforceAccessPermission();
6419 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006420
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006421 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006422 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006423 Binder.getCallingPid(), callingUid, callingPackageName);
6424 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09006425 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6426 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6427 // onLost and onAvailable callbacks when networks move in and out of the background.
6428 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6429 // can't request networks.
6430 restrictBackgroundRequestForCaller(nc);
lucasline117e2e2019-10-22 18:27:33 +08006431 ensureValid(nc);
Etan Cohen89134542017-04-03 12:17:51 -07006432
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006433 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006434 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08006435 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006436 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08006437 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006438 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006439
6440 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6441 return networkRequest;
6442 }
6443
6444 @Override
6445 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08006446 PendingIntent operation, @NonNull String callingPackageName,
6447 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006448 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006449 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04006450 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6451 enforceAccessPermission();
6452 }
lucasline117e2e2019-10-22 18:27:33 +08006453 ensureValid(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006454 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006455 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006456 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006457 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006458
6459 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006460 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006461 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6462 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006463 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04006464
WeiZhang1cc3f172021-06-03 19:02:04 -05006465 mHandler.sendMessage(mHandler.obtainMessage(
6466 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006467 }
6468
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006469 /** Returns the next Network provider ID. */
6470 public final int nextNetworkProviderId() {
6471 return mNextNetworkProviderId.getAndIncrement();
6472 }
6473
Erik Kline0c04b742016-07-07 16:50:58 +09006474 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006475 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006476 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09006477 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006478 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006479 }
6480
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006481 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6482 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006483 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6484 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6485 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08006486 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006487 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006488 return;
6489 }
6490
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006491 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6492 mNetworkProviderInfos.put(npi.messenger, npi);
6493 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006494 }
6495
6496 @Override
6497 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006498 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08006499 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006500 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08006501 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006502 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6503 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006504 }
6505
6506 @Override
6507 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006508 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006509 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006510 }
6511
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006512 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09006513 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006514 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6515 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09006516 Objects.requireNonNull(score);
6517 Objects.requireNonNull(caps);
6518 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09006519 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006520 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09006521 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
6522 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006523 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6524 }
6525
Chalard Jeanbb902a52021-08-18 01:35:19 +09006526 private void updateOfferScore(final NetworkOffer offer) {
6527 final boolean yieldToBadWiFi =
6528 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
6529 final NetworkOffer newOffer = new NetworkOffer(
6530 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
6531 offer.caps, offer.callback, offer.providerId);
6532 if (offer.equals(newOffer)) return;
6533 handleRegisterNetworkOffer(newOffer);
6534 }
6535
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006536 @Override
6537 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6538 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6539 }
6540
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006541 private void handleUnregisterNetworkProvider(Messenger messenger) {
6542 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6543 if (npi == null) {
6544 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006545 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006546 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006547 // Unregister all the offers from this provider
6548 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6549 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09006550 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006551 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6552 toRemove.add(noi);
6553 }
6554 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09006555 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006556 handleUnregisterNetworkOffer(noi);
6557 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006558 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006559 }
6560
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006561 @Override
James Mattisf7027322020-12-13 16:28:14 -08006562 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006563 if (request.hasTransport(TRANSPORT_TEST)) {
6564 enforceNetworkFactoryOrTestNetworksPermission();
6565 } else {
6566 enforceNetworkFactoryPermission();
6567 }
James Mattisf7027322020-12-13 16:28:14 -08006568 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6569 if (nri != null) {
6570 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6571 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6572 mHandler.post(() -> handleReleaseNetworkRequest(
6573 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6574 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006575 }
6576
Paul Jensen1f567382015-02-13 14:18:39 -05006577 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6578 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006579 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05006580 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006581 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05006582 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006583 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006584
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09006585 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05006586 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006587 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006588
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006589 // UID ranges for users that are currently blocked by VPNs.
6590 // This array is accessed and iterated on multiple threads without holding locks, so its
6591 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6592 // (on the handler thread).
6593 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6594
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006595 // Must only be accessed on the handler thread
6596 @NonNull
6597 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6598
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006599 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006600 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006601
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006602 // Current OEM network preferences. This object must only be written to on the handler thread.
6603 // Since it is immutable and always non-null, other threads may read it if they only care
6604 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08006605 @NonNull
6606 private OemNetworkPreferences mOemNetworkPreferences =
6607 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006608 // Current per-profile network preferences. This object follows the same threading rules as
6609 // the OEM network preferences above.
6610 @NonNull
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006611 private ProfileNetworkPreferenceList mProfileNetworkPreferences =
6612 new ProfileNetworkPreferenceList();
James Mattis45d81842021-01-10 14:24:24 -08006613
paulhu51f77dc2021-06-07 02:34:20 +00006614 // A set of UIDs that should use mobile data preferentially if available. This object follows
6615 // the same threading rules as the OEM network preferences above.
6616 @NonNull
6617 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
6618
James Mattiscb1e0362021-04-06 17:07:42 -07006619 // OemNetworkPreferences activity String log entries.
6620 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6621 @NonNull
6622 private final LocalLog mOemNetworkPreferencesLogs =
6623 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6624
James Mattis02220e22021-03-13 19:27:21 -08006625 /**
6626 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6627 * @param packageName the package name to check existence of a mapping for.
6628 * @return true if a mapping exists, false otherwise
6629 */
6630 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6631 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6632 }
6633
James Mattise3ef1912020-12-20 11:09:58 -08006634 // The always-on request for an Internet-capable network that apps without a specific default
6635 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08006636 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09006637 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006638 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08006639 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08006640 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08006641 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006642 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006643
James Mattisd31bdfa2020-12-23 16:37:26 -08006644 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6645 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6646 }
6647
6648 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08006649 * Return the default network request currently tracking the given uid.
6650 * @param uid the uid to check.
6651 * @return the NetworkRequestInfo tracking the given uid.
6652 */
6653 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08006654 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08006655 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006656 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006657 // Checking the first request is sufficient as only multilayer requests will have more
6658 // than one request and for multilayer, all requests will track the same uids.
6659 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08006660 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08006661 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08006662 highestPriorityNri = nri;
6663 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006664 }
6665 }
paulhuaa0743d2021-05-26 21:56:03 +08006666 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006667 }
6668
6669 /**
6670 * Get a copy of the network requests of the default request that is currently tracking the
6671 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006672 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6673 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006674 * @param requestorUid the uid to check the default for.
6675 * @param requestorPackageName the requestor's package name.
6676 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6677 */
6678 @NonNull
6679 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006680 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006681 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006682 getDefaultRequestTrackingUid(asUid).mRequests,
6683 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006684 }
6685
6686 /**
6687 * Copy the given nri's NetworkRequest collection.
6688 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006689 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6690 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006691 * @param requestorUid the uid to set on the copied collection.
6692 * @param requestorPackageName the package name to set on the copied collection.
6693 * @return the copied NetworkRequest collection.
6694 */
6695 @NonNull
6696 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006697 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6698 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006699 final List<NetworkRequest> requests = new ArrayList<>();
6700 for (final NetworkRequest nr : requestsToCopy) {
6701 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006702 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08006703 nr.legacyType, nextNetworkRequestId(), nr.type));
6704 }
6705 return requests;
6706 }
6707
6708 @NonNull
6709 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006710 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6711 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09006712 // These capabilities are for a TRACK_DEFAULT callback, so:
6713 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6714 // mDefaultRequest and a per-UID default request.
6715 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006716 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09006717 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006718 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6719 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006720 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006721 restrictRequestUidsForCallerAndSetRequestorInfo(
6722 netCap, requestorUid, requestorPackageName);
6723 return netCap;
6724 }
6725
6726 /**
6727 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6728 * @param nr the network request to check for equality against.
6729 * @return the nri if one exists, null otherwise.
6730 */
6731 @Nullable
6732 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6733 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6734 if (nri.getNetworkRequestForCallback().equals(nr)) {
6735 return nri;
6736 }
6737 }
6738 return null;
6739 }
6740
6741 /**
6742 * Check if an nri is currently being managed by per-app default networking.
6743 * @param nri the nri to check.
6744 * @return true if this nri is currently being managed by per-app default networking.
6745 */
6746 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
6747 // nri.mRequests.get(0) is only different from the original request filed in
6748 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
6749 // functionality therefore if these two don't match, it means this particular nri is
6750 // currently being managed by a per-app default.
6751 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
6752 }
6753
6754 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08006755 * Determine if an nri is a managed default request that disallows default networking.
6756 * @param nri the request to evaluate
6757 * @return true if device-default networking is disallowed
6758 */
6759 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
6760 // Check if this nri is a managed default that supports the default network at its
6761 // lowest priority request.
6762 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
6763 final NetworkCapabilities lowestPriorityNetCap =
6764 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
6765 return isPerAppDefaultRequest(nri)
6766 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
6767 lowestPriorityNetCap));
6768 }
6769
Erik Kline05f2b402015-04-30 12:58:40 +09006770 // Request used to optionally keep mobile data active even when higher
6771 // priority networks like Wi-Fi are active.
6772 private final NetworkRequest mDefaultMobileDataRequest;
6773
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006774 // Request used to optionally keep wifi data active even when higher
6775 // priority networks like ethernet are active.
6776 private final NetworkRequest mDefaultWifiRequest;
6777
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08006778 // Request used to optionally keep vehicle internal network always active
6779 private final NetworkRequest mDefaultVehicleRequest;
6780
James Mattisd31bdfa2020-12-23 16:37:26 -08006781 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
6782 // network with no service. This NAI should never be matched against, nor should any public API
6783 // ever return the associated network. For this reason, this NAI is not in the list of available
6784 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
6785 // default requests that don't support using the device default network which will ultimately
6786 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
6787 @VisibleForTesting
6788 final NetworkAgentInfo mNoServiceNetwork;
6789
Chalard Jean5b409c72021-02-04 13:12:59 +09006790 // The NetworkAgentInfo currently satisfying the default request, if any.
6791 private NetworkAgentInfo getDefaultNetwork() {
6792 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09006793 }
6794
James Mattis2516da32021-01-31 17:06:19 -08006795 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08006796 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08006797 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6798 // Currently, all network requests will have the same uids therefore checking the first
6799 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006800 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08006801 if (null == uids) {
6802 continue;
6803 }
6804 for (final UidRange range : uids) {
6805 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08006806 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08006807 highestPriorityNri = nri;
6808 }
James Mattis2516da32021-01-31 17:06:19 -08006809 }
6810 }
6811 }
paulhuaa0743d2021-05-26 21:56:03 +08006812 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08006813 }
6814
Varun Ananddf569952019-02-06 10:13:38 -08006815 @Nullable
6816 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
6817 return nai != null ? nai.network : null;
6818 }
6819
6820 private void ensureRunningOnConnectivityServiceThread() {
6821 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
6822 throw new IllegalStateException(
6823 "Not running on ConnectivityService thread: "
6824 + Thread.currentThread().getName());
6825 }
6826 }
6827
Chalard Jean3a3f5f22019-04-10 23:07:55 +09006828 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09006829 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
6830 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006831 }
6832
Chalard Jean29d06db2018-05-02 21:14:54 +09006833 /**
6834 * Register a new agent with ConnectivityService to handle a network.
6835 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006836 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09006837 * @param networkInfo the initial info associated with this network. It can be updated later :
6838 * see {@link #updateNetworkInfo}.
6839 * @param linkProperties the initial link properties of this network. They can be updated
6840 * later : see {@link #updateLinkProperties}.
6841 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09006842 * later : see {@link #updateCapabilities}.
Chalard Jean28018572020-12-21 18:36:52 +09006843 * @param initialScore the initial score of the network. See
Chalard Jean29d06db2018-05-02 21:14:54 +09006844 * {@link NetworkAgentInfo#getCurrentScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006845 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006846 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09006847 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09006848 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006849 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09006850 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09006851 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
6852 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09006853 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
6854 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
6855 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09006856 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09006857 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09006858 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6859 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006860 } else {
6861 enforceNetworkFactoryPermission();
6862 }
6863
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006864 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006865 final long token = Binder.clearCallingIdentity();
6866 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006867 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09006868 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006869 } finally {
6870 Binder.restoreCallingIdentity(token);
6871 }
6872 }
6873
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006874 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006875 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09006876 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
6877 int uid) {
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006878 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
Chalard Jean5b639762020-03-09 21:25:37 +09006879 // Strictly, sanitizing here is unnecessary as the capabilities will be sanitized in
6880 // the call to mixInCapabilities below anyway, but sanitizing here means the NAI never
6881 // sees capabilities that may be malicious, which might prevent mistakes in the future.
6882 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Chiachang Wangc07315a2021-08-10 15:13:39 +08006883 networkCapabilities.restrictCapabilitiesForTestNetwork(uid);
Chalard Jean5b639762020-03-09 21:25:37 +09006884 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006885
Rubin Xuffd77d82017-09-05 18:40:49 +01006886 LinkProperties lp = new LinkProperties(linkProperties);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006887
Chalard Jeana23bc9e2018-01-30 22:41:41 +09006888 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006889 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006890 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo), lp, nc,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09006891 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09006892 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
6893 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006894
6895 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006896 processCapabilitiesFromAgent(nai, nc);
Chalard Jean05edd052019-11-22 22:39:56 +09006897 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006898 processLinkPropertiesFromAgent(nai, nai.linkProperties);
6899
Chalard Jeanf2da1772018-04-26 16:16:10 +09006900 final String extraInfo = networkInfo.getExtraInfo();
6901 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09006902 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07006903 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006904 mDeps.getNetworkStack().makeNetworkMonitor(
6905 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006906 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
6907 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006908 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006909 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09006910 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006911 }
6912
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006913 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
6914 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006915 if (VDBG) log("Got NetworkAgent Messenger");
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006916 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05006917 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006918 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05006919 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006920
6921 try {
6922 networkMonitor.start();
6923 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08006924 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006925 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006926 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09006927 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09006928 updateNetworkInfo(nai, networkInfo);
6929 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006930 }
6931
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006932 private class NetworkOfferInfo implements IBinder.DeathRecipient {
6933 @NonNull public final NetworkOffer offer;
6934
6935 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
6936 this.offer = offer;
6937 }
6938
6939 @Override
6940 public void binderDied() {
6941 mHandler.post(() -> handleUnregisterNetworkOffer(this));
6942 }
6943 }
6944
Chalard Jeandd35f2d2021-03-24 14:31:38 +09006945 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
6946 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
6947 if (npi.providerId == providerId) return true;
6948 }
6949 return false;
6950 }
6951
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006952 /**
6953 * Register or update a network offer.
6954 * @param newOffer The new offer. If the callback member is the same as an existing
6955 * offer, it is an update of that offer.
6956 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09006957 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006958 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
6959 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09006960 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006961 // This may actually happen if a provider updates its score or registers and then
6962 // immediately unregisters. The offer would still be in the handler queue, but the
6963 // provider would have been removed.
6964 if (DBG) log("Received offer from an unregistered provider");
6965 return;
6966 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006967 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
6968 if (null != existingOffer) {
6969 handleUnregisterNetworkOffer(existingOffer);
6970 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09006971 if (DBG) {
6972 // handleUnregisterNetworkOffer has already logged the old offer
6973 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
6974 }
6975 } else {
6976 if (DBG) {
6977 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
6978 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006979 }
6980 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
6981 try {
Chalard Jean30689b82021-03-22 22:44:02 +09006982 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006983 } catch (RemoteException e) {
6984 noi.binderDied();
6985 return;
6986 }
6987 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09006988 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006989 }
6990
6991 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
6992 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09006993 if (DBG) {
6994 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
6995 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07006996
6997 // If the provider removes the offer and dies immediately afterwards this
6998 // function may be called twice in a row, but the array will no longer contain
6999 // the offer.
7000 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007001 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007002 }
7003
7004 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7005 @NonNull final INetworkOfferCallback callback) {
7006 ensureRunningOnConnectivityServiceThread();
7007 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007008 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007009 }
7010 return null;
7011 }
7012
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007013 /**
7014 * Called when receiving LinkProperties directly from a NetworkAgent.
7015 * Stores into |nai| any data coming from the agent that might also be written to the network's
7016 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7017 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007018 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007019 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007020 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7021 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007022 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007023 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007024 }
7025
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007026 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007027 @NonNull LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007028 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007029
Lorenzo Colittid523d142020-04-01 20:16:30 +09007030 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7031 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7032 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007033 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007034
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007035 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007036
7037 // update filtering rules, need to happen after the interface update so netd knows about the
7038 // new interface (the interface name -> index map becomes initialized)
7039 updateVpnFiltering(newLp, oldLp, networkAgent);
7040
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007041 updateMtu(newLp, oldLp);
7042 // TODO - figure out what to do for clat
7043// for (LinkProperties lp : newLp.getStackedLinks()) {
7044// updateMtu(lp, null);
7045// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007046 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007047 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7048 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007049
Erik Klineb9888902016-04-05 13:30:49 +09007050 updateRoutes(newLp, oldLp, netId);
7051 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007052 // Make sure LinkProperties represents the latest private DNS status.
7053 // This does not need to be done before updateDnses because the
7054 // LinkProperties are not the source of the private DNS configuration.
7055 // updateDnses will fetch the private DNS configuration from DnsManager.
7056 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007057
Chalard Jean5b409c72021-02-04 13:12:59 +09007058 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007059 handleApplyDefaultProxy(newLp.getHttpProxy());
7060 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007061 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007062 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007063
7064 updateWakeOnLan(newLp);
7065
Hai Shalome58bdc62021-01-11 18:45:34 -08007066 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7067 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7068 // does, it needs to be merged here.
7069 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7070 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007071
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007072 // TODO - move this check to cover the whole function
7073 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007074 synchronized (networkAgent) {
7075 networkAgent.linkProperties = newLp;
7076 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007077 // Start or stop DNS64 detection and 464xlat according to network state.
7078 networkAgent.clatd.update();
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08007079 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007080 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7081 new LinkProperties(newLp, true /* parcelSensitiveFields */));
lucaslin74fa3972018-11-28 12:51:55 +08007082 if (networkAgent.everConnected) {
7083 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
7084 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007085 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007086
7087 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007088 }
7089
Hai Shalome58bdc62021-01-11 18:45:34 -08007090 /**
7091 * @param naData captive portal data from NetworkAgent
7092 * @param apiData captive portal data from capport API
7093 */
7094 @Nullable
7095 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7096 CaptivePortalData apiData) {
7097 if (naData == null || apiData == null) {
7098 return naData == null ? apiData : naData;
7099 }
7100 final CaptivePortalData.Builder captivePortalBuilder =
7101 new CaptivePortalData.Builder(naData);
7102
7103 if (apiData.isCaptive()) {
7104 captivePortalBuilder.setCaptive(true);
7105 }
7106 if (apiData.isSessionExtendable()) {
7107 captivePortalBuilder.setSessionExtendable(true);
7108 }
7109 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7110 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7111 // otherwise data would be inconsistent. Prefer the capport API info if present,
7112 // as it can generally be refreshed more often.
7113 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7114 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7115 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7116 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7117 // No source has time / bytes remaining information: surface the newest refresh time
7118 // for other fields
7119 captivePortalBuilder.setRefreshTime(
7120 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7121 }
7122
Hai Shalom7c6ab402021-02-04 19:34:06 -08007123 // Prioritize the user portal URL from the network agent if the source is authenticated.
7124 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7125 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7126 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7127 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007128 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007129 // Prioritize the venue information URL from the network agent if the source is
7130 // authenticated.
7131 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7132 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7133 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7134 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007135 }
7136 return captivePortalBuilder.build();
7137 }
7138
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007139 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007140 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007141 // marks on unsupported interfaces is harmless.
7142 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7143 return;
7144 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007145
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007146 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7147 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7148
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007149 // Mask/mark of zero will not detect anything interesting.
7150 // Don't install rules unless both values are nonzero.
7151 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007152 return;
7153 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007154
7155 final String prefix = "iface:" + iface;
7156 try {
7157 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007158 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007159 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007160 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007161 }
7162 } catch (Exception e) {
7163 loge("Exception modifying wakeup packet monitoring: " + e);
7164 }
7165
Joel Scherpelza235a812017-05-22 13:47:41 +09007166 }
7167
Chalard Jean9589e722019-11-19 19:03:53 +09007168 private void updateInterfaces(final @Nullable LinkProperties newLp,
7169 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007170 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09007171 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fa7d9e2017-08-22 16:35:52 +01007172 oldLp != null ? oldLp.getAllInterfaceNames() : null,
7173 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jean9589e722019-11-19 19:03:53 +09007174 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007175 for (final String iface : interfaceDiff.added) {
7176 try {
7177 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007178 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09007179 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007180 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7181 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007182 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007183 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007184 }
Paul Jensenbff73492014-04-28 10:33:11 -04007185 }
7186 }
Chalard Jean9589e722019-11-19 19:03:53 +09007187 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007188 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007189 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007190 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007191 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007192 } catch (Exception e) {
7193 loge("Exception removing interface: " + e);
7194 }
7195 }
7196 }
7197
Tyler Weare4314862019-12-05 14:55:30 -08007198 // TODO: move to frameworks/libs/net.
7199 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7200 final String nextHop;
7201
7202 switch (route.getType()) {
7203 case RouteInfo.RTN_UNICAST:
7204 if (route.hasGateway()) {
7205 nextHop = route.getGateway().getHostAddress();
7206 } else {
7207 nextHop = INetd.NEXTHOP_NONE;
7208 }
7209 break;
7210 case RouteInfo.RTN_UNREACHABLE:
7211 nextHop = INetd.NEXTHOP_UNREACHABLE;
7212 break;
7213 case RouteInfo.RTN_THROW:
7214 nextHop = INetd.NEXTHOP_THROW;
7215 break;
7216 default:
7217 nextHop = INetd.NEXTHOP_NONE;
7218 break;
7219 }
7220
7221 final RouteInfoParcel rip = new RouteInfoParcel();
7222 rip.ifName = route.getInterface();
7223 rip.destination = route.getDestination().toString();
7224 rip.nextHop = nextHop;
7225 rip.mtu = route.getMtu();
7226
7227 return rip;
7228 }
7229
Paul Jensene0fd4a82014-08-06 15:51:33 -04007230 /**
7231 * Have netd update routes from oldLp to newLp.
7232 * @return true if routes changed between oldLp and newLp
7233 */
7234 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007235 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007236 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7237 new CompareOrUpdateResult<>(
7238 oldLp != null ? oldLp.getAllRoutes() : null,
7239 newLp != null ? newLp.getAllRoutes() : null,
7240 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007241
7242 // add routes before removing old in case it helps with continuous connectivity
7243
Chalard Jean9dd11612018-06-04 16:52:49 +09007244 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007245 for (RouteInfo route : routeDiff.added) {
7246 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007247 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007248 try {
Tyler Weare4314862019-12-05 14:55:30 -08007249 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007250 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007251 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007252 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007253 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007254 }
7255 }
7256 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007257 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007258 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007259 try {
Tyler Weare4314862019-12-05 14:55:30 -08007260 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007261 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007262 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007263 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007264 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007265 }
7266 }
7267
7268 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007269 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007270 try {
Tyler Weare4314862019-12-05 14:55:30 -08007271 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007272 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007273 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007274 }
7275 }
Tyler Weare4314862019-12-05 14:55:30 -08007276
7277 for (RouteInfo route : routeDiff.updated) {
7278 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7279 try {
7280 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7281 } catch (Exception e) {
7282 loge("Exception in networkUpdateRouteParcel: " + e);
7283 }
7284 }
7285 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7286 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007287 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007288
Erik Klineb9888902016-04-05 13:30:49 +09007289 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7290 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7291 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007292 }
Erik Klineb9888902016-04-05 13:30:49 +09007293
Erik Kline31b4a9e2018-01-11 21:07:29 +09007294 if (DBG) {
7295 final Collection<InetAddress> dnses = newLp.getDnsServers();
7296 log("Setting DNS servers for network " + netId + " to " + dnses);
7297 }
Erik Klineb9888902016-04-05 13:30:49 +09007298 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007299 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007300 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007301 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007302 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007303 }
Erik Kline54e35c02017-04-07 15:29:29 +09007304 }
7305
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007306 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7307 NetworkAgentInfo nai) {
7308 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
7309 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
7310 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
7311 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
7312
7313 if (!wasFiltering && !needsFiltering) {
7314 // Nothing to do.
7315 return;
7316 }
7317
7318 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7319 // Nothing changed.
7320 return;
7321 }
7322
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007323 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Qingxi Libb8da982020-01-17 17:54:27 -08007324 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007325 // TODO: this create a window of opportunity for apps to receive traffic between the time
7326 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007327 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007328 // old rules are being removed.
7329 if (wasFiltering) {
7330 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7331 }
7332 if (needsFiltering) {
7333 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7334 }
7335 }
7336
Valentin Iftime9fa35092019-09-24 13:32:13 +02007337 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007338 if (mWolSupportedInterfaces == null) {
7339 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007340 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007341 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007342 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7343 }
7344
Luke Huangb913c812018-08-24 20:33:16 +08007345 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007346 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007347 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007348 }
7349 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007350 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007351 }
Luke Huangb913c812018-08-24 20:33:16 +08007352 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007353 }
7354
Chalard Jean62edfd82019-12-02 18:39:29 +09007355 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7356 @NonNull final NetworkCapabilities newNc) {
7357 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7358 final int newPermission = getNetworkPermission(newNc);
7359 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7360 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007361 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08007362 } catch (RemoteException | ServiceSpecificException e) {
7363 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09007364 }
7365 }
7366 }
7367
Paul Jensen53f08952015-06-16 14:27:36 -04007368 /**
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007369 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7370 * Stores into |nai| any data coming from the agent that might also be written to the network's
7371 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7372 * agent is not lost when updateCapabilities is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007373 * This method should never alter the agent's NetworkCapabilities, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007374 */
7375 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007376 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7377 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7378 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7379 // the owner UID here and behave as if the agent had never tried to change it.
Lorenzo Colitti93401342020-12-09 18:30:52 +09007380 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7381 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7382 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7383 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7384 }
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007385 nai.declaredCapabilities = new NetworkCapabilities(nc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007386 }
7387
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007388 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007389 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09007390 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007391 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08007392 underlyingNetworks = underlyingNetworksOrDefault(
7393 agentCaps.getOwnerUid(), underlyingNetworks);
lifrade6c2a2021-03-04 14:08:08 +08007394 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007395 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7396 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007397 // metered if any underlying is metered, or originally declared metered by the agent.
7398 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007399 boolean roaming = false; // roaming if any underlying is roaming
7400 boolean congested = false; // congested if any underlying is congested
7401 boolean suspended = true; // suspended if all underlying are suspended
7402
7403 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08007404 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007405 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08007406 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007407 for (Network underlyingNetwork : underlyingNetworks) {
7408 final NetworkAgentInfo underlying =
7409 getNetworkAgentInfoForNetwork(underlyingNetwork);
7410 if (underlying == null) continue;
7411
7412 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7413 hadUnderlyingNetworks = true;
7414 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007415 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007416 }
7417
7418 // Merge capabilities of this underlying network. For bandwidth, assume the
7419 // worst case.
7420 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7421 underlyingCaps.getLinkDownstreamBandwidthKbps());
7422 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7423 underlyingCaps.getLinkUpstreamBandwidthKbps());
7424 // If this underlying network is metered, the VPN is metered (it may cost money
7425 // to send packets on this network).
7426 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7427 // If this underlying network is roaming, the VPN is roaming (the billing structure
7428 // is different than the usual, local one).
7429 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7430 // If this underlying network is congested, the VPN is congested (the current
7431 // condition of the network affects the performance of this network).
7432 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7433 // If this network is not suspended, the VPN is not suspended (the VPN
7434 // is able to transfer some data).
7435 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08007436 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007437 }
7438 }
7439 if (!hadUnderlyingNetworks) {
7440 // No idea what the underlying networks are; assume reasonable defaults
7441 metered = true;
7442 roaming = false;
7443 congested = false;
7444 suspended = false;
7445 }
7446
lifrade6c2a2021-03-04 14:08:08 +08007447 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007448 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7449 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7450 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7451 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7452 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7453 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08007454 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007455 }
7456
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007457 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007458 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7459 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7460 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04007461 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007462 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007463 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09007464 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007465 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7466 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007467 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007468 // avoid connect/teardown loops.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007469 if (nai.everConnected &&
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007470 !nai.isVPN() &&
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007471 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7472 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09007473 // does not cause any request (that is not a listen) currently matching that agent to
7474 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007475 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09007476 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007477 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09007478 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007479 }
7480
Paul Jensen53f08952015-06-16 14:27:36 -04007481 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007482 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensende49eb12015-06-25 15:30:08 -04007483 if (nai.lastValidated) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007484 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007485 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007486 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007487 }
Paul Jensende49eb12015-06-25 15:30:08 -04007488 if (nai.lastCaptivePortalDetected) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007489 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007490 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007491 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007492 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007493 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007494 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007495 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007496 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007497 }
lucaslin2240ef62019-03-12 13:08:03 +08007498 if (nai.partialConnectivity) {
7499 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7500 } else {
7501 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7502 }
lucasline117e2e2019-10-22 18:27:33 +08007503 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007504
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007505 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09007506 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7507 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007508 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09007509 }
7510
Lorenzo Colittibd079452021-07-02 11:47:57 +09007511 if (nai.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007512 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7513 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007514 }
7515
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007516 return newNc;
7517 }
7518
Lorenzo Colitti44840702021-01-11 22:27:57 +09007519 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7520 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7521 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7522 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7523 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7524 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7525 if (prevSuspended != suspended) {
7526 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7527 // onResumed have been removed.
7528 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7529 : ConnectivityManager.CALLBACK_RESUMED);
7530 }
7531 if (prevSuspended != suspended || prevRoaming != roaming) {
7532 // updateNetworkInfo will mix in the suspended info from the capabilities and
7533 // take appropriate action for the network having possibly changed state.
7534 updateNetworkInfo(nai, nai.networkInfo);
7535 }
7536 }
7537
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007538 /**
7539 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7540 *
7541 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7542 * capabilities we manage and store in {@code nai}, such as validated status and captive
7543 * portal status)
7544 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7545 * potentially triggers rematches.
7546 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7547 * change.)
7548 *
7549 * @param oldScore score of the network before any of the changes that prompted us
7550 * to call this function.
7551 * @param nai the network having its capabilities updated.
7552 * @param nc the new network capabilities.
7553 */
Chalard Jean62edfd82019-12-02 18:39:29 +09007554 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7555 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007556 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007557 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean62edfd82019-12-02 18:39:29 +09007558 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09007559 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007560
Chalard Jeanb2a49912018-01-16 18:43:05 +09007561 updateUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09007562 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007563
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007564 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007565 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7566 // the change we're processing can't affect any requests, it can only affect the listens
7567 // on this network. We might have been called by rematchNetworkAndRequests when a
7568 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09007569 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007570 } else {
7571 // If the requestable capabilities have changed or the score changed, we can't have been
7572 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09007573 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04007574 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07007575 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09007576 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007577
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007578 final boolean oldMetered = prevNc.isMetered();
7579 final boolean newMetered = newNc.isMetered();
7580 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08007581
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007582 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00007583 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7584 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007585 }
junyulaif2c67e42018-08-07 19:50:45 +08007586
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007587 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7588 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08007589
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007590 // Report changes that are interesting for network statistics tracking.
7591 if (meteredChanged || roamingChanged) {
7592 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06007593 }
7594
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007595 // This network might have been underlying another network. Propagate its capabilities.
7596 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08007597
7598 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007599 mDnsManager.updateTransportsForNetwork(
7600 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08007601 }
lucaslin53e8a262021-06-08 01:43:59 +08007602
7603 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007604 }
7605
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007606 /** Convenience method to update the capabilities for a given network. */
7607 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7608 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7609 }
7610
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007611 /**
7612 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7613 * network.
7614 *
7615 * Ingress interface filtering enforces that all apps under the given network can only receive
7616 * packets from the network's interface (and loopback). This is important for VPNs because
7617 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7618 * non-VPN interfaces.
7619 *
7620 * As a result, this method should return true iff
7621 * 1. the network is an app VPN (not legacy VPN)
7622 * 2. the VPN does not allow bypass
7623 * 3. the VPN is fully-routed
7624 * 4. the VPN interface is non-null
7625 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007626 * @see INetd#firewallAddUidInterfaceRules
7627 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007628 */
7629 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7630 LinkProperties lp) {
7631 if (nc == null || lp == null) return false;
7632 return nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007633 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08007634 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007635 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08007636 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7637 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007638 }
7639
Chiachang Wang28afaff2020-12-10 22:24:47 +08007640 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7641 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7642 int index = 0;
7643 for (UidRange range : ranges) {
7644 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7645 index++;
7646 }
7647 return stableRanges;
7648 }
7649
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007650 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7651 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7652 for (int i = 0; i < ranges.length; i++) {
7653 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7654 }
7655 return stableRanges;
7656 }
7657
Ken Chen5e65a852020-12-24 12:59:10 +08007658 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7659 int[] exemptUids) {
7660 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7661 try {
7662 mNetd.socketDestroy(ranges, exemptUids);
7663 } catch (Exception e) {
7664 loge("Exception in socket destroy: ", e);
7665 }
7666 }
7667 }
7668
paulhuaa0743d2021-05-26 21:56:03 +08007669 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08007670 int[] exemptUids = new int[2];
7671 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7672 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7673 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7674 exemptUids[0] = VPN_UID;
7675 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7676 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7677
7678 maybeCloseSockets(nai, ranges, exemptUids);
7679 try {
7680 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08007681 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007682 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08007683 } else {
paulhu0e79d952021-06-09 16:11:35 +08007684 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007685 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08007686 }
7687 } catch (Exception e) {
7688 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7689 " on netId " + nai.network.netId + ". " + e);
7690 }
7691 maybeCloseSockets(nai, ranges, exemptUids);
7692 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007693
lucaslin53e8a262021-06-08 01:43:59 +08007694 private boolean isProxySetOnAnyDefaultNetwork() {
7695 ensureRunningOnConnectivityServiceThread();
7696 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7697 final NetworkAgentInfo nai = nri.getSatisfier();
7698 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
7699 return true;
7700 }
7701 }
7702 return false;
7703 }
7704
7705 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7706 NetworkCapabilities newNc) {
7707 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
7708 // the proxy might be changed since the default network satisfied by the apps might also
7709 // changed.
7710 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
7711 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09007712 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
7713 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
7714 if (nai.isVPN() && nai.everConnected && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08007715 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
7716 mProxyTracker.sendProxyBroadcast();
7717 }
7718 }
7719
Chalard Jeanb2a49912018-01-16 18:43:05 +09007720 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7721 NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007722 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7723 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007724 if (null == prevRanges) prevRanges = new ArraySet<>();
7725 if (null == newRanges) newRanges = new ArraySet<>();
7726 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
7727
7728 prevRanges.removeAll(newRanges);
7729 newRanges.removeAll(prevRangesCopy);
7730
7731 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007732 // When updating the VPN uid routing rules, add the new range first then remove the old
7733 // range. If old range were removed first, there would be a window between the old
7734 // range being removed and the new range being added, during which UIDs contained
7735 // in both ranges are not subject to any VPN routing rules. Adding new range before
7736 // removing old range works because, unlike the filtering rules below, it's possible to
7737 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08007738 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
7739 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
7740 // [1-5] & [1-2],[4-5] == [3]
7741 // Then we can do:
7742 // maybeCloseSockets([3])
7743 // mNetd.networkAddUidRanges([1-2],[4-5])
7744 // mNetd.networkRemoveUidRanges([1-5])
7745 // maybeCloseSockets([3])
7746 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
7747 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09007748 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08007749 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007750 }
7751 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08007752 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007753 }
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007754 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
7755 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
7756 final String iface = nai.linkProperties.getInterfaceName();
7757 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09007758 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007759 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
7760 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
7761 // were added first and then newRanges got removed later, there would be only one uid
7762 // 10013 left. A consequence of removing old ranges before adding new ranges is that
7763 // there is now a window of opportunity when the UIDs are not subject to any filtering.
7764 // Note that this is in contrast with the (more robust) update of VPN routing rules
7765 // above, where the addition of new ranges happens before the removal of old ranges.
7766 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
7767 // to be removed will never overlap with the new range to be added.
7768 if (wasFiltering && !prevRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08007769 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007770 }
7771 if (shouldFilter && !newRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08007772 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007773 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09007774 } catch (Exception e) {
7775 // Never crash!
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007776 loge("Exception in updateUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007777 }
7778 }
7779
Hugo Benichi9d35b752017-09-01 01:23:32 +00007780 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09007781 ensureRunningOnConnectivityServiceThread();
7782
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007783 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00007784 // Ignore updates for disconnected networks
7785 return;
7786 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007787 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09007788 log("Update of LinkProperties for " + nai.toShortString()
7789 + "; created=" + nai.created
7790 + "; everConnected=" + nai.everConnected);
Hugo Benichi9d35b752017-09-01 01:23:32 +00007791 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007792 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
7793 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08007794 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00007795 }
7796
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007797 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
7798 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007799 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007800 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08007801 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08007802 // If apps could file multi-layer requests with PendingIntents, they'd need to know
7803 // which of the layer is satisfied alongside with some ID for the request. Hence, if
7804 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09007805 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
7806 // need to be sent as a separate extra.
7807 final NetworkRequest req = nri.isMultilayerRequest()
7808 ? nri.getActiveRequest()
7809 // Non-multilayer listen requests do not have an active request
7810 : nri.mRequests.get(0);
7811 if (req == null) {
7812 Log.wtf(TAG, "No request in NRI " + nri);
7813 }
7814 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007815 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007816 sendIntent(nri.mPendingIntent, intent);
7817 }
7818 // else not handled
7819 }
7820
7821 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
7822 mPendingIntentWakeLock.acquire();
7823 try {
7824 if (DBG) log("Sending " + pendingIntent);
7825 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
7826 } catch (PendingIntent.CanceledException e) {
7827 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
7828 mPendingIntentWakeLock.release();
7829 releasePendingNetworkRequest(pendingIntent);
7830 }
7831 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
7832 }
7833
7834 @Override
7835 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
7836 String resultData, Bundle resultExtras) {
7837 if (DBG) log("Finished sending " + pendingIntent);
7838 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007839 // Release with a delay so the receiving client has an opportunity to put in its
7840 // own request.
7841 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007842 }
7843
James Mattis212df9e2020-12-03 19:57:41 -08007844 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
7845 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
7846 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08007847 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08007848 // Default request has no msgr. Also prevents callbacks from being invoked for
7849 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
7850 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
7851 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007852 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007853 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08007854 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007855 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007856 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08007857 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007858 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007859 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
7860 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007861 }
Roshan Pius951c0032020-12-22 15:10:42 -08007862 final boolean includeLocationSensitiveInfo =
7863 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007864 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09007865 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08007866 final NetworkCapabilities nc =
7867 networkCapabilitiesRestrictedForCallerPermissions(
7868 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7869 putParcelable(
7870 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08007871 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08007872 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08007873 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08007874 nri.mCallingAttributionTag));
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09007875 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7876 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08007877 // For this notification, arg1 contains the blocked status.
7878 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09007879 break;
7880 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007881 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007882 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007883 break;
7884 }
7885 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09007886 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08007887 final NetworkCapabilities netCap =
7888 networkCapabilitiesRestrictedForCallerPermissions(
7889 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7890 putParcelable(
7891 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08007892 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08007893 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08007894 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08007895 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007896 break;
7897 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007898 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09007899 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7900 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007901 break;
7902 }
junyulaif2c67e42018-08-07 19:50:45 +08007903 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09007904 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08007905 msg.arg1 = arg1;
7906 break;
7907 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007908 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007909 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007910 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007911 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007912 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09007913 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08007914 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007915 }
James Mattis45d81842021-01-10 14:24:24 -08007916 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007917 } catch (RemoteException e) {
7918 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08007919 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007920 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007921 }
7922
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007923 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
7924 bundle.putParcelable(t.getClass().getSimpleName(), t);
7925 }
7926
Chalard Jean0702f982021-09-16 21:50:07 +09007927 /**
7928 * Returns whether reassigning a request from an NAI to another can be done gracefully.
7929 *
7930 * When a request should be assigned to a new network, it is normally lingered to give
7931 * time for apps to gracefully migrate their connections. When both networks are on the same
7932 * radio, but that radio can't do time-sharing efficiently, this may end up being
7933 * counter-productive because any traffic on the old network may drastically reduce the
7934 * performance of the new network.
7935 * The stack supports a configuration to let modem vendors state that their radio can't
7936 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
7937 * from one cell network to another can't be done gracefully.
7938 *
7939 * @param oldNai the old network serving the request
7940 * @param newNai the new network serving the request
7941 * @return whether the switch can be graceful
7942 */
7943 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
7944 @NonNull final NetworkAgentInfo newSatisfier) {
7945 if (mCellularRadioTimesharingCapable) return true;
7946 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
7947 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
7948 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
7949 }
7950
Paul Jensenaf94b982014-09-30 15:37:41 -04007951 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09007952 if (nai.numRequestNetworkRequests() != 0) {
7953 for (int i = 0; i < nai.numNetworkRequests(); i++) {
7954 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007955 // Ignore listening and track default requests.
7956 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09007957 loge("Dead network still had at least " + nr);
7958 break;
7959 }
Paul Jensenaf94b982014-09-30 15:37:41 -04007960 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007961 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04007962 }
7963
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007964 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
7965 if (oldNetwork == null) {
7966 loge("Unknown NetworkAgentInfo in handleLingerComplete");
7967 return;
7968 }
Chalard Jean49707572019-12-10 21:07:02 +09007969 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007970
7971 // If we get here it means that the last linger timeout for this network expired. So there
7972 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08007973 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007974
Lorenzo Colitti2666be82016-09-09 18:48:56 +09007975 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007976 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007977 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007978 } else {
junyulai0ac374f2020-12-14 18:41:52 +08007979 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007980 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007981 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007982 }
7983
James Mattise3ef1912020-12-20 11:09:58 -08007984 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
7985 boolean isDefaultChanged = false;
7986 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
7987 final NetworkReassignment.RequestReassignment reassignment =
7988 changes.getReassignment(defaultRequestInfo);
7989 if (null == reassignment) {
7990 continue;
7991 }
7992 // reassignment only contains those instances where the satisfying network changed.
7993 isDefaultChanged = true;
7994 // Notify system services of the new default.
7995 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
7996 }
Chiachang Wang087fd272018-09-28 22:42:48 +08007997
James Mattise3ef1912020-12-20 11:09:58 -08007998 if (isDefaultChanged) {
7999 // Hold a wakelock for a short time to help apps in migrating to a new default.
8000 scheduleReleaseNetworkTransitionWakelock();
8001 }
8002 }
8003
8004 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8005 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8006 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8007 if (DBG) {
8008 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8009 }
Chalard Jean8e382112019-12-03 20:45:30 +09008010
James Mattisd31bdfa2020-12-23 16:37:26 -08008011 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8012 if (newDefaultNetwork != null) {
8013 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008014 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008015
James Mattisd31bdfa2020-12-23 16:37:26 -08008016 // Set an app level managed default and return since further processing only applies to the
8017 // default network.
8018 if (mDefaultRequest != nri) {
8019 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8020 return;
8021 }
8022
8023 makeDefaultNetwork(newDefaultNetwork);
8024
James Mattise3ef1912020-12-20 11:09:58 -08008025 if (oldDefaultNetwork != null) {
8026 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8027 }
8028 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008029 handleApplyDefaultProxy(null != newDefaultNetwork
8030 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8031 updateTcpBufferSizes(null != newDefaultNetwork
8032 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008033 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008034 }
8035
James Mattisd31bdfa2020-12-23 16:37:26 -08008036 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8037 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8038 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8039 try {
8040 if (VDBG) {
8041 log("Setting default network for " + nri
8042 + " using UIDs " + nri.getUids()
8043 + " with old network " + (oldDefaultNetwork != null
8044 ? oldDefaultNetwork.network().getNetId() : "null")
8045 + " and new network " + (newDefaultNetwork != null
8046 ? newDefaultNetwork.network().getNetId() : "null"));
8047 }
8048 if (nri.getUids().isEmpty()) {
8049 throw new IllegalStateException("makeDefaultForApps called without specifying"
8050 + " any applications to set as the default." + nri);
8051 }
8052 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008053 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008054 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008055 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008056 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008057 }
8058 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008059 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008060 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008061 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008062 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008063 }
8064 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008065 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008066 }
8067 }
8068
8069 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8070 try {
8071 if (null != newDefaultNetwork) {
8072 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8073 } else {
8074 mNetd.networkClearDefault();
8075 }
8076 } catch (RemoteException | ServiceSpecificException e) {
8077 loge("Exception setting default network :" + e);
8078 }
8079 }
8080
Chalard Jean05cbe972019-12-09 11:50:38 +09008081 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008082 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09008083 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09008084 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09008085 processNewlySatisfiedListenRequests(nai);
8086 }
8087
8088 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008089 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8090 if (nri.isMultilayerRequest()) {
8091 continue;
8092 }
8093 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008094 if (!nr.isListen()) continue;
8095 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08008096 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008097 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
8098 }
8099 }
Chalard Jeancd397a22019-11-22 22:33:33 +09008100 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008101
Chalard Jeancd397a22019-11-22 22:33:33 +09008102 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008103 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8104 if (nri.isMultilayerRequest()) {
8105 continue;
8106 }
8107 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008108 if (!nr.isListen()) continue;
8109 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
8110 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09008111 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008112 }
8113 }
8114 }
8115
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008116 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008117 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008118 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08008119 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09008120 @Nullable public final NetworkRequest mOldNetworkRequest;
8121 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008122 @Nullable public final NetworkAgentInfo mOldNetwork;
8123 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08008124 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008125 @Nullable final NetworkRequest oldNetworkRequest,
8126 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008127 @Nullable final NetworkAgentInfo oldNetwork,
8128 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008129 mNetworkRequestInfo = networkRequestInfo;
8130 mOldNetworkRequest = oldNetworkRequest;
8131 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008132 mOldNetwork = oldNetwork;
8133 mNewNetwork = newNetwork;
8134 }
Chalard Jean49707572019-12-10 21:07:02 +09008135
8136 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09008137 final NetworkRequest requestToShow = null != mNewNetworkRequest
8138 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
8139 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08008140 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
8141 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09008142 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008143 }
8144
Chalard Jean46a62372019-12-10 21:25:24 +09008145 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008146
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008147 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09008148 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008149 }
8150
8151 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09008152 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09008153 // The code is never supposed to add two reassignments of the same request. Make
8154 // sure this stays true, but without imposing this expensive check on all
8155 // reassignments on all user devices.
8156 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08008157 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09008158 throw new IllegalStateException("Trying to reassign ["
8159 + reassignment + "] but already have ["
8160 + existing + "]");
8161 }
8162 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09008163 }
Chalard Jean46a62372019-12-10 21:25:24 +09008164 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008165 }
8166
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008167 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09008168 // the passed request.
8169 @Nullable
8170 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008171 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008172 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008173 }
8174 return null;
8175 }
Chalard Jean49707572019-12-10 21:07:02 +09008176
8177 public String toString() {
8178 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8179 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09008180 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008181 for (final RequestReassignment rr : getRequestReassignments()) {
8182 sj.add(rr.toString());
8183 }
8184 return sj.toString();
8185 }
8186
8187 public String debugString() {
8188 final StringBuilder sb = new StringBuilder();
8189 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09008190 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008191 for (final RequestReassignment rr : getRequestReassignments()) {
8192 sb.append("\n ").append(rr);
8193 }
8194 return sb.append("\n").toString();
8195 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008196 }
8197
Chalard Jean24344d72019-12-04 13:32:31 +09008198 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008199 @Nullable final NetworkRequest previousRequest,
8200 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09008201 @Nullable final NetworkAgentInfo previousSatisfier,
8202 @Nullable final NetworkAgentInfo newSatisfier,
8203 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08008204 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09008205 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09008206 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008207 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008208 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09008209 }
James Mattisa076c532020-12-02 14:12:41 -08008210 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean0702f982021-09-16 21:50:07 +09008211 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)) {
8212 // If this network switch can't be supported gracefully, the request is not
8213 // lingered. This allows letting go of the network sooner to reclaim some
8214 // performance on the new network, since the radio can't do both at the same
8215 // time while preserving good performance.
8216 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8217 }
Chalard Jean24344d72019-12-04 13:32:31 +09008218 } else {
8219 if (VDBG || DDBG) log(" accepting network in place of null");
8220 }
junyulai0ac374f2020-12-14 18:41:52 +08008221
8222 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8223 // and immediately satisfies a request then remove the timer. This will happen for
8224 // all networks except in the case of an underlying network for a VCN.
8225 if (newSatisfier.isNascent()) {
8226 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08008227 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008228 }
8229
Chalard Jean5d6e23b2021-03-01 22:00:20 +09008230 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08008231 newSatisfier.unlingerRequest(newRequest.requestId);
8232 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008233 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08008234 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008235 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09008236 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008237 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008238 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08008239 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008240 }
James Mattisa076c532020-12-02 14:12:41 -08008241 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008242 }
James Mattisa076c532020-12-02 14:12:41 -08008243 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008244 }
8245
James Mattisa076c532020-12-02 14:12:41 -08008246 /**
8247 * This function is triggered when something can affect what network should satisfy what
8248 * request, and it computes the network reassignment from the passed collection of requests to
8249 * network match to the one that the system should now have. That data is encoded in an
8250 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8251 * satisfier.
8252 *
8253 * After the reassignment is computed, it is applied to the state objects.
8254 *
8255 * @param networkRequests the nri objects to evaluate for possible network reassignment
8256 * @return NetworkReassignment listing of proposed network assignment changes
8257 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008258 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08008259 private NetworkReassignment computeNetworkReassignment(
8260 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09008261 final NetworkReassignment changes = new NetworkReassignment();
8262
Chalard Jeanc81d4c32021-04-07 17:06:19 +09008263 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09008264 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008265 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattisa076c532020-12-02 14:12:41 -08008266 if (!nai.everConnected) {
8267 continue;
8268 }
Chalard Jean857a1712019-12-10 21:08:07 +09008269 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09008270 }
Chalard Jean857a1712019-12-10 21:08:07 +09008271
James Mattisa076c532020-12-02 14:12:41 -08008272 for (final NetworkRequestInfo nri : networkRequests) {
8273 // Non-multilayer listen requests can be ignored.
8274 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8275 continue;
8276 }
8277 NetworkAgentInfo bestNetwork = null;
8278 NetworkRequest bestRequest = null;
8279 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09008280 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08008281 // Stop evaluating as the highest possible priority request is satisfied.
8282 if (null != bestNetwork) {
8283 bestRequest = req;
8284 break;
8285 }
8286 }
James Mattisd31bdfa2020-12-23 16:37:26 -08008287 if (null == bestNetwork && isDefaultBlocked(nri)) {
8288 // Remove default networking if disallowed for managed default requests.
8289 bestNetwork = mNoServiceNetwork;
8290 }
8291 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09008292 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09008293 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08008294 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09008295 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008296 }
8297 return changes;
8298 }
8299
James Mattisa076c532020-12-02 14:12:41 -08008300 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8301 return new HashSet<>(mNetworkRequests.values());
8302 }
8303
Paul Jensenc88b39b2015-06-16 14:27:36 -04008304 /**
James Mattisa076c532020-12-02 14:12:41 -08008305 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04008306 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04008307 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008308 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08008309 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8310 }
8311
8312 /**
8313 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8314 * being disconnected.
8315 */
8316 private void rematchNetworksAndRequests(
8317 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8318 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09008319 // TODO: This may be slow, and should be optimized.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008320 final long now = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08008321 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jean49707572019-12-10 21:07:02 +09008322 if (VDBG || DDBG) {
8323 log(changes.debugString());
8324 } else if (DBG) {
8325 log(changes.toString()); // Shorter form, only one line of log
8326 }
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008327 applyNetworkReassignment(changes, now);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008328 issueNetworkNeeds();
Chalard Jeand7f762d2019-12-10 19:01:29 +09008329 }
Chalard Jean64520dc2019-12-04 19:55:32 +09008330
Chalard Jeand7f762d2019-12-10 19:01:29 +09008331 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008332 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008333 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09008334
8335 // Since most of the time there are only 0 or 1 background networks, it would probably
8336 // be more efficient to just use an ArrayList here. TODO : measure performance
8337 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8338 for (final NetworkAgentInfo nai : nais) {
8339 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8340 }
8341
Chalard Jeand7f762d2019-12-10 19:01:29 +09008342 // First, update the lists of satisfied requests in the network agents. This is necessary
8343 // because some code later depends on this state to be correct, most prominently computing
8344 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09008345 for (final NetworkReassignment.RequestReassignment event :
8346 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008347 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8348 event.mOldNetworkRequest, event.mNewNetworkRequest,
8349 event.mOldNetwork, event.mNewNetwork,
8350 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09008351 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008352
James Mattise3ef1912020-12-20 11:09:58 -08008353 // Process default network changes if applicable.
8354 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008355
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008356 // Notify requested networks are available after the default net is switched, but
8357 // before LegacyTypeTracker sends legacy broadcasts
8358 for (final NetworkReassignment.RequestReassignment event :
8359 changes.getRequestReassignments()) {
8360 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008361 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008362 } else {
James Mattisa076c532020-12-02 14:12:41 -08008363 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008364 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008365 }
8366 }
8367
junyulai0ac374f2020-12-14 18:41:52 +08008368 // Update the inactivity state before processing listen callbacks, because the background
8369 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008370 // just yet though, because they have to be sent after the listens are processed to keep
8371 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08008372 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09008373 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08008374 // Rematching may have altered the inactivity state of some networks, so update all
8375 // inactivity timers. updateInactivityState reads the state from the network agent
8376 // and does nothing if the state has not changed : the source of truth is controlled
8377 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8378 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08008379 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08008380 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008381 }
8382 }
8383
Chalard Jeanb10ab412019-12-11 14:12:30 +09008384 for (final NetworkAgentInfo nai : nais) {
8385 if (!nai.everConnected) continue;
8386 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008387 // Process listen requests and update capabilities if the background state has
8388 // changed for this network. For consistency with previous behavior, send onLost
8389 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09008390 processNewlyLostListenRequests(nai);
8391 if (oldBackground != nai.isBackgroundNetwork()) {
8392 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008393 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09008394 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008395 }
8396
junyulai0ac374f2020-12-14 18:41:52 +08008397 for (final NetworkAgentInfo nai : inactiveNetworks) {
8398 // For nascent networks, if connecting with no foreground request, skip broadcasting
8399 // LOSING for backward compatibility. This is typical when mobile data connected while
8400 // wifi connected with mobile data always-on enabled.
8401 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008402 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008403 }
8404
James Mattise3ef1912020-12-20 11:09:58 -08008405 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09008406
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008407 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008408 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008409 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08008410 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008411 // This network has active linger timers and no requests, but is not
8412 // lingering. Linger it.
8413 //
8414 // One way (the only way?) this can happen if this network is unvalidated
8415 // and became unneeded due to another network improving its score to the
8416 // point where this network will no longer be able to satisfy any requests
8417 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08008418 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008419 notifyNetworkLosing(nai, now);
8420 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09008421 } else {
Chalard Jean49707572019-12-10 21:07:02 +09008422 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09008423 teardownUnneededNetwork(nai);
8424 }
8425 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04008426 }
8427 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008428
Chalard Jean62edfd82019-12-02 18:39:29 +09008429 /**
8430 * Apply a change in background state resulting from rematching networks with requests.
8431 *
8432 * During rematch, a network may change background states by starting to satisfy or stopping
8433 * to satisfy a foreground request. Listens don't count for this. When a network changes
8434 * background states, its capabilities need to be updated and callbacks fired for the
8435 * capability change.
8436 *
8437 * @param nai The network that changed background states
8438 */
8439 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8440 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8441 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8442 updateNetworkPermissions(nai, newNc);
8443 nai.getAndSetNetworkCapabilities(newNc);
8444 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8445 }
8446
Chalard Jeanf0344532019-11-19 19:23:38 +09008447 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08008448 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008449 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09008450 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8451 changes.getReassignment(mDefaultRequest);
8452 final NetworkAgentInfo oldDefaultNetwork =
8453 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8454 final NetworkAgentInfo newDefaultNetwork =
8455 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08008456
Chalard Jean5b409c72021-02-04 13:12:59 +09008457 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008458 // Maintain the illusion : since the legacy API only understands one network at a time,
8459 // if the default network changed, apps should see a disconnected broadcast for the
8460 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09008461 if (oldDefaultNetwork != null) {
8462 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8463 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008464 }
Chalard Jean5b409c72021-02-04 13:12:59 +09008465 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008466 // The new default network can be newly null if and only if the old default
8467 // network doesn't satisfy the default request any more because it lost a
8468 // capability.
Chalard Jean5b409c72021-02-04 13:12:59 +09008469 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08008470 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09008471 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008472 }
8473 }
8474
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008475 // Now that all the callbacks have been sent, send the legacy network broadcasts
8476 // as needed. This is necessary so that legacy requests correctly bind dns
8477 // requests to this network. The legacy users are listening for this broadcast
8478 // and will generally do a dns request so they can ensureRouteToHost and if
8479 // they do that before the callbacks happen they'll use the default network.
8480 //
8481 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8482 // callbacks, but if apps can receive the broadcast before the callback, they still might
8483 // have an inconsistent view of networking.
8484 //
8485 // This *does* introduce a race where if the user uses the new api
8486 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8487 // they may get old info. Reverse this after the old startUsing api is removed.
8488 // This is on top of the multiple intent sequencing referenced in the todo above.
8489 for (NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008490 if (nai.everConnected) {
8491 addNetworkToLegacyTypeTracker(nai);
8492 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08008493 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008494 }
8495
Chalard Jean0354d8c2021-01-12 10:58:56 +09008496 private void issueNetworkNeeds() {
8497 ensureRunningOnConnectivityServiceThread();
8498 for (final NetworkOfferInfo noi : mNetworkOffers) {
8499 issueNetworkNeeds(noi);
8500 }
8501 }
8502
8503 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8504 ensureRunningOnConnectivityServiceThread();
8505 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8506 informOffer(nri, noi.offer, mNetworkRanker);
8507 }
8508 }
8509
8510 /**
8511 * Inform a NetworkOffer about any new situation of a request.
8512 *
8513 * This function handles updates to offers. A number of events may happen that require
8514 * updating the registrant for this offer about the situation :
8515 * • The offer itself was updated. This may lead the offer to no longer being able
8516 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8517 * or conversely being strengthened enough to beat the satisfier (and therefore
8518 * start being needed)
8519 * • The network satisfying a request changed (including cases where the request
8520 * starts or stops being satisfied). The new network may be a stronger or weaker
8521 * match than the old one, possibly affecting whether the offer is needed.
8522 * • The network satisfying a request updated their score. This may lead the offer
8523 * to no longer be able to beat it if the current satisfier got better, or
8524 * conversely start being a good choice if the current satisfier got weaker.
8525 *
8526 * @param nri The request
8527 * @param offer The offer. This may be an updated offer.
8528 */
8529 private static void informOffer(@NonNull NetworkRequestInfo nri,
8530 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
8531 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
8532 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09008533
8534 // Multi-layer requests have a currently active request, the one being satisfied.
8535 // Since the system will try to bring up a better network than is currently satisfying
8536 // the request, NetworkProviders need to be told the offers matching the requests *above*
8537 // the currently satisfied one are needed, that the ones *below* the satisfied one are
8538 // not needed, and the offer is needed for the active request iff the offer can beat
8539 // the satisfier.
8540 // For non-multilayer requests, the logic above gracefully degenerates to only the
8541 // last case.
8542 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
8543 // providers that the offer is needed for this request, until the active request is found.
8544 // In a second phase, deal with the currently active request. In a third phase, inform
8545 // the providers that offer is unneeded for the remaining requests.
8546
8547 // First phase : inform providers of all requests above the active request.
8548 int i;
8549 for (i = 0; nri.mRequests.size() > i; ++i) {
8550 final NetworkRequest request = nri.mRequests.get(i);
8551 if (activeRequest == request) break; // Found the active request : go to phase 2
8552 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8553 // Since this request is higher-priority than the one currently satisfied, if the
8554 // offer can satisfy it, the provider should try and bring up the network for sure ;
8555 // no need to even ask the ranker – an offer that can satisfy is always better than
8556 // no network. Hence tell the provider so unless it already knew.
8557 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
8558 offer.onNetworkNeeded(request);
8559 }
8560 }
8561
8562 // Second phase : deal with the active request (if any)
8563 if (null != activeRequest && activeRequest.isRequest()) {
8564 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00008565 // If an offer can satisfy the request, it is considered needed if it is currently
8566 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09008567 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00008568 && satisfier.factorySerialNumber == offer.providerId
8569 && activeRequest.canBeSatisfiedBy(offer.caps);
8570 final boolean newNeeded = currentlyServing
8571 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008572 if (newNeeded != oldNeeded) {
8573 if (newNeeded) {
8574 offer.onNetworkNeeded(activeRequest);
8575 } else {
8576 // The offer used to be able to beat the satisfier. Now it can't.
8577 offer.onNetworkUnneeded(activeRequest);
8578 }
8579 }
8580 }
8581
8582 // Third phase : inform the providers that the offer isn't needed for any request
8583 // below the active one.
8584 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
8585 final NetworkRequest request = nri.mRequests.get(i);
8586 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8587 // Since this request is lower-priority than the one currently satisfied, if the
8588 // offer can satisfy it, the provider should not try and bring up the network.
8589 // Hence tell the provider so unless it already knew.
8590 if (offer.neededFor(request)) {
8591 offer.onNetworkUnneeded(request);
8592 }
8593 }
8594 }
8595
Chalard Jean61c79252019-11-07 23:07:32 +09008596 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8597 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8598 NetworkRequest nr = nai.requestAt(i);
8599 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8600 // legacy type tracker filters out repeat adds
8601 mLegacyTypeTracker.add(nr.legacyType, nai);
8602 }
8603 }
8604
8605 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09008606 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09008607 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8608 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8609 if (nai.isVPN()) {
8610 mLegacyTypeTracker.add(TYPE_VPN, nai);
8611 }
8612 }
8613
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008614 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04008615 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittia8de5ca2014-12-17 11:14:42 +09008616 if (!nai.everValidated) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09008617 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04008618 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09008619 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008620
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008621 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008622 // Don't repeat publish.
8623 if (newInetCondition == mDefaultInetConditionPublished) return;
8624
8625 mDefaultInetConditionPublished = newInetCondition;
8626 sendInetConditionBroadcast(nai.networkInfo);
8627 }
8628
Chalard Jeand61375d2020-01-14 22:46:36 +09008629 @NonNull
8630 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8631 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008632 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09008633 final boolean suspended =
8634 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8635 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8636 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8637 // state. This is because the network could have been suspended before connecting,
8638 // or it could be disconnecting while being suspended, and in both these cases
8639 // the state should not be overridden. Note that the only detailed state that
8640 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8641 // worry about multiple different substates of CONNECTED.
8642 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8643 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08008644 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8645 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8646 // network agent is created, then goes to suspended, then goes out of suspended without
8647 // ever setting connected. Check if network agent is ever connected to update the state.
8648 newInfo.setDetailedState(nai.everConnected
8649 ? NetworkInfo.DetailedState.CONNECTED
8650 : NetworkInfo.DetailedState.CONNECTING,
8651 info.getReason(),
8652 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09008653 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008654 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09008655 return newInfo;
8656 }
8657
8658 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8659 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8660
Erik Kline99f301b2017-02-15 19:59:17 +09008661 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008662 NetworkInfo oldInfo = null;
8663 synchronized (networkAgent) {
8664 oldInfo = networkAgent.networkInfo;
8665 networkAgent.networkInfo = newInfo;
8666 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008667
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008668 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008669 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8670 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008671 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07008672
Robin Leea8c0b6e2016-05-01 23:00:00 +01008673 if (!networkAgent.created
8674 && (state == NetworkInfo.State.CONNECTED
8675 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008676
8677 // A network that has just connected has zero requests and is thus a foreground network.
8678 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8679
Luke Huangfdd11f82019-04-09 18:41:49 +08008680 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09008681 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008682 // Initialize the network's capabilities to their starting values according to the
8683 // underlying networks. This ensures that the capabilities are correct before
8684 // anything happens to the network.
8685 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09008686 }
Paul Jensen74940202014-08-04 12:21:19 -04008687 networkAgent.created = true;
Chiachang Wang3f6cc072021-03-24 18:39:17 +08008688 networkAgent.onNetworkCreated();
Robin Leea8c0b6e2016-05-01 23:00:00 +01008689 }
8690
8691 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
8692 networkAgent.everConnected = true;
8693
lucaslin45e639b2019-04-03 17:09:28 +08008694 // NetworkCapabilities need to be set before sending the private DNS config to
8695 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09008696 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
8697
Erik Kline9a62f012018-03-21 07:18:33 -07008698 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08008699 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
8700 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008701
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008702 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
8703 // command must be sent after updating LinkProperties to maximize chances of
8704 // NetworkMonitor seeing the correct LinkProperties when starting.
8705 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008706 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09008707 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008708 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09008709 networkAgent.networkMonitor().notifyNetworkConnected(
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008710 new LinkProperties(networkAgent.linkProperties,
8711 true /* parcelSensitiveFields */),
8712 networkAgent.networkCapabilities);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09008713 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008714
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008715 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
8716 // be communicated to a particular NetworkAgent depends only on the network's immutable,
8717 // capabilities, so it only needs to be done once on initial connect, not every time the
8718 // network's capabilities change. Note that we do this before rematching the network,
8719 // so we could decide to tear it down immediately afterwards. That's fine though - on
8720 // disconnection NetworkAgents should stop any signal strength monitoring they have been
8721 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09008722 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008723
junyulai0ac374f2020-12-14 18:41:52 +08008724 // Before first rematching networks, put an inactivity timer without any request, this
8725 // allows {@code updateInactivityState} to update the state accordingly and prevent
8726 // tearing down for any {@code unneeded} evaluation in this period.
8727 // Note that the timer will not be rescheduled since the expiry time is
8728 // fixed after connection regardless of the network satisfying other requests or not.
8729 // But it will be removed as soon as the network satisfies a request for the first time.
8730 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
8731 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08008732 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008733
Paul Jensen05e85ee2014-09-11 11:00:39 -04008734 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008735 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008736
8737 // This has to happen after matching the requests, because callbacks are just requests.
8738 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008739 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008740 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04008741 if (networkAgent.isVPN()) {
Chalard Jeanb2a49912018-01-16 18:43:05 +09008742 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04008743 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09008744 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00008745 if (networkAgent.isVPN()) {
8746 // As the active or bound network changes for apps, broadcast the default proxy, as
8747 // apps may need to update their proxy data. This is called after disconnecting from
8748 // VPN to make sure we do not broadcast the old proxy data.
8749 // TODO(b/122649188): send the broadcast only to VPN users.
8750 mProxyTracker.sendProxyBroadcast();
8751 }
Yintang Gu5014b522019-06-18 14:24:32 +08008752 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
8753 state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008754 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008755 }
8756 }
8757
Chalard Jean28018572020-12-21 18:36:52 +09008758 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09008759 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
8760 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008761 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07008762 }
8763
Erik Kline99f301b2017-02-15 19:59:17 +09008764 // Notify only this one new request of the current state. Transfer all the
8765 // current state by calling NetworkCapabilities and LinkProperties callbacks
8766 // so that callers can be guaranteed to have as close to atomicity in state
8767 // transfer as can be supported by this current API.
8768 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07008769 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09008770 if (nri.mPendingIntent != null) {
8771 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
8772 // Attempt no subsequent state pushes where intents are involved.
8773 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008774 }
Erik Kline99f301b2017-02-15 19:59:17 +09008775
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008776 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08008777 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008778 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
8779 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
8780 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08008781 }
8782
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008783 // Notify the requests on this NAI that the network is now lingered.
8784 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08008785 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008786 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
8787 }
8788
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008789 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
8790 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
8791 return vpnBlocked
8792 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
8793 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
8794 }
8795
8796 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
8797 if (blockedReasons == BLOCKED_REASON_NONE) {
8798 mUidBlockedReasons.delete(uid);
8799 } else {
8800 mUidBlockedReasons.put(uid, blockedReasons);
8801 }
8802 }
8803
junyulaif2c67e42018-08-07 19:50:45 +08008804 /**
8805 * Notify of the blocked state apps with a registered callback matching a given NAI.
8806 *
8807 * Unlike other callbacks, blocked status is different between each individual uid. So for
8808 * any given nai, all requests need to be considered according to the uid who filed it.
8809 *
8810 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008811 * @param oldMetered True if the previous network capabilities were metered.
8812 * @param newMetered True if the current network capabilities are metered.
8813 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
8814 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08008815 */
8816 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00008817 boolean newMetered, List<UidRange> oldBlockedUidRanges,
8818 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08008819
8820 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8821 NetworkRequest nr = nai.requestAt(i);
8822 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008823
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008824 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8825 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
8826 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008827 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008828 : oldVpnBlocked;
8829
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008830 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
8831 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
8832 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08008833 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008834 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08008835 }
8836 }
8837 }
8838
8839 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00008840 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08008841 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00008842 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08008843 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008844 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008845 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08008846 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008847 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00008848
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008849 final int oldBlockedState = getBlockedState(
8850 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
8851 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
8852 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08008853 continue;
junyulaif2c67e42018-08-07 19:50:45 +08008854 }
junyulaif2c67e42018-08-07 19:50:45 +08008855 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8856 NetworkRequest nr = nai.requestAt(i);
8857 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008858 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008859 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8860 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08008861 }
8862 }
8863 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008864 }
8865
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008866 @VisibleForTesting
8867 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09008868 // The NetworkInfo we actually send out has no bearing on the real
8869 // state of affairs. For example, if the default connection is mobile,
8870 // and a request for HIPRI has just gone away, we need to pretend that
8871 // HIPRI has just disconnected. So we need to set the type to HIPRI and
8872 // the state to DISCONNECTED, even though the network is of type MOBILE
8873 // and is still connected.
8874 NetworkInfo info = new NetworkInfo(nai.networkInfo);
8875 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09008876 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008877 if (state != DetailedState.DISCONNECTED) {
8878 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09008879 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008880 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008881 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07008882 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
8883 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
8884 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
8885 if (info.isFailover()) {
8886 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
8887 nai.networkInfo.setFailover(false);
8888 }
8889 if (info.getReason() != null) {
8890 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
8891 }
8892 if (info.getExtraInfo() != null) {
8893 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
8894 }
8895 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09008896 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08008897 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07008898 if (newDefaultAgent != null) {
8899 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
8900 newDefaultAgent.networkInfo);
8901 } else {
8902 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
8903 }
8904 }
8905 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
8906 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09008907 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008908 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09008909 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008910 }
8911 }
8912 }
8913
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008914 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008915 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008916 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09008917 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09008918 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008919 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
8920 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008921 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8922 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008923 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008924 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008925 } else {
8926 sendPendingIntentForRequest(nri, networkAgent, notifyType);
8927 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008928 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008929 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07008930
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008931 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
8932 notifyNetworkCallbacks(networkAgent, notifyType, 0);
8933 }
8934
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008935 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09008936 * Returns the list of all interfaces that could be used by network traffic that does not
8937 * explicitly specify a network. This includes the default network, but also all VPNs that are
8938 * currently connected.
8939 *
8940 * Must be called on the handler thread.
8941 */
junyulaie7c7d2a2021-01-26 15:29:15 +08008942 @NonNull
8943 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08008944 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08008945 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08008946 final Set<Integer> activeNetIds = new ArraySet<>();
8947 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8948 if (nri.isBeingSatisfied()) {
8949 activeNetIds.add(nri.getSatisfier().network().netId);
8950 }
8951 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008952 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattis2516da32021-01-31 17:06:19 -08008953 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09008954 defaultNetworks.add(nai.network);
8955 }
8956 }
junyulaie7c7d2a2021-01-26 15:29:15 +08008957 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09008958 }
8959
8960 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09008961 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
8962 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008963 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08008964 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08008965 ensureRunningOnConnectivityServiceThread();
8966 String activeIface = null;
8967 LinkProperties activeLinkProperties = getActiveLinkProperties();
8968 if (activeLinkProperties != null) {
8969 activeIface = activeLinkProperties.getInterfaceName();
8970 }
Benedict Wong9308cd32019-06-12 17:46:31 +00008971
junyulai2050bed2021-01-23 09:46:34 +08008972 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008973 try {
junyulaide41fc22021-01-22 22:46:01 +08008974 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
junyulai69114da2021-03-05 14:46:25 +08008975 for (final NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaide41fc22021-01-22 22:46:01 +08008976 snapshots.add(snapshot);
8977 }
junyulaie7c7d2a2021-01-26 15:29:15 +08008978 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
8979 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008980 } catch (Exception ignored) {
8981 }
8982 }
8983
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07008984 @Override
Udam Sainicd645462016-01-04 12:16:14 -08008985 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08008986 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008987 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008988 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01008989
8990 if (!TextUtils.isEmpty(settingUrl)) {
8991 return settingUrl;
8992 }
8993
8994 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08008995 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01008996 if (!TextUtils.isEmpty(settingUrl)) {
8997 return settingUrl;
8998 }
8999
9000 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009001 }
9002
9003 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009004 public void startNattKeepalive(Network network, int intervalSeconds,
9005 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009006 enforceKeepalivePermission();
9007 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009008 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai070f9ff2019-01-16 20:23:34 +08009009 intervalSeconds, cb,
junyulai011b1f12019-01-03 18:50:15 +08009010 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009011 }
9012
9013 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009014 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009015 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulaid05a1922019-01-15 11:32:44 +08009016 String dstAddr) {
Josh Gao461a1222020-06-16 15:58:11 -07009017 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009018 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009019 mKeepaliveTracker.startNattKeepalive(
9020 getNetworkAgentInfoForNetwork(network), fd, resourceId,
9021 intervalSeconds, cb,
9022 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
9023 } finally {
9024 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9025 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009026 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9027 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009028 }
9029 }
junyulaid05a1922019-01-15 11:32:44 +08009030 }
9031
9032 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009033 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009034 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009035 try {
9036 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08009037 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009038 mKeepaliveTracker.startTcpKeepalive(
9039 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
9040 } finally {
9041 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9042 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009043 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9044 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009045 }
9046 }
junyulai0835a1e2019-01-08 20:04:33 +08009047 }
9048
9049 @Override
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009050 public void stopKeepalive(Network network, int slot) {
9051 mHandler.sendMessage(mHandler.obtainMessage(
junyulai011b1f12019-01-03 18:50:15 +08009052 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009053 }
9054
9055 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07009056 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08009057 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07009058
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009059 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08009060 final long token = Binder.clearCallingIdentity();
9061 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009062 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
9063 UserHandle.getUserHandleForUid(uid))) {
9064 return;
9065 }
9066
Heemin Seogdb8489d2019-06-12 09:21:44 -07009067 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
9068 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009069
9070 // Turn airplane mode off
9071 setAirplaneMode(false);
9072
9073 // restore private DNS settings to default mode (opportunistic)
9074 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
9075 UserHandle.getUserHandleForUid(uid))) {
9076 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
9077 PRIVATE_DNS_MODE_OPPORTUNISTIC);
9078 }
9079
9080 Settings.Global.putString(mContext.getContentResolver(),
9081 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08009082 } finally {
9083 Binder.restoreCallingIdentity(token);
9084 }
Stuart Scottd5463642015-04-02 18:00:02 -07009085 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04009086
Ricky Wai7097cc92018-01-23 04:09:45 +00009087 @Override
9088 public byte[] getNetworkWatchlistConfigHash() {
9089 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
9090 if (nwm == null) {
9091 loge("Unable to get NetworkWatchlistManager");
9092 return null;
9093 }
9094 // Redirect it to network watchlist service to access watchlist file and calculate hash.
9095 return nwm.getWatchlistConfigHash();
9096 }
9097
Hugo Benichibe0c7652016-05-31 16:28:06 +09009098 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09009099 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08009100 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09009101 }
Hugo Benichif4210292017-04-21 15:07:12 +09009102
9103 private static boolean toBool(int encodedBoolean) {
9104 return encodedBoolean != 0; // Only 0 means false.
9105 }
9106
9107 private static int encodeBool(boolean b) {
9108 return b ? 1 : 0;
9109 }
mswest4632928412018-03-12 10:34:34 -07009110
9111 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009112 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
9113 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
9114 @NonNull String[] args) {
9115 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
9116 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07009117 }
9118
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009119 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07009120 @Override
9121 public int onCommand(String cmd) {
9122 if (cmd == null) {
9123 return handleDefaultCommands(cmd);
9124 }
9125 final PrintWriter pw = getOutPrintWriter();
9126 try {
9127 switch (cmd) {
9128 case "airplane-mode":
9129 final String action = getNextArg();
9130 if ("enable".equals(action)) {
9131 setAirplaneMode(true);
9132 return 0;
9133 } else if ("disable".equals(action)) {
9134 setAirplaneMode(false);
9135 return 0;
9136 } else if (action == null) {
9137 final ContentResolver cr = mContext.getContentResolver();
9138 final int enabled = Settings.Global.getInt(cr,
9139 Settings.Global.AIRPLANE_MODE_ON);
9140 pw.println(enabled == 0 ? "disabled" : "enabled");
9141 return 0;
9142 } else {
9143 onHelp();
9144 return -1;
9145 }
9146 default:
9147 return handleDefaultCommands(cmd);
9148 }
9149 } catch (Exception e) {
9150 pw.println(e);
9151 }
9152 return -1;
9153 }
9154
9155 @Override
9156 public void onHelp() {
9157 PrintWriter pw = getOutPrintWriter();
9158 pw.println("Connectivity service commands:");
9159 pw.println(" help");
9160 pw.println(" Print this help text.");
9161 pw.println(" airplane-mode [enable|disable]");
9162 pw.println(" Turn airplane mode on or off.");
9163 pw.println(" airplane-mode");
9164 pw.println(" Get airplane mode.");
9165 }
9166 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009167
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09009168 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009169 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
9170 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
9171 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +08009172 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009173 }
9174
9175 /**
9176 * @param connectionInfo the connection to resolve.
9177 * @return {@code uid} if the connection is found and the app has permission to observe it
9178 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
9179 * connection is not found.
9180 */
9181 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009182 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
9183 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
9184 }
9185
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09009186 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009187 connectionInfo.local, connectionInfo.remote);
9188
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009189 if (uid == INVALID_UID) return uid; // Not found.
9190
9191 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
9192 // VPN, if any, that applies to the UID that owns the connection.
9193 if (checkNetworkStackPermission()) return uid;
9194
9195 final NetworkAgentInfo vpn = getVpnForUid(uid);
9196 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09009197 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009198 return INVALID_UID;
9199 }
9200
9201 return uid;
9202 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +00009203
Benedict Wong493e04b2018-11-09 14:45:34 -08009204 /**
9205 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
9206 *
9207 * <p>The TestNetworkService must be run in the system server due to TUN creation.
9208 */
9209 @Override
9210 public IBinder startOrGetTestNetworkService() {
9211 synchronized (mTNSLock) {
9212 TestNetworkService.enforceTestNetworkPermissions(mContext);
9213
9214 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +08009215 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -08009216 }
9217
9218 return mTNS;
9219 }
9220 }
Cody Kestingd199a9d2019-12-17 12:55:28 -08009221
Cody Kesting73708bf2019-12-18 10:57:50 -08009222 /**
9223 * Handler used for managing all Connectivity Diagnostics related functions.
9224 *
9225 * @see android.net.ConnectivityDiagnosticsManager
9226 *
9227 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9228 */
9229 @VisibleForTesting
9230 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009231 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9232
Cody Kesting73708bf2019-12-18 10:57:50 -08009233 /**
9234 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9235 * android.net.ConnectivityDiagnosticsManager}.
9236 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9237 * NetworkRequestInfo to be registered
9238 */
9239 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9240
9241 /**
9242 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9243 * android.net.ConnectivityDiagnosticsManager}.
9244 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9245 * arg1 = the uid of the caller
9246 */
9247 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9248
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009249 /**
9250 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
9251 * after processing {@link #EVENT_NETWORK_TESTED} events.
9252 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9253 * NetworkMonitor.
9254 * data = PersistableBundle of extras passed from NetworkMonitor.
9255 *
9256 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
9257 */
9258 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
9259
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009260 /**
9261 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9262 * been detected on the network.
9263 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9264 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9265 * arg2 = NetID.
9266 * data = PersistableBundle of extras passed from NetworkMonitor.
9267 */
9268 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9269
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009270 /**
9271 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9272 * the platform. This event will invoke {@link
9273 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9274 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -07009275 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009276 */
9277 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9278
Cody Kesting73708bf2019-12-18 10:57:50 -08009279 private ConnectivityDiagnosticsHandler(Looper looper) {
9280 super(looper);
9281 }
9282
9283 @Override
9284 public void handleMessage(Message msg) {
9285 switch (msg.what) {
9286 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9287 handleRegisterConnectivityDiagnosticsCallback(
9288 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9289 break;
9290 }
9291 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9292 handleUnregisterConnectivityDiagnosticsCallback(
9293 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9294 break;
9295 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009296 case EVENT_NETWORK_TESTED: {
9297 final ConnectivityReportEvent reportEvent =
9298 (ConnectivityReportEvent) msg.obj;
9299
Aaron Huang959d3642021-01-21 15:47:41 +08009300 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009301 break;
9302 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009303 case EVENT_DATA_STALL_SUSPECTED: {
9304 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +08009305 final Pair<Long, PersistableBundle> arg =
9306 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009307 if (nai == null) break;
9308
Aaron Huang959d3642021-01-21 15:47:41 +08009309 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009310 break;
9311 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009312 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -07009313 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009314 break;
9315 }
9316 default: {
9317 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9318 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009319 }
9320 }
9321 }
9322
9323 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9324 @VisibleForTesting
9325 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9326 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9327 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009328 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009329
9330 @VisibleForTesting
9331 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009332 @NonNull IConnectivityDiagnosticsCallback cb,
9333 @NonNull NetworkRequestInfo nri,
9334 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009335 mCb = cb;
9336 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009337 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009338 }
9339
9340 @Override
9341 public void binderDied() {
9342 log("ConnectivityDiagnosticsCallback IBinder died.");
9343 unregisterConnectivityDiagnosticsCallback(mCb);
9344 }
9345 }
9346
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009347 /**
9348 * Class used for sending information from {@link
9349 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9350 */
9351 private static class NetworkTestedResults {
9352 private final int mNetId;
9353 private final int mTestResult;
9354 private final long mTimestampMillis;
9355 @Nullable private final String mRedirectUrl;
9356
9357 private NetworkTestedResults(
9358 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9359 mNetId = netId;
9360 mTestResult = testResult;
9361 mTimestampMillis = timestampMillis;
9362 mRedirectUrl = redirectUrl;
9363 }
9364 }
9365
9366 /**
9367 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9368 * ConnectivityDiagnosticsHandler}.
9369 */
9370 private static class ConnectivityReportEvent {
9371 private final long mTimestampMillis;
9372 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +08009373 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009374
Aaron Huang959d3642021-01-21 15:47:41 +08009375 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9376 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009377 mTimestampMillis = timestampMillis;
9378 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +08009379 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009380 }
9381 }
9382
Cody Kestingf1120be2020-08-03 18:01:40 -07009383 /**
9384 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
9385 * ConnectivityDiagnosticsHandler}.
9386 */
9387 private static class ReportedNetworkConnectivityInfo {
9388 public final boolean hasConnectivity;
9389 public final boolean isNetworkRevalidating;
9390 public final int reporterUid;
9391 @NonNull public final NetworkAgentInfo nai;
9392
9393 private ReportedNetworkConnectivityInfo(
9394 boolean hasConnectivity,
9395 boolean isNetworkRevalidating,
9396 int reporterUid,
9397 @NonNull NetworkAgentInfo nai) {
9398 this.hasConnectivity = hasConnectivity;
9399 this.isNetworkRevalidating = isNetworkRevalidating;
9400 this.reporterUid = reporterUid;
9401 this.nai = nai;
9402 }
9403 }
9404
Cody Kesting73708bf2019-12-18 10:57:50 -08009405 private void handleRegisterConnectivityDiagnosticsCallback(
9406 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9407 ensureRunningOnConnectivityServiceThread();
9408
9409 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -08009410 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009411 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9412
James Mattis64b8b0f2020-11-24 17:40:49 -08009413 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9414 // confusing for these networks to change when an NRI is satisfied in another layer.
9415 if (nri.isMultilayerRequest()) {
9416 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9417 + "network requests.");
9418 }
9419
Cody Kesting73708bf2019-12-18 10:57:50 -08009420 // This means that the client registered the same callback multiple times. Do
9421 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -08009422 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009423 if (VDBG) log("Diagnostics callback is already registered");
9424
9425 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9426 // incremented when the NetworkRequestInfo is created as part of
9427 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009428 nri.decrementRequestCount();
Cody Kesting73708bf2019-12-18 10:57:50 -08009429 return;
9430 }
9431
Cody Kesting31f1ff62020-03-05 10:46:02 -08009432 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -08009433
9434 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -08009435 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009436 } catch (RemoteException e) {
9437 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -08009438 return;
9439 }
9440
9441 // Once registered, provide ConnectivityReports for matching Networks
9442 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9443 synchronized (mNetworkForNetId) {
9444 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9445 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -08009446 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9447 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -08009448 matchingNetworks.add(nai);
9449 }
9450 }
9451 }
9452 for (final NetworkAgentInfo nai : matchingNetworks) {
9453 final ConnectivityReport report = nai.getConnectivityReport();
9454 if (report == null) {
9455 continue;
9456 }
9457 if (!checkConnectivityDiagnosticsPermissions(
9458 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9459 continue;
9460 }
9461
9462 try {
9463 cb.onConnectivityReportAvailable(report);
9464 } catch (RemoteException e) {
9465 // Exception while sending the ConnectivityReport. Move on to the next network.
9466 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009467 }
9468 }
9469
9470 private void handleUnregisterConnectivityDiagnosticsCallback(
9471 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9472 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009473 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009474
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009475 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9476 mConnectivityDiagnosticsCallbacks.remove(iCb);
9477 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009478 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9479 return;
9480 }
9481
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009482 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -08009483
Cody Kesting70fa2b22020-12-02 12:16:56 -08009484 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9485 // (if the Binder died)
9486 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9487 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -08009488 return;
9489 }
9490
Cody Kesting46cb1672020-03-04 13:35:20 -08009491 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9492 // incremented when the NetworkRequestInfo is created as part of
9493 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009494 nri.decrementRequestCount();
Cody Kesting46cb1672020-03-04 13:35:20 -08009495
Cody Kesting31f1ff62020-03-05 10:46:02 -08009496 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009497 }
9498
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009499 private void handleNetworkTestedWithExtras(
9500 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9501 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -08009502 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009503 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009504 final ConnectivityReport report =
9505 new ConnectivityReport(
9506 reportEvent.mNai.network,
9507 reportEvent.mTimestampMillis,
9508 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009509 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009510 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -08009511 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -07009512
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009513 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009514 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009515 for (final IConnectivityDiagnosticsCallback cb : results) {
9516 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -08009517 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009518 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -07009519 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009520 }
9521 }
9522 }
9523
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009524 private void handleDataStallSuspected(
9525 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9526 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -08009527 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009528 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009529 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -08009530 new DataStallReport(
9531 nai.network,
9532 timestampMillis,
9533 detectionMethod,
9534 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009535 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -08009536 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009537 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009538 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009539 for (final IConnectivityDiagnosticsCallback cb : results) {
9540 try {
9541 cb.onDataStallSuspected(report);
9542 } catch (RemoteException ex) {
9543 loge("Error invoking onDataStallSuspected", ex);
9544 }
9545 }
9546 }
9547
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009548 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -07009549 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
9550 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
9551 final ConnectivityReport cachedReport = nai.getConnectivityReport();
9552
9553 // If the Network is being re-validated as a result of this call to
9554 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
9555 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009556 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009557 getMatchingPermissionedCallbacks(
9558 nai,
9559 reportedNetworkConnectivityInfo.isNetworkRevalidating
9560 ? Process.INVALID_UID
9561 : reportedNetworkConnectivityInfo.reporterUid);
9562
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009563 for (final IConnectivityDiagnosticsCallback cb : results) {
9564 try {
Cody Kestingf1120be2020-08-03 18:01:40 -07009565 cb.onNetworkConnectivityReported(
9566 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009567 } catch (RemoteException ex) {
9568 loge("Error invoking onNetworkConnectivityReported", ex);
9569 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009570
9571 // If the Network isn't re-validating, also provide the cached report. If there is no
9572 // cached report, the Network is still being validated and a report will be sent once
9573 // validation is complete. Note that networks which never undergo validation will still
9574 // have a cached ConnectivityReport with RESULT_SKIPPED.
9575 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
9576 try {
9577 cb.onConnectivityReportAvailable(cachedReport);
9578 } catch (RemoteException ex) {
9579 loge("Error invoking onConnectivityReportAvailable", ex);
9580 }
9581 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009582 }
9583 }
9584
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009585 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +09009586 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9587 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009588 sanitized.setUids(null);
9589 sanitized.setAdministratorUids(new int[0]);
9590 sanitized.setOwnerUid(Process.INVALID_UID);
9591 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -08009592 }
9593
Cody Kestingf1120be2020-08-03 18:01:40 -07009594 /**
9595 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
9596 *
9597 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
9598 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009599 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -07009600 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009601 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009602 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009603 mConnectivityDiagnosticsCallbacks.entrySet()) {
9604 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9605 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -07009606
James Mattis64b8b0f2020-11-24 17:40:49 -08009607 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -07009608 if (!nai.satisfies(nri.mRequests.get(0))) {
9609 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009610 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009611
9612 // UID for this callback must either be:
9613 // - INVALID_UID (which sends callbacks to all UIDs), or
9614 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
9615 // notified as a result)
9616 if (uid != Process.INVALID_UID && uid != nri.mUid) {
9617 continue;
9618 }
9619
9620 if (!checkConnectivityDiagnosticsPermissions(
9621 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9622 continue;
9623 }
9624
9625 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009626 }
9627 return results;
9628 }
9629
Cody Kesting7474f672021-05-11 14:22:40 -07009630 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
9631 @NonNull NetworkAgentInfo nai) {
9632 // TODO(b/188483916): replace with a transport-agnostic location-aware check
9633 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
9634 }
9635
Cody Kesting160ef392021-05-05 13:17:22 -07009636 private boolean hasLocationPermission(String packageName, int uid) {
9637 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9638 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9639 // call in a try-catch.
9640 try {
9641 if (!mLocationPermissionChecker.checkLocationPermission(
9642 packageName, null /* featureId */, uid, null /* message */)) {
9643 return false;
9644 }
9645 } catch (SecurityException e) {
9646 return false;
9647 }
9648
9649 return true;
9650 }
9651
9652 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
9653 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +09009654 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -07009655 && virtual.networkCapabilities.getOwnerUid() == uid
9656 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
9657 return true;
9658 }
9659 }
9660
9661 return false;
9662 }
9663
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009664 @VisibleForTesting
9665 boolean checkConnectivityDiagnosticsPermissions(
9666 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9667 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9668 return true;
9669 }
9670
Cody Kesting160ef392021-05-05 13:17:22 -07009671 // Administrator UIDs also contains the Owner UID
9672 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
9673 if (!CollectionUtils.contains(administratorUids, callbackUid)
9674 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009675 return false;
9676 }
9677
Cody Kesting7474f672021-05-11 14:22:40 -07009678 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
9679 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009680 }
9681
Cody Kestingd199a9d2019-12-17 12:55:28 -08009682 @Override
9683 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009684 @NonNull IConnectivityDiagnosticsCallback callback,
9685 @NonNull NetworkRequest request,
9686 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -07009687 Objects.requireNonNull(callback, "callback must not be null");
9688 Objects.requireNonNull(request, "request must not be null");
9689 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
9690
Cody Kesting73708bf2019-12-18 10:57:50 -08009691 if (request.legacyType != TYPE_NONE) {
9692 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
9693 + " Please use NetworkCapabilities instead.");
9694 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009695 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -08009696 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009697
9698 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
9699 // and administrator uids to be safe.
9700 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08009701 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009702
9703 final NetworkRequest requestWithId =
9704 new NetworkRequest(
9705 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
9706
9707 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
9708 //
9709 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
9710 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
9711 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009712 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -08009713 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009714 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009715
9716 mConnectivityDiagnosticsHandler.sendMessage(
9717 mConnectivityDiagnosticsHandler.obtainMessage(
9718 ConnectivityDiagnosticsHandler
9719 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9720 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -08009721 }
9722
9723 @Override
9724 public void unregisterConnectivityDiagnosticsCallback(
9725 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +08009726 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -08009727 mConnectivityDiagnosticsHandler.sendMessage(
9728 mConnectivityDiagnosticsHandler.obtainMessage(
9729 ConnectivityDiagnosticsHandler
9730 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009731 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -08009732 0,
9733 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -08009734 }
Cody Kestingf53a0752020-04-15 12:33:28 -07009735
9736 @Override
9737 public void simulateDataStall(int detectionMethod, long timestampMillis,
9738 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -07009739 Objects.requireNonNull(network, "network must not be null");
9740 Objects.requireNonNull(extras, "extras must not be null");
9741
Cody Kestingf53a0752020-04-15 12:33:28 -07009742 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
9743 android.Manifest.permission.NETWORK_STACK);
9744 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
9745 if (!nc.hasTransport(TRANSPORT_TEST)) {
9746 throw new SecurityException("Data Stall simluation is only possible for test networks");
9747 }
9748
9749 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009750 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -07009751 throw new SecurityException("Data Stall simulation is only possible for network "
9752 + "creators");
9753 }
9754
Cody Kesting652e3ec2020-05-21 12:08:21 -07009755 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
9756 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
9757 // Data Stall information as a DataStallReportParcelable and passing to
9758 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
9759 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -07009760 final DataStallReportParcelable p = new DataStallReportParcelable();
9761 p.timestampMillis = timestampMillis;
9762 p.detectionMethod = detectionMethod;
9763
9764 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
9765 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
9766 }
9767 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
9768 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
9769 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
9770 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
9771 }
9772
Serik Beketayevec8ad212020-12-07 22:43:07 -08009773 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -07009774 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009775
lucaslin66f44212021-02-23 01:12:55 +08009776 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
9777 @Override
lucaslin87b58aa2021-02-25 15:10:29 +08009778 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +08009779 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +08009780 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +08009781 }
lucaslin37a16d92021-01-21 19:48:09 +08009782
9783 @Override
9784 public void onInterfaceLinkStateChanged(String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +08009785 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +08009786 nai.clatd.interfaceLinkStateChanged(iface, up);
9787 }
9788 }
9789
9790 @Override
9791 public void onInterfaceRemoved(String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +08009792 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +08009793 nai.clatd.interfaceRemoved(iface);
9794 }
lucaslin66f44212021-02-23 01:12:55 +08009795 }
9796 }
9797
lucaslin1a8b4c62021-01-21 02:02:55 +08009798 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
9799
9800 /**
9801 * Class used for updating network activity tracking with netd and notify network activity
9802 * changes.
9803 */
9804 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +08009805 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +08009806 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +08009807 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +08009808 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
9809 new RemoteCallbackList<>();
9810 // Indicate the current system default network activity is active or not.
9811 @GuardedBy("mActiveIdleTimers")
9812 private boolean mNetworkActive;
9813 @GuardedBy("mActiveIdleTimers")
9814 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
9815 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +08009816
lucaslin1193a5d2021-01-21 02:04:15 +08009817 private class IdleTimerParams {
9818 public final int timeout;
9819 public final int transportType;
9820
9821 IdleTimerParams(int timeout, int transport) {
9822 this.timeout = timeout;
9823 this.transportType = transport;
9824 }
9825 }
9826
9827 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +08009828 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +08009829 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +08009830 mNetd = netd;
9831 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +08009832 }
9833
lucaslin66f44212021-02-23 01:12:55 +08009834 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
9835 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
9836 synchronized (mActiveIdleTimers) {
9837 mNetworkActive = active;
9838 // If there are no idle timers, it means that system is not monitoring
9839 // activity, so the system default network for those default network
9840 // unspecified apps is always considered active.
9841 //
9842 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
9843 // any network activity change event. Whenever this event is received,
9844 // the mActiveIdleTimers should be always not empty. The legacy behavior
9845 // is no-op. Remove to refer to mNetworkActive only.
9846 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
9847 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
9848 }
9849 }
9850 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009851
lucaslin1193a5d2021-01-21 02:04:15 +08009852 // The network activity should only be updated from ConnectivityService handler thread
9853 // when mActiveIdleTimers lock is held.
9854 @GuardedBy("mActiveIdleTimers")
9855 private void reportNetworkActive() {
9856 final int length = mNetworkActivityListeners.beginBroadcast();
9857 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
9858 try {
9859 for (int i = 0; i < length; i++) {
9860 try {
9861 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
9862 } catch (RemoteException | RuntimeException e) {
9863 loge("Fail to send network activie to listener " + e);
9864 }
9865 }
9866 } finally {
9867 mNetworkActivityListeners.finishBroadcast();
9868 }
9869 }
9870
9871 @GuardedBy("mActiveIdleTimers")
9872 public void handleReportNetworkActivity() {
9873 synchronized (mActiveIdleTimers) {
9874 reportNetworkActive();
9875 }
9876 }
9877
lucaslin1a8b4c62021-01-21 02:02:55 +08009878 // This is deprecated and only to support legacy use cases.
9879 private int transportTypeToLegacyType(int type) {
9880 switch (type) {
9881 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009882 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +08009883 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009884 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +08009885 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009886 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +08009887 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009888 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +08009889 default:
9890 loge("Unexpected transport in transportTypeToLegacyType: " + type);
9891 }
9892 return ConnectivityManager.TYPE_NONE;
9893 }
9894
9895 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
9896 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
9897 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
9898 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
9899 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
9900 final long ident = Binder.clearCallingIdentity();
9901 try {
9902 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
9903 RECEIVE_DATA_ACTIVITY_CHANGE,
9904 null /* resultReceiver */,
9905 null /* scheduler */,
9906 0 /* initialCode */,
9907 null /* initialData */,
9908 null /* initialExtra */);
9909 } finally {
9910 Binder.restoreCallingIdentity(ident);
9911 }
9912 }
9913
9914 /**
9915 * Setup data activity tracking for the given network.
9916 *
9917 * Every {@code setupDataActivityTracking} should be paired with a
9918 * {@link #removeDataActivityTracking} for cleanup.
9919 */
9920 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
9921 final String iface = networkAgent.linkProperties.getInterfaceName();
9922
9923 final int timeout;
9924 final int type;
9925
9926 if (networkAgent.networkCapabilities.hasTransport(
9927 NetworkCapabilities.TRANSPORT_CELLULAR)) {
9928 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009929 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +08009930 10);
9931 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9932 } else if (networkAgent.networkCapabilities.hasTransport(
9933 NetworkCapabilities.TRANSPORT_WIFI)) {
9934 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009935 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +08009936 15);
9937 type = NetworkCapabilities.TRANSPORT_WIFI;
9938 } else {
9939 return; // do not track any other networks
9940 }
9941
lucaslinb961efc2021-01-21 02:03:17 +08009942 updateRadioPowerState(true /* isActive */, type);
9943
lucaslin1a8b4c62021-01-21 02:02:55 +08009944 if (timeout > 0 && iface != null) {
9945 try {
lucaslin1193a5d2021-01-21 02:04:15 +08009946 synchronized (mActiveIdleTimers) {
9947 // Networks start up.
9948 mNetworkActive = true;
9949 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
9950 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
9951 reportNetworkActive();
9952 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009953 } catch (Exception e) {
9954 // You shall not crash!
9955 loge("Exception in setupDataActivityTracking " + e);
9956 }
9957 }
9958 }
9959
9960 /**
9961 * Remove data activity tracking when network disconnects.
9962 */
9963 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
9964 final String iface = networkAgent.linkProperties.getInterfaceName();
9965 final NetworkCapabilities caps = networkAgent.networkCapabilities;
9966
lucaslinb961efc2021-01-21 02:03:17 +08009967 if (iface == null) return;
9968
9969 final int type;
9970 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
9971 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9972 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
9973 type = NetworkCapabilities.TRANSPORT_WIFI;
9974 } else {
9975 return; // do not track any other networks
9976 }
9977
9978 try {
9979 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +08009980 synchronized (mActiveIdleTimers) {
9981 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
9982 // The call fails silently if no idle timer setup for this interface
9983 mNetd.idletimerRemoveInterface(iface, params.timeout,
9984 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +08009985 }
lucaslinb961efc2021-01-21 02:03:17 +08009986 } catch (Exception e) {
9987 // You shall not crash!
9988 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +08009989 }
9990 }
9991
9992 /**
9993 * Update data activity tracking when network state is updated.
9994 */
9995 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
9996 NetworkAgentInfo oldNetwork) {
9997 if (newNetwork != null) {
9998 setupDataActivityTracking(newNetwork);
9999 }
10000 if (oldNetwork != null) {
10001 removeDataActivityTracking(oldNetwork);
10002 }
10003 }
lucaslinb961efc2021-01-21 02:03:17 +080010004
10005 private void updateRadioPowerState(boolean isActive, int transportType) {
10006 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
10007 switch (transportType) {
10008 case NetworkCapabilities.TRANSPORT_CELLULAR:
10009 bs.reportMobileRadioPowerState(isActive, NO_UID);
10010 break;
10011 case NetworkCapabilities.TRANSPORT_WIFI:
10012 bs.reportWifiRadioPowerState(isActive, NO_UID);
10013 break;
10014 default:
10015 logw("Untracked transport type:" + transportType);
10016 }
10017 }
lucaslin1193a5d2021-01-21 02:04:15 +080010018
10019 public boolean isDefaultNetworkActive() {
10020 synchronized (mActiveIdleTimers) {
10021 // If there are no idle timers, it means that system is not monitoring activity,
10022 // so the default network is always considered active.
10023 //
10024 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
10025 // tracking is disabled (negative idle timer value configured), or no active default
10026 // network. In the latter case, this reports active but it should report inactive.
10027 return mNetworkActive || mActiveIdleTimers.isEmpty();
10028 }
10029 }
10030
10031 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
10032 mNetworkActivityListeners.register(l);
10033 }
10034
10035 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
10036 mNetworkActivityListeners.unregister(l);
10037 }
lucaslin012f7a12021-01-21 02:04:35 +080010038
10039 public void dump(IndentingPrintWriter pw) {
10040 synchronized (mActiveIdleTimers) {
10041 pw.print("mNetworkActive="); pw.println(mNetworkActive);
10042 pw.println("Idle timers:");
10043 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
10044 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
10045 final IdleTimerParams params = ent.getValue();
10046 pw.print(" timeout="); pw.print(params.timeout);
10047 pw.print(" type="); pw.println(params.transportType);
10048 }
10049 }
10050 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010051 }
James Mattis47db0582021-01-01 14:13:35 -080010052
Daniel Brightf9e945b2020-06-15 16:10:01 -070010053 /**
10054 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
10055 *
10056 * @param socketInfo the socket information
10057 * @param callback the callback to register
10058 */
10059 @Override
10060 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
10061 @NonNull final IQosCallback callback) {
10062 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
10063 if (nai == null || nai.networkCapabilities == null) {
10064 try {
10065 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
10066 } catch (final RemoteException ex) {
10067 loge("registerQosCallbackInternal: RemoteException", ex);
10068 }
10069 return;
10070 }
10071 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
10072 }
10073
10074 /**
10075 * Register a {@link IQosCallback} with base {@link QosFilter}.
10076 *
10077 * @param filter the filter to register
10078 * @param callback the callback to register
10079 * @param nai the agent information related to the filter's network
10080 */
10081 @VisibleForTesting
10082 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
10083 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
10084 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
10085 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
10086
10087 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
10088 enforceConnectivityRestrictedNetworksPermission();
10089 }
10090 mQosCallbackTracker.registerCallback(callback, filter, nai);
10091 }
10092
10093 /**
10094 * Unregisters the given callback.
10095 *
10096 * @param callback the callback to unregister
10097 */
10098 @Override
10099 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010100 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010101 mQosCallbackTracker.unregisterCallback(callback);
10102 }
James Mattis47db0582021-01-01 14:13:35 -080010103
James Mattis45d81842021-01-10 14:24:24 -080010104 /**
Chalard Jeanfa45a682021-02-25 17:23:40 +090010105 * Request that a user profile is put by default on a network matching a given preference.
10106 *
10107 * See the documentation for the individual preferences for a description of the supported
10108 * behaviors.
10109 *
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010110 * @param profile the user profile for whih the preference is being set.
10111 * @param preferences the list of profile network preferences for the
10112 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010113 * @param listener an optional listener to listen for completion of the operation.
10114 */
10115 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010116 public void setProfileNetworkPreferences(
10117 @NonNull final UserHandle profile,
10118 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090010119 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010120 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010121 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010122
10123 if (preferences.size() == 0) {
10124 preferences.add((new ProfileNetworkPreference.Builder()).build());
10125 }
10126
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010127 PermissionUtils.enforceNetworkStackPermission(mContext);
10128 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010129 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010130 }
10131 if (profile.getIdentifier() < 0) {
10132 throw new IllegalArgumentException("Must explicitly specify a user handle ("
10133 + "UserHandle.CURRENT not supported)");
10134 }
Chalard Jeana21ef9b2021-04-02 19:24:44 +090010135 final UserManager um = mContext.getSystemService(UserManager.class);
10136 if (!um.isManagedProfile(profile.getIdentifier())) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010137 throw new IllegalArgumentException("Profile must be a managed profile");
10138 }
paulhuaa0743d2021-05-26 21:56:03 +080010139
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010140 final List<ProfileNetworkPreferenceList.Preference> preferenceList =
10141 new ArrayList<ProfileNetworkPreferenceList.Preference>();
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010142 boolean allowFallback = true;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010143 for (final ProfileNetworkPreference preference : preferences) {
10144 final NetworkCapabilities nc;
10145 switch (preference.getPreference()) {
10146 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
10147 nc = null;
10148 break;
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010149 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
10150 allowFallback = false;
10151 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010152 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
10153 final UidRange uids = UidRange.createForUser(profile);
10154 nc = createDefaultNetworkCapabilitiesForUidRange(uids);
10155 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
10156 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10157 break;
10158 default:
10159 throw new IllegalArgumentException(
10160 "Invalid preference in setProfileNetworkPreferences");
10161 }
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010162 preferenceList.add(new ProfileNetworkPreferenceList.Preference(
10163 profile, nc, allowFallback));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010164 }
10165 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010166 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010167 }
10168
10169 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
10170 @Nullable final NetworkCapabilities nc) {
10171 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
10172 ensureRequestableCapabilities(nc);
10173 }
10174
10175 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010176 @NonNull final ProfileNetworkPreferenceList prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010177 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010178 for (final ProfileNetworkPreferenceList.Preference pref : prefs.preferences) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010179 // The NRI for a user should contain the request for capabilities.
10180 // If fallback to default network is needed then NRI should include
10181 // the request for the default network. Create an image of it to
10182 // have the correct UIDs in it (also a request can only be part of one NRI, because
10183 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010184 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
10185 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010186 if (pref.allowFallback) {
10187 nrs.add(createDefaultInternetRequestForTransport(
10188 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10189 }
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010190 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080010191 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080010192 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010193 result.add(nri);
10194 }
10195 return result;
10196 }
10197
10198 private void handleSetProfileNetworkPreference(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010199 @NonNull final List<ProfileNetworkPreferenceList.Preference> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010200 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010201 for (final ProfileNetworkPreferenceList.Preference preference : preferenceList) {
10202 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
10203 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
10204 }
paulhu74128522021-09-28 02:29:03 +000010205 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
10206 addPerAppDefaultNetworkRequests(
10207 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010208 // Finally, rematch.
10209 rematchAllNetworksAndRequests();
10210
10211 if (null != listener) {
10212 try {
10213 listener.onComplete();
10214 } catch (RemoteException e) {
10215 loge("Listener for setProfileNetworkPreference has died");
10216 }
10217 }
10218 }
10219
paulhu51f77dc2021-06-07 02:34:20 +000010220 @VisibleForTesting
10221 @NonNull
10222 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
10223 @NonNull final Set<Integer> uids) {
10224 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10225 if (uids.size() == 0) {
10226 // Should not create NetworkRequestInfo if no preferences. Without uid range in
10227 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
10228 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
10229 return nris;
10230 }
10231
10232 final List<NetworkRequest> requests = new ArrayList<>();
10233 // The NRI should be comprised of two layers:
10234 // - The request for the mobile network preferred.
10235 // - The request for the default network, for fallback.
10236 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090010237 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000010238 requests.add(createDefaultInternetRequestForTransport(
10239 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10240 final Set<UidRange> ranges = new ArraySet<>();
10241 for (final int uid : uids) {
10242 ranges.add(new UidRange(uid, uid));
10243 }
10244 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080010245 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080010246 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000010247 return nris;
10248 }
10249
10250 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000010251 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000010252 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
10253 addPerAppDefaultNetworkRequests(
10254 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000010255 // Finally, rematch.
10256 rematchAllNetworksAndRequests();
10257 }
10258
James Mattis45d81842021-01-10 14:24:24 -080010259 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080010260 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
10261 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080010262 }
10263
10264 /**
10265 * Used by automotive devices to set the network preferences used to direct traffic at an
10266 * application level as per the given OemNetworkPreferences. An example use-case would be an
10267 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
10268 * vehicle via a particular network.
10269 *
10270 * Calling this will overwrite the existing preference.
10271 *
James Mattisda32cfe2021-01-26 16:23:52 -080010272 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090010273 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080010274 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080010275 */
James Mattis47db0582021-01-01 14:13:35 -080010276 @Override
James Mattis45d81842021-01-10 14:24:24 -080010277 public void setOemNetworkPreference(
10278 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010279 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080010280
James Mattisfa270db2021-05-31 17:11:10 -070010281 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10282 // Only bypass the permission/device checks if this is a valid test request.
10283 if (isValidTestOemNetworkPreference(preference)) {
10284 enforceManageTestNetworksPermission();
10285 } else {
10286 enforceAutomotiveDevice();
10287 enforceOemNetworkPreferencesPermission();
10288 validateOemNetworkPreferences(preference);
10289 }
James Mattis45d81842021-01-10 14:24:24 -080010290
James Mattis45d81842021-01-10 14:24:24 -080010291 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
10292 new Pair<>(preference, listener)));
10293 }
10294
James Mattisfa270db2021-05-31 17:11:10 -070010295 /**
10296 * Check the validity of an OEM network preference to be used for testing purposes.
10297 * @param preference the preference to validate
10298 * @return true if this is a valid OEM network preference test request.
10299 */
10300 private boolean isValidTestOemNetworkPreference(
10301 @NonNull final OemNetworkPreferences preference) {
10302 // Allow for clearing of an existing OemNetworkPreference used for testing.
10303 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
10304 // changes after this check is complete. This is an unlikely scenario as calling of this API
10305 // is controlled by the OEM therefore the added complexity is not worth adding given those
10306 // circumstances. That said, it is an edge case to be aware of hence this comment.
10307 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
10308 && isTestOemNetworkPreference(mOemNetworkPreferences);
10309 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
10310 }
10311
10312 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
10313 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
10314 return prefMap.size() == 1
10315 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
10316 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
10317 }
10318
James Mattis45d81842021-01-10 14:24:24 -080010319 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
10320 for (@OemNetworkPreferences.OemNetworkPreference final int pref
10321 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070010322 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
10323 throw new IllegalArgumentException(
10324 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
10325 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080010326 }
10327 }
10328 }
10329
10330 private void handleSetOemNetworkPreference(
10331 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010332 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080010333 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10334 if (DBG) {
10335 log("set OEM network preferences :" + preference.toString());
10336 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010337
James Mattiscb1e0362021-04-06 17:07:42 -070010338 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000010339 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
10340 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
10341 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080010342 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080010343
10344 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010345 try {
10346 listener.onComplete();
10347 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080010348 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010349 }
James Mattis45d81842021-01-10 14:24:24 -080010350 }
10351 }
10352
paulhu74128522021-09-28 02:29:03 +000010353 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080010354 // Skip the requests which are set by other network preference. Because the uid range rules
10355 // should stay in netd.
10356 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080010357 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080010358 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080010359 }
10360
James Mattis3ce3d3c2021-02-09 18:18:28 -080010361 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
10362 ensureRunningOnConnectivityServiceThread();
10363 mDefaultNetworkRequests.addAll(nris);
10364 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
10365 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080010366 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000010367 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
10368 nrisToRegister.addAll(
10369 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
10370 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010371 }
10372
10373 /**
10374 * All current requests that are tracking the default network need to be assessed as to whether
10375 * or not the current set of per-application default requests will be changing their default
10376 * network. If so, those requests will need to be updated so that they will send callbacks for
10377 * default network changes at the appropriate time. Additionally, those requests tracking the
10378 * default that were previously updated by this flow will need to be reassessed.
10379 * @return the nris which will need to be updated.
10380 */
10381 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
10382 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
10383 // Get the distinct nris to check since for multilayer requests, it is possible to have the
10384 // same nri in the map's values for each of its NetworkRequest objects.
10385 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080010386 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010387 // Include this nri if it is currently being tracked.
10388 if (isPerAppTrackedNri(nri)) {
10389 defaultCallbackRequests.add(nri);
10390 continue;
10391 }
10392 // We only track callbacks for requests tracking the default.
10393 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
10394 continue;
10395 }
10396 // Include this nri if it will be tracked by the new per-app default requests.
10397 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010398 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080010399 if (isNriGoingToBeTracked) {
10400 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080010401 }
10402 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080010403 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080010404 }
10405
James Mattis3ce3d3c2021-02-09 18:18:28 -080010406 /**
10407 * Create nris for those network requests that are currently tracking the default network that
10408 * are being controlled by a per-application default.
10409 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
10410 * foundation when creating the nri. Important items include the calling uid's original
10411 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
10412 * requests are assumed to have already been validated as needing to be updated.
10413 * @return the Set of nris to use when registering network requests.
10414 */
10415 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
10416 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
10417 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
10418 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
10419 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010420 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010421
Chalard Jean9473c982021-07-29 20:03:04 +090010422 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080010423 if (trackingNri == mDefaultRequest) {
10424 callbackRequestsToRegister.add(new NetworkRequestInfo(
10425 callbackRequest,
10426 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
10427 continue;
10428 }
10429
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010430 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010431 callbackRequestsToRegister.add(new NetworkRequestInfo(
10432 callbackRequest,
10433 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010434 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090010435 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080010436 }
10437 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080010438 }
10439
Chalard Jean17215832021-03-01 14:06:28 +090010440 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
10441 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090010442 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010443 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090010444 }
10445 }
10446
James Mattis45d81842021-01-10 14:24:24 -080010447 /**
10448 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
10449 */
10450 @VisibleForTesting
10451 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010452 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080010453 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010454 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080010455 final SparseArray<Set<Integer>> uids =
10456 createUidsFromOemNetworkPreferences(preference);
10457 for (int i = 0; i < uids.size(); i++) {
10458 final int key = uids.keyAt(i);
10459 final Set<Integer> value = uids.valueAt(i);
10460 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
10461 // No need to add an nri without any requests.
10462 if (0 == nri.mRequests.size()) {
10463 continue;
10464 }
10465 nris.add(nri);
10466 }
10467
10468 return nris;
10469 }
10470
10471 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
10472 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070010473 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080010474 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080010475 final List<UserHandle> users =
10476 mContext.getSystemService(UserManager.class).getUserHandles(true);
10477 if (null == users || users.size() == 0) {
10478 if (VDBG || DDBG) {
10479 log("No users currently available for setting the OEM network preference.");
10480 }
James Mattisb6b6a432021-06-01 22:30:36 -070010481 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080010482 }
James Mattis45d81842021-01-10 14:24:24 -080010483 for (final Map.Entry<String, Integer> entry :
10484 preference.getNetworkPreferences().entrySet()) {
10485 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070010486 // Add the rules for all users as this policy is device wide.
10487 for (final UserHandle user : users) {
10488 try {
10489 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
10490 if (!prefToUids.contains(pref)) {
10491 prefToUids.put(pref, new ArraySet<>());
10492 }
10493 prefToUids.get(pref).add(uid);
10494 } catch (PackageManager.NameNotFoundException e) {
10495 // Although this may seem like an error scenario, it is ok that uninstalled
10496 // packages are sent on a network preference as the system will watch for
10497 // package installations associated with this network preference and update
10498 // accordingly. This is done to minimize race conditions on app install.
10499 continue;
James Mattis45d81842021-01-10 14:24:24 -080010500 }
James Mattis45d81842021-01-10 14:24:24 -080010501 }
10502 }
James Mattisb6b6a432021-06-01 22:30:36 -070010503 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080010504 }
10505
10506 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10507 @OemNetworkPreferences.OemNetworkPreference final int preference,
10508 @NonNull final Set<Integer> uids) {
10509 final List<NetworkRequest> requests = new ArrayList<>();
10510 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10511 switch (preference) {
10512 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10513 requests.add(createUnmeteredNetworkRequest());
10514 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070010515 requests.add(createDefaultInternetRequestForTransport(
10516 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080010517 break;
10518 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10519 requests.add(createUnmeteredNetworkRequest());
10520 requests.add(createOemPaidNetworkRequest());
10521 break;
10522 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10523 requests.add(createOemPaidNetworkRequest());
10524 break;
10525 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10526 requests.add(createOemPrivateNetworkRequest());
10527 break;
James Mattisfa270db2021-05-31 17:11:10 -070010528 case OEM_NETWORK_PREFERENCE_TEST:
10529 requests.add(createUnmeteredNetworkRequest());
10530 requests.add(createTestNetworkRequest());
10531 requests.add(createDefaultRequest());
10532 break;
10533 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
10534 requests.add(createTestNetworkRequest());
10535 break;
James Mattis45d81842021-01-10 14:24:24 -080010536 default:
10537 // This should never happen.
10538 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10539 + " called with invalid preference of " + preference);
10540 }
10541
James Mattisfa270db2021-05-31 17:11:10 -070010542 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090010543 for (final int uid : uids) {
10544 ranges.add(new UidRange(uid, uid));
10545 }
10546 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080010547 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080010548 }
10549
10550 private NetworkRequest createUnmeteredNetworkRequest() {
10551 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10552 .addCapability(NET_CAPABILITY_NOT_METERED)
10553 .addCapability(NET_CAPABILITY_VALIDATED);
10554 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10555 }
10556
10557 private NetworkRequest createOemPaidNetworkRequest() {
10558 // NET_CAPABILITY_OEM_PAID is a restricted capability.
10559 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10560 .addCapability(NET_CAPABILITY_OEM_PAID)
10561 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10562 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10563 }
10564
10565 private NetworkRequest createOemPrivateNetworkRequest() {
10566 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
10567 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10568 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
10569 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10570 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10571 }
10572
10573 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070010574 final NetworkCapabilities netcap = new NetworkCapabilities();
10575 netcap.addCapability(NET_CAPABILITY_INTERNET);
10576 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
10577 return netcap;
10578 }
10579
10580 private NetworkRequest createTestNetworkRequest() {
10581 final NetworkCapabilities netcap = new NetworkCapabilities();
10582 netcap.clearAll();
10583 netcap.addTransportType(TRANSPORT_TEST);
10584 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080010585 }
James Mattis47db0582021-01-01 14:13:35 -080010586 }
markchien738ad912021-12-09 18:15:45 +080010587
10588 @Override
10589 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
10590 enforceNetworkStackOrSettingsPermission();
10591
10592 try {
10593 if (add) {
10594 mNetd.bandwidthAddNiceApp(uid);
10595 } else {
10596 mNetd.bandwidthRemoveNiceApp(uid);
10597 }
10598 } catch (RemoteException | ServiceSpecificException e) {
10599 throw new IllegalStateException(e);
10600 }
10601 }
10602
10603 @Override
10604 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
10605 enforceNetworkStackOrSettingsPermission();
10606
10607 try {
10608 if (add) {
10609 mNetd.bandwidthAddNaughtyApp(uid);
10610 } else {
10611 mNetd.bandwidthRemoveNaughtyApp(uid);
10612 }
10613 } catch (RemoteException | ServiceSpecificException e) {
10614 throw new IllegalStateException(e);
10615 }
10616 }
markchiene1561fa2021-12-09 22:00:56 +080010617
10618 @Override
10619 public void updateFirewallRule(final int chain, final int uid, final boolean allow) {
10620 enforceNetworkStackOrSettingsPermission();
10621
10622 try {
10623 mNetd.firewallSetUidRule(chain, uid,
10624 allow ? INetd.FIREWALL_RULE_ALLOW : INetd.FIREWALL_RULE_DENY);
10625 } catch (RemoteException | ServiceSpecificException e) {
10626 throw new IllegalStateException(e);
10627 }
10628 }
markchien98a6f952022-01-13 23:43:53 +080010629
10630 @Override
10631 public void setFirewallChainEnabled(final int chain, final boolean enable) {
10632 enforceNetworkStackOrSettingsPermission();
10633
10634 try {
10635 mNetd.firewallEnableChildChain(chain, enable);
10636 } catch (RemoteException | ServiceSpecificException e) {
10637 throw new IllegalStateException(e);
10638 }
10639 }
10640
markchien00a0bed2022-01-13 23:46:13 +080010641 @Override
10642 public void replaceFirewallChain(final int chain, final int[] uids) {
10643 enforceNetworkStackOrSettingsPermission();
10644
10645 try {
10646 switch (chain) {
10647 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
10648 mNetd.firewallReplaceUidChain("fw_dozable", true /* isAllowList */, uids);
10649 break;
10650 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
10651 mNetd.firewallReplaceUidChain("fw_standby", false /* isAllowList */, uids);
10652 break;
10653 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
10654 mNetd.firewallReplaceUidChain("fw_powersave", true /* isAllowList */, uids);
10655 break;
10656 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
10657 mNetd.firewallReplaceUidChain("fw_restricted", true /* isAllowList */, uids);
10658 break;
10659 default:
10660 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
10661 + chain);
10662 }
10663 } catch (RemoteException | ServiceSpecificException e) {
10664 throw new IllegalStateException(e);
10665 }
10666 }
markchien9c806112022-01-11 23:28:23 +080010667
10668 @Override
10669 public void swapActiveStatsMap() {
10670 enforceNetworkStackOrSettingsPermission();
10671 try {
10672 mNetd.trafficSwapActiveStatsMap();
10673 } catch (RemoteException | ServiceSpecificException e) {
10674 throw new IllegalStateException(e);
10675 }
10676 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070010677}