blob: 6227bb25b93e79b5ce98b9f79f7a1b728cff3714 [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;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400169import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700170import android.net.QosCallbackException;
171import android.net.QosFilter;
172import android.net.QosSocketFilter;
173import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700174import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800175import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800176import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800177import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900178import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400179import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800180import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800181import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400182import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800183import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900184import android.net.VpnTransportInfo;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900185import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900186import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800187import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900188import android.net.networkstack.ModuleNetworkStackClient;
189import android.net.networkstack.NetworkStackClientBase;
paulhu7c0a2e62021-01-08 00:51:49 +0800190import android.net.resolv.aidl.DnsHealthEventParcel;
191import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
192import android.net.resolv.aidl.Nat64PrefixEventParcel;
193import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900194import android.net.shared.PrivateDnsConfig;
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900195import android.net.util.MultinetworkPolicyTracker;
lucaslinb961efc2021-01-21 02:03:17 +0800196import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800197import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800198import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700199import android.os.Bundle;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800200import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700201import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700202import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800203import android.os.Looper;
204import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700205import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700206import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900207import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800208import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700209import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700210import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800211import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700212import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900213import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900214import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700215import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700216import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400217import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800218import android.provider.Settings;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900219import android.sysprop.NetworkProperties;
Wink Saville32506bc2013-06-29 21:10:57 -0700220import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700221import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800222import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900223import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000224import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600225import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900226import android.util.Pair;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700227import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700228import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800229
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900230import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400231import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400232import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700233import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900234import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800235import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900236import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800237import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900238import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900239import com.android.net.module.util.DeviceConfigUtils;
Chalard Jean79162542020-08-19 16:07:22 +0900240import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
241import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900242import com.android.net.module.util.LocationPermissionChecker;
lifrade6c2a2021-03-04 14:08:08 +0800243import com.android.net.module.util.NetworkCapabilitiesUtils;
paulhudf23d662021-01-25 18:53:17 +0800244import com.android.net.module.util.PermissionUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000245import com.android.net.module.util.netlink.InetDiagMessage;
Chalard Jean7284daa2019-05-30 14:58:29 +0900246import com.android.server.connectivity.AutodestructReference;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900247import com.android.server.connectivity.ConnectivityFlags;
Erik Kline32120082017-12-13 19:40:49 +0900248import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500249import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900250import com.android.server.connectivity.FullScore;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900251import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100252import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700253import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700254import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600255import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900256import com.android.server.connectivity.NetworkNotificationManager;
257import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900258import com.android.server.connectivity.NetworkOffer;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900259import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700260import com.android.server.connectivity.PermissionMonitor;
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900261import com.android.server.connectivity.ProfileNetworkPreferences;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900262import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700263import com.android.server.connectivity.QosCallbackTracker;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600264
Josh Gao461a1222020-06-16 15:58:11 -0700265import libcore.io.IoUtils;
266
The Android Open Source Project28527d22009-03-03 19:31:44 -0800267import java.io.FileDescriptor;
268import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900269import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700270import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700271import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900272import java.net.InetSocketAddress;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700273import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700274import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700275import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700276import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800277import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900278import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800279import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700280import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700281import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700282import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700283import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900284import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700285import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900286import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600287import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900288import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600289import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900290import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800291
292/**
293 * @hide
294 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800295public class ConnectivityService extends IConnectivityManager.Stub
296 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900297 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800298
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900299 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900300 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900301 private static final String NETWORK_ARG = "networks";
302 private static final String REQUEST_ARG = "requests";
Erik Klined364a242017-05-12 16:52:48 +0900303
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900304 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900305 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
306 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800307
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900308 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700309
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100310 /**
311 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
312 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800313 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100314 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
315 * (preferably via runtime resource overlays).
316 */
317 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
318 "http://connectivitycheck.gstatic.com/generate_204";
319
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700320 // TODO: create better separation between radio types and network types
321
Robert Greenwalt2034b912009-08-12 16:08:25 -0700322 // how long to wait before switching back to a radio's default network
323 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
324 // system property that can override the above value
325 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
326 "android.telephony.apn-restore";
327
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900328 // How long to wait before putting up a "This network doesn't have an Internet connection,
329 // connect anyway?" dialog after the user selects a network that doesn't validate.
330 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
331
junyulai0ac374f2020-12-14 18:41:52 +0800332 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900333 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
334 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800335 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700336
337 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900338 @VisibleForTesting
339 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700340
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900341 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700342 @VisibleForTesting
343 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900344
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900345 @VisibleForTesting
346 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800347 @VisibleForTesting
348 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900349 // True if the cell radio of the device is capable of time-sharing.
350 @VisibleForTesting
351 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900352
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800353 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800354 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800355 private final int mReleasePendingIntentDelayMs;
356
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900357 private MockableSystemProperties mSystemProperties;
358
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000359 @VisibleForTesting
360 protected final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700361
Chalard Jean9473c982021-07-29 20:03:04 +0900362 @VisibleForTesting
363 final PerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700364 @VisibleForTesting
365 final PerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700366
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900367 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700368
junyulaif2c67e42018-08-07 19:50:45 +0800369 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000370 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
371 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800372 */
Sudheer Shanka9967d462021-03-18 19:09:25 +0000373 private SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800374
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900375 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900376 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000377 // The Context is created for UserHandle.ALL.
378 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900379 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900380 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700381 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700382 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800383
Chenbo Feng15416292018-11-08 17:36:21 -0800384 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800385 protected IDnsResolver mDnsResolver;
386 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800387 protected INetd mNetd;
junyulaie7c7d2a2021-01-26 15:29:15 +0800388 private NetworkStatsManager mStatsManager;
paulhu9a9f71b2020-12-29 18:15:13 +0800389 private NetworkPolicyManager mPolicyManager;
lucaslin66f44212021-02-23 01:12:55 +0800390 private final NetdCallback mNetdCallback;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700391
Benedict Wong493e04b2018-11-09 14:45:34 -0800392 /**
393 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
394 * instances.
395 */
396 @GuardedBy("mTNSLock")
397 private TestNetworkService mTNS;
398
399 private final Object mTNSLock = new Object();
400
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700401 private String mCurrentTcpBufferSizes;
402
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900403 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
lifraf3a3492021-03-10 13:58:14 +0800404 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900405
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500406 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400407 // Tear down networks that have no chance (e.g. even if validated) of becoming
408 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500409 // all networks have been rematched against all NetworkRequests.
410 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400411 // Don't reap networks. This should be passed when some networks have not yet been
412 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500413 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900414 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500415
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900416 private enum UnneededFor {
417 LINGER, // Determine whether this network is unneeded and should be lingered.
418 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
419 }
420
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700421 /**
paulhuaa0743d2021-05-26 21:56:03 +0800422 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800423 * should have priority. The order is passed to netd which will use it together
424 * with UID ranges to generate the corresponding IP rule. This serves to
425 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800426 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800427 * Order ints passed to netd must be in the 0~999 range. Larger values code for
paulhuaa0743d2021-05-26 21:56:03 +0800428 * a lower priority, {@see NativeUidRangeConfig}
paulhue9913722021-05-26 15:19:20 +0800429 *
paulhu48291862021-07-14 14:53:57 +0800430 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
431 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800432 */
paulhu48291862021-07-14 14:53:57 +0800433 // Bound for the lowest valid preference order.
434 static final int PREFERENCE_ORDER_LOWEST = 999;
435 // Used when sending to netd to code for "no order".
436 static final int PREFERENCE_ORDER_NONE = 0;
437 // Order for requests that don't code for a per-app preference. As it is
438 // out of the valid range, the corresponding order should be
439 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800440 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800441 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
442 // Order for the default internet request. Since this must always have the
paulhuaa0743d2021-05-26 21:56:03 +0800443 // lowest priority, its value is larger than the largest acceptable value. As
paulhu48291862021-07-14 14:53:57 +0800444 // it is out of the valid range, the corresponding order should be
445 // PREFERENCE_ORDER_NONE when sending to netd.
446 static final int PREFERENCE_ORDER_DEFAULT = 1000;
paulhuaa0743d2021-05-26 21:56:03 +0800447 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800448 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
449 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800450 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800451 static final int PREFERENCE_ORDER_OEM = 10;
452 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800453 // See {@link #setProfileNetworkPreference}.
454 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800455 static final int PREFERENCE_ORDER_PROFILE = 20;
456 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800457 // better scores are connected.
458 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800459 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800460 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
paulhue9913722021-05-26 15:19:20 +0800461
462 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700463 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700464 * from one net to another. Clear happens when we get a new
465 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
466 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700467 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700468 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700469
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700470 /**
471 * used internally to reload global proxy settings
472 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700473 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700474
Robert Greenwalt34848c02011-03-25 13:09:25 -0700475 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400476 * PAC manager has received new port.
477 */
478 private static final int EVENT_PROXY_HAS_CHANGED = 16;
479
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700480 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900481 * used internally when registering NetworkProviders
482 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700483 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900484 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700485
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700486 /**
487 * used internally when registering NetworkAgents
488 * obj = Messenger
489 */
490 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
491
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700492 /**
493 * used to add a network request
494 * includes a NetworkRequestInfo
495 */
496 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
497
498 /**
499 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900500 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700501 * cancel it.
502 * includes a NetworkRequestInfo
503 */
504 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
505
506 /**
507 * used to add a network listener - no request
508 * includes a NetworkRequestInfo
509 */
510 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
511
512 /**
513 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400514 * arg1 = UID of caller
515 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700516 */
517 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
518
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700519 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900520 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700521 * obj = Messenger
522 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900523 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700524
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700525 /**
526 * used internally to expire a wakelock when transitioning
527 * from one net to another. Expire happens when we fail to find
528 * a new network (typically after 1 minute) -
529 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
530 * a replacement network.
531 */
532 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
533
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700534 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800535 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400536 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800537 */
538 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
539
540 /**
541 * used to remove a pending intent and its associated network request.
542 * arg1 = UID of caller
543 * obj = PendingIntent
544 */
545 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
546
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900547 /**
548 * used to specify whether a network should be used even if unvalidated.
549 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
550 * arg2 = whether to remember this choice in the future (1 or 0)
551 * obj = network
552 */
553 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
554
555 /**
556 * used to ask the user to confirm a connection to an unvalidated network.
557 * obj = network
558 */
559 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700560
Erik Kline05f2b402015-04-30 12:58:40 +0900561 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700562 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900563 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700564 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900565
Paul Jensenc8873fc2015-06-17 14:15:39 -0400566 /**
567 * used to add a network listener with a pending intent
568 * obj = NetworkRequestInfo
569 */
570 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
571
Hugo Benichid6b510a2017-04-06 17:22:18 +0900572 /**
573 * used to specify whether a network should not be penalized when it becomes unvalidated.
574 */
575 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
576
577 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700578 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900579 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700580 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900581
Erik Kline31b4a9e2018-01-11 21:07:29 +0900582 // Handle changes in Private DNS settings.
583 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
584
dalyk1720e542018-03-05 12:42:22 -0500585 // Handle private DNS validation status updates.
586 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
587
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900588 /**
589 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
590 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800591 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
592 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
593 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900594 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900595 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900596
597 /**
598 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
599 * config was resolved.
600 * obj = PrivateDnsConfig
601 * arg2 = netid
602 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900603 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900604
605 /**
606 * Request ConnectivityService display provisioning notification.
607 * arg1 = Whether to make the notification visible.
608 * arg2 = NetID.
609 * obj = Intent to be launched when notification selected by user, null if !arg1.
610 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900611 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900612
613 /**
lucaslin2240ef62019-03-12 13:08:03 +0800614 * Used to specify whether a network should be used even if connectivity is partial.
615 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
616 * false)
617 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
618 * obj = network
619 */
lucaslin444d43a2020-02-20 16:56:59 +0800620 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800621
622 /**
lucasline117e2e2019-10-22 18:27:33 +0800623 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
624 * Both of the arguments are bitmasks, and the value of bits come from
625 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
626 * arg1 = A bitmask to describe which probes are completed.
627 * arg2 = A bitmask to describe which probes are successful.
628 */
lucaslin444d43a2020-02-20 16:56:59 +0800629 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800630
631 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900632 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
633 * arg1 = unused
634 * arg2 = netId
635 * obj = captive portal data
636 */
lucaslin444d43a2020-02-20 16:56:59 +0800637 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900638
639 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900640 * Used by setRequireVpnForUids.
641 * arg1 = whether the specified UID ranges are required to use a VPN.
642 * obj = Array of UidRange objects.
643 */
644 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
645
646 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900647 * Used internally when setting the default networks for OemNetworkPreferences.
648 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800649 */
650 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
651
652 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800653 * Used to indicate the system default network becomes active.
654 */
655 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
656
657 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900658 * Used internally when setting a network preference for a user profile.
659 * obj = Pair<ProfileNetworkPreference, Listener>
660 */
661 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
662
663 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000664 * Event to specify that reasons for why an uid is blocked changed.
665 * arg1 = uid
666 * arg2 = blockedReasons
667 */
668 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
669
670 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900671 * Event to register a new network offer
672 * obj = NetworkOffer
673 */
674 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
675
676 /**
677 * Event to unregister an existing network offer
678 * obj = INetworkOfferCallback
679 */
680 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
681
682 /**
paulhu51f77dc2021-06-07 02:34:20 +0000683 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
684 */
685 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
686
687 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800688 * Event to set temporary allow bad wifi within a limited time to override
689 * {@code config_networkAvoidBadWifi}.
690 */
691 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
692
693 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900694 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
695 * should be shown.
696 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900697 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900698
699 /**
700 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
701 * should be hidden.
702 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900703 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900704
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800705 /**
706 * The maximum alive time to allow bad wifi configuration for testing.
707 */
708 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
709
Hugo Benichi47011212017-03-30 10:46:05 +0900710 private static String eventName(int what) {
711 return sMagicDecoderRing.get(what, Integer.toString(what));
712 }
713
paulhua10d8212020-11-10 15:32:56 +0800714 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900715 final DnsResolverServiceManager dsm = context.getSystemService(
716 DnsResolverServiceManager.class);
717 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800718 }
719
Cody Kesting73708bf2019-12-18 10:57:50 -0800720 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900721 @VisibleForTesting
722 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700723 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700724 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700725 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700726 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800727 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
728 @VisibleForTesting
729 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
730
Erik Kline32120082017-12-13 19:40:49 +0900731 private final DnsManager mDnsManager;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900732 private final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700733
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400734 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800735 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400736
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700737 private PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800738 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700739
Chalard Jean5d70ba42018-06-07 16:44:04 +0900740 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
741 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000742 @VisibleForTesting
743 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400744
Erik Kline05f2b402015-04-30 12:58:40 +0900745 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700746
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400747 private UserManager mUserManager;
748
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700749 // the set of network types that can only be enabled by system/sig apps
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900750 private List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700751
Valentin Iftime9fa35092019-09-24 13:32:13 +0200752 private Set<String> mWolSupportedInterfaces;
753
Roshan Pius08c94fb2020-01-16 12:17:17 -0800754 private final TelephonyManager mTelephonyManager;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800755 private final AppOpsManager mAppOpsManager;
756
757 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400758
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900759 private KeepaliveTracker mKeepaliveTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700760 private QosCallbackTracker mQosCallbackTracker;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900761 private NetworkNotificationManager mNotifier;
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +0900762 private LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900763
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700764 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800765 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700766
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900767 // Sequence number for NetworkProvider IDs.
768 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
769 NetworkProvider.FIRST_PROVIDER_ID);
770
Erik Klineedf878b2015-07-09 18:24:03 +0900771 // NetworkRequest activity String log entries.
772 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
773 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
774
Hugo Benichid159fdd2016-07-11 11:05:12 +0900775 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900776 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900777 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
778
Hugo Benichi47011212017-03-30 10:46:05 +0900779 private static final int MAX_WAKELOCK_LOGS = 20;
780 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900781 private int mTotalWakelockAcquisitions = 0;
782 private int mTotalWakelockReleases = 0;
783 private long mTotalWakelockDurationMs = 0;
784 private long mMaxWakelockDurationMs = 0;
785 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900786
Hugo Benichi208c0102016-07-28 17:53:06 +0900787 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900788
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700789 @GuardedBy("mBandwidthRequests")
790 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
791
Erik Kline95ecfee2016-10-02 18:02:14 +0900792 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900793 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900794
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900795 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800796 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
797 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800798
Robert Greenwalt802c1102014-06-02 15:32:02 -0700799 /**
800 * Implements support for the legacy "one network per network type" model.
801 *
802 * We used to have a static array of NetworkStateTrackers, one for each
803 * network type, but that doesn't work any more now that we can have,
804 * for example, more that one wifi network. This class stores all the
805 * NetworkAgentInfo objects that support a given type, but the legacy
806 * API will only see the first one.
807 *
808 * It serves two main purposes:
809 *
810 * 1. Provide information about "the network for a given type" (since this
811 * API only supports one).
812 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
813 * the first network for a given type changes, or if the default network
814 * changes.
815 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900816 @VisibleForTesting
817 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900818
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900819 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900820 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900821
Robert Greenwalt802c1102014-06-02 15:32:02 -0700822 /**
823 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
824 * Each list holds references to all NetworkAgentInfos that are used to
825 * satisfy requests for that network type.
826 *
827 * This array is built out at startup such that an unsupported network
828 * doesn't get an ArrayList instance, making this a tristate:
829 * unsupported, supported but not active and active.
830 *
831 * The actual lists are populated when we scan the network types that
832 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900833 *
834 * Threading model:
835 * - addSupportedType() is only called in the constructor
836 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
837 * They are therefore not thread-safe with respect to each other.
838 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
839 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900840 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900841 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700842 */
Hugo Benichi389633f2016-06-21 09:48:07 +0900843 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900844 @NonNull
845 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700846
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900847 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
848 // an entry have no timer (equivalent to -1). Lazily loaded.
849 @NonNull
850 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
851
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900852 LegacyTypeTracker(@NonNull ConnectivityService service) {
853 mService = service;
854 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700855 }
856
Chiachang Wang3bc52762021-11-25 14:17:57 +0800857 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
858 // addressed.
859 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900860 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
861 final PackageManager pm = ctx.getPackageManager();
862 if (pm.hasSystemFeature(FEATURE_WIFI)) {
863 addSupportedType(TYPE_WIFI);
864 }
865 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
866 addSupportedType(TYPE_WIFI_P2P);
867 }
868 if (tm.isDataCapable()) {
869 // Telephony does not have granular support for these types: they are either all
870 // supported, or none is supported
871 addSupportedType(TYPE_MOBILE);
872 addSupportedType(TYPE_MOBILE_MMS);
873 addSupportedType(TYPE_MOBILE_SUPL);
874 addSupportedType(TYPE_MOBILE_DUN);
875 addSupportedType(TYPE_MOBILE_HIPRI);
876 addSupportedType(TYPE_MOBILE_FOTA);
877 addSupportedType(TYPE_MOBILE_IMS);
878 addSupportedType(TYPE_MOBILE_CBS);
879 addSupportedType(TYPE_MOBILE_IA);
880 addSupportedType(TYPE_MOBILE_EMERGENCY);
881 }
882 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
883 addSupportedType(TYPE_BLUETOOTH);
884 }
885 if (pm.hasSystemFeature(FEATURE_WATCH)) {
886 // TYPE_PROXY is only used on Wear
887 addSupportedType(TYPE_PROXY);
888 }
889 // Ethernet is often not specified in the configs, although many devices can use it via
890 // USB host adapters. Add it as long as the ethernet service is here.
891 if (ctx.getSystemService(Context.ETHERNET_SERVICE) != null) {
892 addSupportedType(TYPE_ETHERNET);
893 }
894
895 // Always add TYPE_VPN as a supported type
896 addSupportedType(TYPE_VPN);
897 }
898
899 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700900 if (mTypeLists[type] != null) {
901 throw new IllegalStateException(
902 "legacy list for type " + type + "already initialized");
903 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900904 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -0700905 }
906
Robert Greenwalt802c1102014-06-02 15:32:02 -0700907 public boolean isTypeSupported(int type) {
908 return isNetworkTypeValid(type) && mTypeLists[type] != null;
909 }
910
911 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +0900912 synchronized (mTypeLists) {
913 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
914 return mTypeLists[type].get(0);
915 }
Robert Greenwalt802c1102014-06-02 15:32:02 -0700916 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900917 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700918 }
919
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900920 public int getRestoreTimerForType(int type) {
921 synchronized (mTypeLists) {
922 if (mRestoreTimers == null) {
923 mRestoreTimers = loadRestoreTimers();
924 }
925 return mRestoreTimers.getOrDefault(type, -1);
926 }
927 }
928
929 private ArrayMap<Integer, Integer> loadRestoreTimers() {
930 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900931 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900932 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
933 for (final String config : configs) {
934 final String[] splits = TextUtils.split(config, ",");
935 if (splits.length != 2) {
936 logwtf("Invalid restore timer token count: " + config);
937 continue;
938 }
939 try {
940 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
941 } catch (NumberFormatException e) {
942 logwtf("Invalid restore timer number format: " + config, e);
943 }
944 }
945 return ret;
946 }
947
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -0700948 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +0900949 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900950 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +0900951 log("Sending " + state
952 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +0900953 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900954 }
955 }
956
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900957 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
958 // network type, to preserve previous behaviour.
959 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
960 if (vpnNai != mService.getLegacyLockdownNai()) return;
961
962 if (vpnNai.declaredUnderlyingNetworks == null
963 || vpnNai.declaredUnderlyingNetworks.length != 1) {
964 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
965 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
966 return;
967 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +0900968 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900969 vpnNai.declaredUnderlyingNetworks[0]);
970 if (underlyingNai == null) return;
971
972 final int type = underlyingNai.networkInfo.getType();
973 final DetailedState state = DetailedState.CONNECTED;
974 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
975 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
976 }
977
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900978 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -0700979 public void add(int type, NetworkAgentInfo nai) {
980 if (!isTypeSupported(type)) {
981 return; // Invalid network type.
982 }
983 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
984
985 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
986 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700987 return;
988 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900989 synchronized (mTypeLists) {
990 list.add(nai);
991 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +0900992
Chalard Jean5b409c72021-02-04 13:12:59 +0900993 // Send a broadcast if this is the first network of its type or if it's the default.
994 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900995
996 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
997 // to preserve previous behaviour.
998 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +0900999 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001000 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1001 mService.sendLegacyNetworkBroadcast(nai, state, type);
1002 }
1003
1004 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1005 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001006 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001007 }
1008
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001009 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001010 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001011 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1012 if (list == null || list.isEmpty()) {
1013 return;
1014 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001015 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001016
Hugo Benichi389633f2016-06-21 09:48:07 +09001017 synchronized (mTypeLists) {
1018 if (!list.remove(nai)) {
1019 return;
1020 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001021 }
1022
Lorenzo Colitti49767722015-05-01 00:30:10 +09001023 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001024 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1025 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001026 }
1027
1028 if (!list.isEmpty() && wasFirstNetwork) {
1029 if (DBG) log("Other network available for type " + type +
1030 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001031 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001032 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001033 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001034 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001035 }
1036 }
1037
1038 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001039 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1040 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001041 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001042 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001043 }
1044 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001045
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001046 // send out another legacy broadcast - currently only used for suspend/unsuspend
1047 // toggle
1048 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001049 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001050 final DetailedState state = nai.networkInfo.getDetailedState();
1051 for (int type = 0; type < mTypeLists.length; type++) {
1052 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001053 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001054 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001055 if (isFirst || contains && isDefault) {
1056 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001057 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001058 }
1059 }
1060 }
1061
Robert Greenwalt94e22142014-07-30 16:31:24 -07001062 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001063 pw.println("mLegacyTypeTracker:");
1064 pw.increaseIndent();
1065 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001066 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001067 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001068 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001069 pw.println();
1070 pw.println("Current state:");
1071 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001072 synchronized (mTypeLists) {
1073 for (int type = 0; type < mTypeLists.length; type++) {
1074 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1075 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001076 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001077 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001078 }
1079 }
1080 pw.decreaseIndent();
1081 pw.decreaseIndent();
1082 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001083 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001084 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001085 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001086
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001087 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001088 /**
1089 * Helper class which parses out priority arguments and dumps sections according to their
1090 * priority. If priority arguments are omitted, function calls the legacy dump command.
1091 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001092 private class LocalPriorityDump {
1093 private static final String PRIORITY_ARG = "--dump-priority";
1094 private static final String PRIORITY_ARG_HIGH = "HIGH";
1095 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1096
1097 LocalPriorityDump() {}
1098
1099 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1100 doDump(fd, pw, new String[] {DIAG_ARG});
1101 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001102 }
1103
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001104 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1105 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001106 }
1107
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001108 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1109 if (args == null) {
1110 dumpNormal(fd, pw, args);
1111 return;
1112 }
1113
1114 String priority = null;
1115 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1116 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1117 argIndex++;
1118 priority = args[argIndex];
1119 }
1120 }
1121
1122 if (PRIORITY_ARG_HIGH.equals(priority)) {
1123 dumpHigh(fd, pw);
1124 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1125 dumpNormal(fd, pw, args);
1126 } else {
1127 // ConnectivityService publishes binder service using publishBinderService() with
1128 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001129 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1130 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001131 // TODO: Integrate into signal dump.
1132 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001133 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001134 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001135 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001136
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001137 /**
Daniel Brightf9e945b2020-06-15 16:10:01 -07001138 * Keeps track of the number of requests made under different uids.
1139 */
1140 public static class PerUidCounter {
1141 private final int mMaxCountPerUid;
1142
1143 // Map from UID to number of NetworkRequests that UID has filed.
James Mattis20a4a8b2021-03-28 17:41:09 -07001144 @VisibleForTesting
Daniel Brightf9e945b2020-06-15 16:10:01 -07001145 @GuardedBy("mUidToNetworkRequestCount")
James Mattis20a4a8b2021-03-28 17:41:09 -07001146 final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
Daniel Brightf9e945b2020-06-15 16:10:01 -07001147
1148 /**
1149 * Constructor
1150 *
1151 * @param maxCountPerUid the maximum count per uid allowed
1152 */
1153 public PerUidCounter(final int maxCountPerUid) {
1154 mMaxCountPerUid = maxCountPerUid;
1155 }
1156
1157 /**
1158 * Increments the request count of the given uid. Throws an exception if the number
1159 * of open requests for the uid exceeds the value of maxCounterPerUid which is the value
1160 * passed into the constructor. see: {@link #PerUidCounter(int)}.
1161 *
1162 * @throws ServiceSpecificException with
1163 * {@link ConnectivityManager.Errors.TOO_MANY_REQUESTS} if the number of requests for
1164 * the uid exceed the allowed number.
1165 *
1166 * @param uid the uid that the request was made under
1167 */
1168 public void incrementCountOrThrow(final int uid) {
1169 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001170 incrementCountOrThrow(uid, 1 /* numToIncrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001171 }
1172 }
1173
James Mattis20a4a8b2021-03-28 17:41:09 -07001174 private void incrementCountOrThrow(final int uid, final int numToIncrement) {
1175 final int newRequestCount =
1176 mUidToNetworkRequestCount.get(uid, 0) + numToIncrement;
Chalard Jean9473c982021-07-29 20:03:04 +09001177 if (newRequestCount >= mMaxCountPerUid
1178 // HACK : the system server is allowed to go over the request count limit
1179 // when it is creating requests on behalf of another app (but not itself,
1180 // so it can still detect its own request leaks). This only happens in the
1181 // per-app API flows in which case the old requests for that particular
1182 // UID will be removed soon.
1183 // TODO : instead of this hack, addPerAppDefaultNetworkRequests and other
1184 // users of transact() should unregister the requests to decrease the count
1185 // before they increase it again by creating a new NRI. Then remove the
1186 // transact() method.
1187 && (Process.myUid() == uid || Process.myUid() != Binder.getCallingUid())) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001188 throw new ServiceSpecificException(
Chalard Jean9473c982021-07-29 20:03:04 +09001189 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
1190 "Uid " + uid + " exceeded its allotted requests limit");
James Mattis20a4a8b2021-03-28 17:41:09 -07001191 }
1192 mUidToNetworkRequestCount.put(uid, newRequestCount);
1193 }
1194
Daniel Brightf9e945b2020-06-15 16:10:01 -07001195 /**
1196 * Decrements the request count of the given uid.
1197 *
1198 * @param uid the uid that the request was made under
1199 */
1200 public void decrementCount(final int uid) {
1201 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001202 decrementCount(uid, 1 /* numToDecrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001203 }
1204 }
James Mattis20a4a8b2021-03-28 17:41:09 -07001205
1206 private void decrementCount(final int uid, final int numToDecrement) {
1207 final int newRequestCount =
1208 mUidToNetworkRequestCount.get(uid, 0) - numToDecrement;
1209 if (newRequestCount < 0) {
1210 logwtf("BUG: too small request count " + newRequestCount + " for UID " + uid);
1211 } else if (newRequestCount == 0) {
1212 mUidToNetworkRequestCount.delete(uid);
1213 } else {
1214 mUidToNetworkRequestCount.put(uid, newRequestCount);
1215 }
1216 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07001217 }
1218
1219 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001220 * Dependencies of ConnectivityService, for injection in tests.
1221 */
1222 @VisibleForTesting
1223 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001224 public int getCallingUid() {
1225 return Binder.getCallingUid();
1226 }
1227
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001228 /**
1229 * Get system properties to use in ConnectivityService.
1230 */
1231 public MockableSystemProperties getSystemProperties() {
1232 return new MockableSystemProperties();
1233 }
1234
1235 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001236 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1237 */
1238 public ConnectivityResources getResources(@NonNull Context ctx) {
1239 return new ConnectivityResources(ctx);
1240 }
1241
1242 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001243 * Create a HandlerThread to use in ConnectivityService.
1244 */
1245 public HandlerThread makeHandlerThread() {
1246 return new HandlerThread("ConnectivityServiceThread");
1247 }
1248
1249 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001250 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001251 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001252 public NetworkStackClientBase getNetworkStack() {
1253 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001254 }
1255
1256 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001257 * @see ProxyTracker
1258 */
1259 public ProxyTracker makeProxyTracker(@NonNull Context context,
1260 @NonNull Handler connServiceHandler) {
1261 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1262 }
1263
1264 /**
1265 * @see NetIdManager
1266 */
1267 public NetIdManager makeNetIdManager() {
1268 return new NetIdManager();
1269 }
1270
1271 /**
1272 * @see NetworkUtils#queryUserAccess(int, int)
1273 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001274 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1275 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001276 }
1277
1278 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001279 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1280 * requires CAP_NET_ADMIN, which the unit tests do not have.
1281 */
1282 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1283 InetSocketAddress remote) {
1284 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1285 }
1286
1287 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001288 * @see MultinetworkPolicyTracker
1289 */
1290 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1291 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1292 return new MultinetworkPolicyTracker(c, h, r);
1293 }
1294
Aaron Huang330a4c02020-10-27 03:36:19 +08001295 /**
1296 * @see BatteryStatsManager
1297 */
1298 public void reportNetworkInterfaceForTransports(Context context, String iface,
1299 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001300 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001301 context.getSystemService(BatteryStatsManager.class);
1302 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1303 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001304
1305 public boolean getCellular464XlatEnabled() {
1306 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1307 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001308
1309 /**
1310 * @see PendingIntent#intentFilterEquals
1311 */
1312 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1313 return a.intentFilterEquals(b);
1314 }
1315
1316 /**
1317 * @see LocationPermissionChecker
1318 */
1319 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1320 return new LocationPermissionChecker(context);
1321 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001322
1323 /**
1324 * @see DeviceConfigUtils#isFeatureEnabled
1325 */
1326 public boolean isFeatureEnabled(Context context, String name, boolean defaultEnabled) {
1327 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, name,
1328 TETHERING_MODULE_NAME, defaultEnabled);
1329 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001330 }
1331
junyulaie7c7d2a2021-01-26 15:29:15 +08001332 public ConnectivityService(Context context) {
1333 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001334 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1335 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001336 }
1337
1338 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001339 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1340 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001341 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001342
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001343 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001344 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001345 mSystemProperties = mDeps.getSystemProperties();
1346 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001347 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001348 mResources = deps.getResources(mContext);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001349 mNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_UID);
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09001350 mSystemNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001351
Hugo Benichi208c0102016-07-28 17:53:06 +09001352 mMetricsLog = logger;
Chalard Jean96a4f4b2019-12-10 22:16:53 +09001353 mNetworkRanker = new NetworkRanker();
James Mattis45d81842021-01-10 14:24:24 -08001354 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1355 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001356 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001357 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001358 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001359 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1360 mDefaultNetworkRequests.add(mDefaultRequest);
1361 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001362
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001363 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001364 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001365
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001366 // The default WiFi request is a background request so that apps using WiFi are
1367 // migrated to a better network (typically ethernet) when one comes up, instead
1368 // of staying on WiFi forever.
1369 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1370 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1371
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001372 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1373 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1374 NetworkRequest.Type.BACKGROUND_REQUEST);
1375
Chalard Jean0702f982021-09-16 21:50:07 +09001376 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1377 // TODO: Consider making the timer customizable.
1378 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1379 mCellularRadioTimesharingCapable =
1380 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1381
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001382 mHandlerThread = mDeps.makeHandlerThread();
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001383 mHandlerThread.start();
1384 mHandler = new InternalHandler(mHandlerThread.getLooper());
1385 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001386 mConnectivityDiagnosticsHandler =
1387 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001388
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001389 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001390 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001391
junyulaie7c7d2a2021-01-26 15:29:15 +08001392 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001393 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001394 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001395 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001396
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001397 mNetd = netd;
Wink Saville32506bc2013-06-29 21:10:57 -07001398 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001399 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001400 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001401
Sudheer Shanka9967d462021-03-18 19:09:25 +00001402 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001403 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1404 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001405 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001406
1407 final PowerManager powerManager = (PowerManager) context.getSystemService(
1408 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001409 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001410 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001411
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001412 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1413 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001414 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001415 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001416 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001417 mProtectedNetworks.add(p);
1418 } else {
1419 if (DBG) loge("Ignoring protectedNetwork " + p);
1420 }
1421 }
1422
soma, kawata29444ae2019-05-23 09:30:40 +09001423 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1424
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001425 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -07001426
James Mattis02220e22021-03-13 19:27:21 -08001427 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001428 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001429 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001430 final IntentFilter userIntentFilter = new IntentFilter();
1431 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1432 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1433 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1434 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001435
James Mattis02220e22021-03-13 19:27:21 -08001436 // Listen to package add/removes for netd
1437 final IntentFilter packageIntentFilter = new IntentFilter();
1438 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1439 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1440 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1441 packageIntentFilter.addDataScheme("package");
1442 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001443 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001444
lucaslind5c2d072021-02-20 18:59:47 +08001445 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001446
lucaslin66f44212021-02-23 01:12:55 +08001447 mNetdCallback = new NetdCallback();
1448 try {
1449 mNetd.registerUnsolicitedEventListener(mNetdCallback);
1450 } catch (RemoteException | ServiceSpecificException e) {
1451 loge("Error registering event listener :" + e);
1452 }
1453
Erik Kline05f2b402015-04-30 12:58:40 +09001454 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1455 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001456
junyulai7e06ad42019-03-04 22:45:36 +08001457 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001458 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001459 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001460
1461 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001462 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001463 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1464 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001465 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001466 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1467 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001468
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001469 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001470 mContext, mHandler, () -> updateAvoidBadWifi());
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001471 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001472
Chiachang Wangc1215d32020-10-20 15:38:58 +08001473 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001474 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001475
Chalard Jean28018572020-12-21 18:36:52 +09001476 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1477 // request that doesn't allow fallback to the default network. It should never be visible
1478 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1479 // arguments like the handler or the DnsResolver.
1480 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001481 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001482 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001483 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001484 new LinkProperties(), new NetworkCapabilities(),
1485 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001486 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1487 mLingerDelayMs, mQosCallbackTracker, mDeps);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001488 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001489
Chalard Jean46adcf32018-04-18 20:18:38 +09001490 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001491 return createDefaultNetworkCapabilitiesForUidRange(new UidRange(uid, uid));
1492 }
1493
1494 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRange(
1495 @NonNull final UidRange uids) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001496 final NetworkCapabilities netCap = new NetworkCapabilities();
1497 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001498 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001499 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Chiachang Wang8156c4e2021-03-19 00:45:39 +00001500 netCap.setUids(UidRange.toIntRanges(Collections.singleton(uids)));
Chalard Jean46adcf32018-04-18 20:18:38 +09001501 return netCap;
1502 }
1503
James Mattis45d81842021-01-10 14:24:24 -08001504 private NetworkRequest createDefaultRequest() {
1505 return createDefaultInternetRequestForTransport(
1506 TYPE_NONE, NetworkRequest.Type.REQUEST);
1507 }
1508
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001509 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001510 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001511 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001512 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001513 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001514 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001515 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001516 netCap.addTransportType(transportType);
1517 }
James Mattis45d81842021-01-10 14:24:24 -08001518 return createNetworkRequest(type, netCap);
1519 }
1520
1521 private NetworkRequest createNetworkRequest(
1522 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001523 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001524 }
1525
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001526 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1527 NetworkRequest.Type type) {
1528 final NetworkCapabilities netCap = new NetworkCapabilities();
1529 netCap.clearAll();
1530 netCap.addCapability(capability);
1531 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1532 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1533 }
1534
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001535 // Used only for testing.
1536 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001537 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001538 // changing ContentResolver to make registerContentObserver non-final).
1539 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1540 // by subclassing SettingsObserver.
1541 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001542 void updateAlwaysOnNetworks() {
1543 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001544 }
1545
Erik Kline9a62f012018-03-21 07:18:33 -07001546 // See FakeSettingsProvider comment above.
1547 @VisibleForTesting
1548 void updatePrivateDnsSettings() {
1549 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1550 }
1551
paulhu51f77dc2021-06-07 02:34:20 +00001552 @VisibleForTesting
1553 void updateMobileDataPreferredUids() {
1554 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1555 }
1556
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09001557 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, int id) {
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001558 final boolean enable = mContext.getResources().getBoolean(id);
1559 handleAlwaysOnNetworkRequest(networkRequest, enable);
1560 }
1561
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001562 private void handleAlwaysOnNetworkRequest(
1563 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001564 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001565 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001566 handleAlwaysOnNetworkRequest(networkRequest, enable);
1567 }
1568
1569 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001570 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001571 if (enable == isEnabled) {
1572 return; // Nothing to do.
1573 }
1574
1575 if (enable) {
1576 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001577 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001578 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001579 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001580 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001581 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1582 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001583 }
1584 }
1585
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001586 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001587 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1588 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1589 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1590 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001591 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1592 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001593 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001594 }
1595
paulhu51f77dc2021-06-07 02:34:20 +00001596 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001597 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001598 private void registerSettingsCallbacks() {
1599 // Watch for global HTTP proxy changes.
1600 mSettingsObserver.observe(
1601 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1602 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1603
1604 // Watch for whether or not to keep mobile data always on.
1605 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001606 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001607 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1608
1609 // Watch for whether or not to keep wifi always on.
1610 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001611 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001612 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001613
1614 // Watch for mobile data preferred uids changes.
1615 mSettingsObserver.observe(
1616 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1617 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001618 }
1619
Erik Kline31b4a9e2018-01-11 21:07:29 +09001620 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001621 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1622 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001623 }
1624 }
1625
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001626 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001627 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1628 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001629 return mNextNetworkRequestId++;
1630 }
1631
junyulai74f9a8b2018-06-13 15:00:37 +08001632 @VisibleForTesting
1633 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001634 if (network == null) {
1635 return null;
1636 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001637 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001638 }
1639
1640 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001641 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001642 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001643 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001644 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001645
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001646 // TODO: determine what to do when more than one VPN applies to |uid|.
1647 private NetworkAgentInfo getVpnForUid(int uid) {
1648 synchronized (mNetworkForNetId) {
1649 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1650 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
1651 if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) {
1652 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001653 }
1654 }
1655 }
1656 return null;
1657 }
1658
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001659 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001660 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001661 final NetworkAgentInfo nai = getVpnForUid(uid);
1662 if (nai != null) return nai.declaredUnderlyingNetworks;
1663 return null;
1664 }
1665
Lorenzo Colittia7574052021-01-19 01:33:05 +09001666 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001667 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001668
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001669 final Network[] networks = getVpnUnderlyingNetworks(uid);
1670 if (networks != null) {
1671 // getUnderlyingNetworks() returns:
1672 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1673 // empty array => the VPN explicitly said "no default network".
1674 // non-empty array => the VPN specified one or more default networks; we use the
1675 // first one.
1676 if (networks.length > 0) {
1677 nai = getNetworkAgentInfoForNetwork(networks[0]);
1678 } else {
1679 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001680 }
1681 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001682 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001683 }
1684
1685 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001686 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001687 */
paulhu7aeba372020-12-30 00:42:19 +08001688 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1689 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001690 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001691 if (ignoreBlocked) {
1692 return false;
1693 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001694 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001695 final long ident = Binder.clearCallingIdentity();
1696 try {
1697 final boolean metered = nc == null ? true : nc.isMetered();
1698 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1699 } finally {
1700 Binder.restoreCallingIdentity(ident);
1701 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001702 }
1703
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001704 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001705 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1706 return;
1707 }
Hugo Benichi47011212017-03-30 10:46:05 +09001708 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001709 synchronized (mBlockedAppUids) {
1710 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001711 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001712 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001713 blocked = false;
1714 } else {
1715 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001716 }
1717 }
Hugo Benichi47011212017-03-30 10:46:05 +09001718 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1719 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1720 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001721 }
1722
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001723 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001724 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1725 return;
1726 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001727 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001728 final int requestId = nri.getActiveRequest() != null
1729 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001730 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001731 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001732 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001733 }
1734
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001735 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001736 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001737 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001738 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001739 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001740 @NonNull
1741 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1742 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001743 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1744 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1745 // but only exists if an app asks about them or requests them. Ensure the requesting app
1746 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001747 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001748 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1749 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1750 null /* extraInfo */);
1751 }
1752 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001753 return filtered;
1754 }
1755
1756 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1757 boolean ignoreBlocked) {
1758 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1759 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001760 }
1761
1762 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001763 * Return NetworkInfo for the active (i.e., connected) network interface.
1764 * It is assumed that at most one network is active at a time. If more
1765 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001766 * @return the info for the active network, or {@code null} if none is
1767 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001768 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001769 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001770 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001771 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001772 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001773 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1774 if (nai == null) return null;
1775 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1776 maybeLogBlockedNetworkInfo(networkInfo, uid);
1777 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001778 }
1779
Paul Jensen1f567382015-02-13 14:18:39 -05001780 @Override
1781 public Network getActiveNetwork() {
1782 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001783 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00001784 }
1785
1786 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001787 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001788 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001789 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001790 }
1791
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001792 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001793 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1794 if (vpnNai != null) {
1795 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1796 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1797 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09001798 }
Paul Jensen1f567382015-02-13 14:18:39 -05001799 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001800
James Mattis2516da32021-01-31 17:06:19 -08001801 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001802 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1803 ignoreBlocked)) {
1804 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001805 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001806 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05001807 }
1808
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001809 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001810 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001811 PermissionUtils.enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001812 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1813 if (nai == null) return null;
1814 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001815 }
1816
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001817 /** Returns a NetworkInfo object for a network that doesn't exist. */
1818 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1819 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1820 getNetworkTypeName(networkType), "" /* subtypeName */);
1821 info.setIsAvailable(true);
1822 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1823 // background data is restricted.
1824 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1825 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1826 ? DetailedState.BLOCKED
1827 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001828 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1829 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001830 return info;
1831 }
1832
Lorenzo Colittia7574052021-01-19 01:33:05 +09001833 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001834 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1835 return null;
1836 }
1837 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001838 if (nai == null) {
1839 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001840 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001841 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1842 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001843 }
1844
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001845 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001846 public NetworkInfo getNetworkInfo(int networkType) {
1847 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001848 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001849 if (getVpnUnderlyingNetworks(uid) != null) {
1850 // A VPN is active, so we may need to return one of its underlying networks. This
1851 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09001852 // getNetworkAgentInfoForUid.
1853 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1854 if (nai == null) return null;
1855 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1856 if (networkInfo.getType() == networkType) {
1857 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001858 }
1859 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001860 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001861 }
1862
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001863 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001864 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001865 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001866 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001867 if (nai == null) return null;
1868 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001869 }
1870
1871 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001872 public NetworkInfo[] getAllNetworkInfo() {
1873 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08001874 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04001875 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1876 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001877 NetworkInfo info = getNetworkInfo(networkType);
1878 if (info != null) {
1879 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001880 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001881 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001882 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001883 }
1884
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001885 @Override
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001886 public Network getNetworkForType(int networkType) {
1887 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001888 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1889 return null;
1890 }
1891 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1892 if (nai == null) {
1893 return null;
1894 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001895 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001896 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
1897 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001898 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001899 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001900 }
1901
1902 @Override
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001903 public Network[] getAllNetworks() {
1904 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001905 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04001906 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001907 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04001908 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001909 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04001910 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001911 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001912 }
1913
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001914 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08001915 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001916 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001917 // The basic principle is: if an app's traffic could possibly go over a
1918 // network, without the app doing anything multinetwork-specific,
1919 // (hence, by "default"), then include that network's capabilities in
1920 // the array.
1921 //
1922 // In the normal case, app traffic only goes over the system's default
1923 // network connection, so that's the only network returned.
1924 //
1925 // With a VPN in force, some app traffic may go into the VPN, and thus
1926 // over whatever underlying networks the VPN specifies, while other app
1927 // traffic may go over the system default network (e.g.: a split-tunnel
1928 // VPN, or an app disallowed by the VPN), so the set of networks
1929 // returned includes the VPN's underlying networks and the system
1930 // default.
1931 enforceAccessPermission();
1932
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001933 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001934
James Mattis2516da32021-01-31 17:06:19 -08001935 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
1936 if (!nri.isBeingSatisfied()) {
1937 continue;
1938 }
1939 final NetworkAgentInfo nai = nri.getSatisfier();
1940 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
1941 if (null != nc
1942 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
1943 && !result.containsKey(nai.network)) {
1944 result.put(
1945 nai.network,
1946 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08001947 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08001948 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
1949 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08001950 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001951 }
1952
Lorenzo Colittidfab3032020-12-15 00:49:41 +09001953 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09001954 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08001955 if (null != networks) {
1956 for (final Network network : networks) {
1957 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
1958 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08001959 result.put(
1960 network,
1961 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08001962 nc,
1963 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08001964 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08001965 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001966 }
1967 }
1968 }
1969
1970 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1971 out = result.values().toArray(out);
1972 return out;
1973 }
1974
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001975 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001976 public boolean isNetworkSupported(int networkType) {
1977 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001978 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001979 }
1980
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001981 /**
1982 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08001983 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001984 * @return the ip properties for the active network, or {@code null} if
1985 * none is active
1986 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001987 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001988 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001989 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001990 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001991 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1992 if (nai == null) return null;
1993 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09001994 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001995 }
1996
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001997 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07001998 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001999 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002000 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002001 final LinkProperties lp = getLinkProperties(nai);
2002 if (lp == null) return null;
2003 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002004 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002005 }
2006
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002007 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002008 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002009 public LinkProperties getLinkProperties(Network network) {
2010 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002011 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2012 if (lp == null) return null;
2013 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002014 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002015 }
2016
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002017 @Nullable
2018 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002019 if (nai == null) {
2020 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002021 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002022 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002023 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002024 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002025 }
2026
Qingxi Lib2748102020-01-08 12:51:49 -08002027 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2028 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2029 }
2030
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002031 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002032 if (nai == null) return null;
2033 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002034 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002035 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002036 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002037 }
2038
2039 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002040 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2041 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002042 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002043 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002044 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002045 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002046 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002047 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002048 }
2049
Qingxi Libb8da982020-01-17 17:54:27 -08002050 @VisibleForTesting
2051 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002052 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002053 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002054 if (!checkSettingsPermission(callerPid, callerUid)) {
2055 newNc.setUids(null);
2056 newNc.setSSID(null);
lucaslin6adf5ac2021-10-19 15:04:56 +08002057 newNc.setUnderlyingNetworks(null);
Chalard Jean46adcf32018-04-18 20:18:38 +09002058 }
Etan Cohen107ae952018-12-30 17:59:59 -08002059 if (newNc.getNetworkSpecifier() != null) {
2060 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2061 }
Cody Kesting5ab1f552020-03-16 18:15:28 -07002062 newNc.setAdministratorUids(new int[0]);
Benedict Wong53de25f2021-03-24 14:01:51 -07002063 if (!checkAnyPermissionOf(
2064 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
junyulai2217bec2021-04-14 23:33:31 +08002065 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002066 }
Qingxi Libb8da982020-01-17 17:54:27 -08002067
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002068 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002069 }
2070
Roshan Pius98f59ec2021-02-23 08:47:39 -08002071 /**
2072 * Wrapper used to cache the permission check results performed for the corresponding
2073 * app. This avoid performing multiple permission checks for different fields in
2074 * NetworkCapabilities.
2075 * Note: This wrapper does not support any sort of invalidation and thus must not be
2076 * persistent or long-lived. It may only be used for the time necessary to
2077 * compute the redactions required by one particular NetworkCallback or
2078 * synchronous call.
2079 */
2080 private class RedactionPermissionChecker {
2081 private final int mCallingPid;
2082 private final int mCallingUid;
2083 @NonNull private final String mCallingPackageName;
2084 @Nullable private final String mCallingAttributionTag;
2085
2086 private Boolean mHasLocationPermission = null;
2087 private Boolean mHasLocalMacAddressPermission = null;
2088 private Boolean mHasSettingsPermission = null;
2089
2090 RedactionPermissionChecker(int callingPid, int callingUid,
2091 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2092 mCallingPid = callingPid;
2093 mCallingUid = callingUid;
2094 mCallingPackageName = callingPackageName;
2095 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002096 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002097
2098 private boolean hasLocationPermissionInternal() {
2099 final long token = Binder.clearCallingIdentity();
2100 try {
2101 return mLocationPermissionChecker.checkLocationPermission(
2102 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2103 null /* message */);
2104 } finally {
2105 Binder.restoreCallingIdentity(token);
2106 }
2107 }
2108
2109 /**
2110 * Returns whether the app holds location permission or not (might return cached result
2111 * if the permission was already checked before).
2112 */
2113 public boolean hasLocationPermission() {
2114 if (mHasLocationPermission == null) {
2115 // If there is no cached result, perform the check now.
2116 mHasLocationPermission = hasLocationPermissionInternal();
2117 }
2118 return mHasLocationPermission;
2119 }
2120
2121 /**
2122 * Returns whether the app holds local mac address permission or not (might return cached
2123 * result if the permission was already checked before).
2124 */
2125 public boolean hasLocalMacAddressPermission() {
2126 if (mHasLocalMacAddressPermission == null) {
2127 // If there is no cached result, perform the check now.
2128 mHasLocalMacAddressPermission =
2129 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2130 }
2131 return mHasLocalMacAddressPermission;
2132 }
2133
2134 /**
2135 * Returns whether the app holds settings permission or not (might return cached
2136 * result if the permission was already checked before).
2137 */
2138 public boolean hasSettingsPermission() {
2139 if (mHasSettingsPermission == null) {
2140 // If there is no cached result, perform the check now.
2141 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2142 }
2143 return mHasSettingsPermission;
2144 }
2145 }
2146
2147 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2148 @NetworkCapabilities.NetCapability long redaction) {
2149 return (redactions & redaction) != 0;
2150 }
2151
2152 /**
2153 * Use the provided |applicableRedactions| to check the receiving app's
2154 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2155 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2156 * before being sent to the corresponding app.
2157 */
2158 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2159 @NetworkCapabilities.RedactionType long applicableRedactions,
2160 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2161 boolean includeLocationSensitiveInfo) {
2162 long redactions = applicableRedactions;
2163 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2164 if (includeLocationSensitiveInfo
2165 && redactionPermissionChecker.hasLocationPermission()) {
2166 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2167 }
2168 }
2169 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2170 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2171 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2172 }
2173 }
2174 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2175 if (redactionPermissionChecker.hasSettingsPermission()) {
2176 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2177 }
2178 }
2179 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002180 }
2181
Qingxi Lib2748102020-01-08 12:51:49 -08002182 @VisibleForTesting
2183 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002184 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002185 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002186 int callingPid, int callingUid, @NonNull String callingPkgName,
2187 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002188 if (nc == null) {
2189 return null;
2190 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002191 // Avoid doing location permission check if the transport info has no location sensitive
2192 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002193 final RedactionPermissionChecker redactionPermissionChecker =
2194 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2195 callingAttributionTag);
2196 final long redactions = retrieveRequiredRedactions(
2197 nc.getApplicableRedactions(), redactionPermissionChecker,
2198 includeLocationSensitiveInfo);
2199 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002200 // Reset owner uid if not destined for the owner app.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002201 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002202 newNc.setOwnerUid(INVALID_UID);
2203 return newNc;
2204 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002205 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2206 if (nc.hasTransport(TRANSPORT_VPN)) {
2207 // Owner UIDs already checked above. No need to re-check.
2208 return newNc;
2209 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002210 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2211 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002212 // compatibility for older apps.
2213 if (!includeLocationSensitiveInfo
2214 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002215 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002216 newNc.setOwnerUid(INVALID_UID);
2217 return newNc;
2218 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002219 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002220 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002221 newNc.setOwnerUid(INVALID_UID);
2222 }
Qingxi Lib2748102020-01-08 12:51:49 -08002223 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002224 }
2225
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002226 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2227 LinkProperties lp, int callerPid, int callerUid) {
2228 if (lp == null) return new LinkProperties();
2229
2230 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2231 final boolean needsSanitization =
2232 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2233 if (!needsSanitization) {
2234 return new LinkProperties(lp);
2235 }
2236
2237 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002238 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002239 }
2240
2241 final LinkProperties newLp = new LinkProperties(lp);
2242 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2243 // object gets parceled.
2244 newLp.setCaptivePortalApiUrl(null);
2245 newLp.setCaptivePortalData(null);
2246 return newLp;
2247 }
2248
Roshan Pius08c94fb2020-01-16 12:17:17 -08002249 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2250 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002251 // There is no need to track the effective UID of the request here. If the caller
2252 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002253 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002254 // Unprivileged apps can only pass in null or their own UID.
2255 if (nc.getUids() == null) {
2256 // If the caller passes in null, the callback will also match networks that do not
2257 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2258 // In this case, redact everything in the request immediately. This ensures that the
2259 // app is not able to get any redacted information by filing an unredacted request
2260 // and observing whether the request matches something.
2261 if (nc.getNetworkSpecifier() != null) {
2262 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2263 }
2264 } else {
2265 nc.setSingleUid(callerUid);
2266 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002267 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002268 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002269 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002270
2271 // Clear owner UID; this can never come from an app.
2272 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002273 }
2274
Chalard Jean38354d12018-03-20 19:13:57 +09002275 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002276 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002277 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2278 }
2279 }
2280
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002281 @Override
2282 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2283 enforceAccessPermission();
2284 final int callerUid = Binder.getCallingUid();
2285 final long token = Binder.clearCallingIdentity();
2286 try {
2287 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2288 } finally {
2289 Binder.restoreCallingIdentity(token);
2290 }
2291 }
2292
junyulaiebd15162021-03-03 12:09:05 +08002293 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002294 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002295 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002296 // This contains IMSI details, so make sure the caller is privileged.
paulhudf23d662021-01-25 18:53:17 +08002297 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002298
Serik Beketayev05130302021-01-15 16:47:25 -08002299 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002300 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002301 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2302 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002303 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002304 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002305 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002306 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2307 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002308 }
2309 }
2310 return result.toArray(new NetworkState[result.size()]);
2311 }
2312
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002313 @Override
junyulaiebd15162021-03-03 12:09:05 +08002314 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002315 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002316 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002317 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002318
2319 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2320 for (Network network : getAllNetworks()) {
2321 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Junyu Laiddecb662021-08-17 08:44:36 +00002322 if (nai != null && nai.everConnected) {
junyulaiebd15162021-03-03 12:09:05 +08002323 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2324 // NetworkCapabilities, which may contain UIDs of apps to which the
2325 // network applies. Should the UIDs be cleared so as not to leak or
2326 // interfere ?
2327 result.add(nai.getNetworkStateSnapshot());
2328 }
2329 }
2330 return result;
2331 }
2332
2333 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002334 public boolean isActiveNetworkMetered() {
2335 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002336
Qingxi Lib2748102020-01-08 12:51:49 -08002337 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002338 if (caps != null) {
2339 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2340 } else {
2341 // Always return the most conservative value
2342 return true;
2343 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002344 }
2345
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002346 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002347 * Ensures that the system cannot call a particular method.
2348 */
2349 private boolean disallowedBecauseSystemCaller() {
2350 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002351 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2352 // for devices launched with Q and above. However, existing devices upgrading to Q and
2353 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002354 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002355 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002356 log("This method exists only for app backwards compatibility"
2357 + " and must not be called by system services.");
2358 return true;
2359 }
2360 return false;
2361 }
2362
paulhub2c28682021-08-18 18:35:54 +08002363 private int getAppUid(final String app, final UserHandle user) {
2364 final PackageManager pm =
2365 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2366 final long token = Binder.clearCallingIdentity();
2367 try {
2368 return pm.getPackageUid(app, 0 /* flags */);
2369 } catch (PackageManager.NameNotFoundException e) {
2370 return -1;
2371 } finally {
2372 Binder.restoreCallingIdentity(token);
2373 }
2374 }
2375
2376 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2377 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2378 if (getAppUid(packageName, user) != callingUid) {
2379 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2380 }
2381 }
2382
Lorenzo Colitti23862912018-09-28 11:31:55 +09002383 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002384 * Ensure that a network route exists to deliver traffic to the specified
2385 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002386 * @param networkType the type of the network over which traffic to the
2387 * specified host is to be routed
2388 * @param hostAddress the IP address of the host to which the route is
2389 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002390 * @return {@code true} on success, {@code false} on failure
2391 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002392 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002393 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2394 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002395 if (disallowedBecauseSystemCaller()) {
2396 return false;
2397 }
paulhub2c28682021-08-18 18:35:54 +08002398 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002399 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002400 if (mProtectedNetworks.contains(networkType)) {
paulhu8e96a752019-08-12 16:25:11 +08002401 enforceConnectivityRestrictedNetworksPermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002402 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002403
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002404 InetAddress addr;
2405 try {
2406 addr = InetAddress.getByAddress(hostAddress);
2407 } catch (UnknownHostException e) {
2408 if (DBG) log("requestRouteToHostAddress got " + e.toString());
2409 return false;
2410 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002411
The Android Open Source Project28527d22009-03-03 19:31:44 -08002412 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002413 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002414 return false;
2415 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002416
2417 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2418 if (nai == null) {
2419 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
2420 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2421 } else {
2422 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2423 }
2424 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002425 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002426
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002427 DetailedState netState;
2428 synchronized (nai) {
2429 netState = nai.networkInfo.getDetailedState();
2430 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002431
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002432 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002433 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002434 log("requestRouteToHostAddress on down network "
2435 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002436 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002437 }
2438 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002439 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002440
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002441 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002442 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002443 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002444 LinkProperties lp;
2445 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002446 synchronized (nai) {
2447 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002448 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002449 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002450 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002451 if (DBG) {
2452 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2453 }
Wink Saville32506bc2013-06-29 21:10:57 -07002454 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002455 } finally {
2456 Binder.restoreCallingIdentity(token);
2457 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002458 }
2459
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002460 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002461 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002462 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002463 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002464 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002465 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002466 if (bestRoute.getGateway().equals(addr)) {
2467 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002468 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002469 } else {
2470 // if we will connect to this through another route, add a direct route
2471 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002472 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002473 }
2474 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002475 if (DBG) log("Adding legacy route " + bestRoute +
2476 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002477
2478 final String dst = bestRoute.getDestinationLinkAddress().toString();
2479 final String nextHop = bestRoute.hasGateway()
2480 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002481 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002482 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2483 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002484 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002485 return false;
2486 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002487 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002488 }
2489
paulhu7c0a2e62021-01-08 00:51:49 +08002490 class DnsResolverUnsolicitedEventCallback extends
2491 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002492 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002493 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002494 try {
2495 mHandler.sendMessage(mHandler.obtainMessage(
2496 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002497 new PrivateDnsValidationUpdate(event.netId,
2498 InetAddresses.parseNumericAddress(event.ipAddress),
2499 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002500 } catch (IllegalArgumentException e) {
2501 loge("Error parsing ip address in validation event");
2502 }
2503 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002504
2505 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002506 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2507 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002508 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2509 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2510 // event callback for certain nai. e.g. cellular. Register here to pass to
2511 // NetworkMonitor instead.
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002512 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allow one
2513 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2514 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002515 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002516 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002517 }
2518 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002519
2520 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002521 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2522 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2523 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002524 }
dalyk1720e542018-03-05 12:42:22 -05002525
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002526 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002527 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002528 return this.VERSION;
2529 }
2530
2531 @Override
2532 public String getInterfaceHash() {
2533 return this.HASH;
2534 }
paulhu7c0a2e62021-01-08 00:51:49 +08002535 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002536
2537 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002538 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2539 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002540
paulhu7c0a2e62021-01-08 00:51:49 +08002541 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002542 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002543 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002544 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002545 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002546 }
2547 }
2548
Sudheer Shanka9967d462021-03-18 19:09:25 +00002549 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002550 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002551 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002552 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2553 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002554 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002555 };
2556
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002557 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002558 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002559 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002560 }
2561
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002562 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002563 for (String permission : permissions) {
2564 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002565 return true;
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002566 }
2567 }
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002568 return false;
2569 }
2570
paulhu1a407652019-03-22 16:35:06 +08002571 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2572 for (String permission : permissions) {
2573 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2574 return true;
2575 }
2576 }
2577 return false;
2578 }
2579
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002580 private void enforceAnyPermissionOf(String... permissions) {
2581 if (!checkAnyPermissionOf(permissions)) {
2582 throw new SecurityException("Requires one of the following permissions: "
2583 + String.join(", ", permissions) + ".");
2584 }
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002585 }
2586
Paul Jensen83f5d572014-08-29 09:54:01 -04002587 private void enforceInternetPermission() {
2588 mContext.enforceCallingOrSelfPermission(
2589 android.Manifest.permission.INTERNET,
2590 "ConnectivityService");
2591 }
2592
The Android Open Source Project28527d22009-03-03 19:31:44 -08002593 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002594 mContext.enforceCallingOrSelfPermission(
2595 android.Manifest.permission.ACCESS_NETWORK_STATE,
2596 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002597 }
2598
paulhua6ee2122021-02-22 15:40:43 +08002599 /**
2600 * Performs a strict and comprehensive check of whether a calling package is allowed to
2601 * change the state of network, as the condition differs for pre-M, M+, and
2602 * privileged/preinstalled apps. The caller is expected to have either the
2603 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2604 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2605 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2606 * permission and cannot be revoked. See http://b/23597341
2607 *
2608 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2609 * of this app will be updated to the current time.
2610 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002611 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002612 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2613 == PackageManager.PERMISSION_GRANTED) {
2614 return;
2615 }
2616
2617 if (callingPkg == null) {
2618 throw new SecurityException("Calling package name is null.");
2619 }
2620
2621 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2622 final int uid = mDeps.getCallingUid();
2623 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2624 callingPkg, callingAttributionTag, null /* message */);
2625
2626 if (mode == AppOpsManager.MODE_ALLOWED) {
2627 return;
2628 }
2629
2630 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2631 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2632 return;
2633 }
2634
2635 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2636 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2637 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002638 }
2639
Charles He9369e612017-05-15 17:07:18 +01002640 private void enforceSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002641 enforceAnyPermissionOf(
Charles He9369e612017-05-15 17:07:18 +01002642 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002643 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002644 }
2645
paulhu8e96a752019-08-12 16:25:11 +08002646 private void enforceNetworkFactoryPermission() {
paulhub6ba8e82020-03-04 09:43:41 +08002647 enforceAnyPermissionOf(
paulhu8e96a752019-08-12 16:25:11 +08002648 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002649 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002650 }
2651
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002652 private void enforceNetworkFactoryOrSettingsPermission() {
2653 enforceAnyPermissionOf(
2654 android.Manifest.permission.NETWORK_SETTINGS,
2655 android.Manifest.permission.NETWORK_FACTORY,
2656 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2657 }
2658
2659 private void enforceNetworkFactoryOrTestNetworksPermission() {
2660 enforceAnyPermissionOf(
2661 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2662 android.Manifest.permission.NETWORK_FACTORY,
2663 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2664 }
2665
Chalard Jean9a396cc2018-02-21 18:43:54 +09002666 private boolean checkSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002667 return checkAnyPermissionOf(
2668 android.Manifest.permission.NETWORK_SETTINGS,
2669 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002670 }
2671
2672 private boolean checkSettingsPermission(int pid, int uid) {
2673 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002674 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2675 || PERMISSION_GRANTED == mContext.checkPermission(
2676 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002677 }
2678
paulhu8e96a752019-08-12 16:25:11 +08002679 private void enforceNetworkStackOrSettingsPermission() {
2680 enforceAnyPermissionOf(
2681 android.Manifest.permission.NETWORK_SETTINGS,
2682 android.Manifest.permission.NETWORK_STACK,
2683 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2684 }
2685
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002686 private void enforceNetworkStackSettingsOrSetup() {
2687 enforceAnyPermissionOf(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002688 android.Manifest.permission.NETWORK_SETTINGS,
2689 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002690 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002691 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002692 }
2693
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002694 private void enforceAirplaneModePermission() {
2695 enforceAnyPermissionOf(
2696 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2697 android.Manifest.permission.NETWORK_SETTINGS,
2698 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2699 android.Manifest.permission.NETWORK_STACK,
2700 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2701 }
2702
James Mattis8378aec2021-01-26 14:05:36 -08002703 private void enforceOemNetworkPreferencesPermission() {
2704 mContext.enforceCallingOrSelfPermission(
2705 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2706 "ConnectivityService");
2707 }
2708
James Mattisfa270db2021-05-31 17:11:10 -07002709 private void enforceManageTestNetworksPermission() {
2710 mContext.enforceCallingOrSelfPermission(
2711 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2712 "ConnectivityService");
2713 }
2714
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002715 private boolean checkNetworkStackPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002716 return checkAnyPermissionOf(
2717 android.Manifest.permission.NETWORK_STACK,
2718 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002719 }
2720
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002721 private boolean checkNetworkStackPermission(int pid, int uid) {
2722 return checkAnyPermissionOf(pid, uid,
2723 android.Manifest.permission.NETWORK_STACK,
2724 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2725 }
2726
paulhu1a407652019-03-22 16:35:06 +08002727 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2728 return checkAnyPermissionOf(pid, uid,
2729 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002730 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2731 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002732 }
2733
Hugo Benichibd0cc762016-07-19 15:59:27 +09002734 private void enforceConnectivityRestrictedNetworksPermission() {
2735 try {
2736 mContext.enforceCallingOrSelfPermission(
2737 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2738 "ConnectivityService");
2739 return;
2740 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
paulhu8e96a752019-08-12 16:25:11 +08002741 // TODO: Remove this fallback check after all apps have declared
2742 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2743 mContext.enforceCallingOrSelfPermission(
2744 android.Manifest.permission.CONNECTIVITY_INTERNAL,
2745 "ConnectivityService");
Hugo Benichibd0cc762016-07-19 15:59:27 +09002746 }
2747
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002748 private void enforceKeepalivePermission() {
Lorenzo Colittif25beee2015-09-08 13:21:48 +09002749 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002750 }
2751
Roshan Pius98f59ec2021-02-23 08:47:39 -08002752 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2753 return PERMISSION_GRANTED == mContext.checkPermission(
2754 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2755 }
2756
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002757 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002758 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002759 }
2760
2761 private void sendInetConditionBroadcast(NetworkInfo info) {
2762 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2763 }
2764
Wink Saville4f0de1e2011-08-04 15:01:58 -07002765 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002766 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002767 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002768 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002769 if (info.isFailover()) {
2770 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2771 info.setFailover(false);
2772 }
2773 if (info.getReason() != null) {
2774 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2775 }
2776 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002777 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2778 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002779 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002780 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002781 return intent;
2782 }
2783
2784 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2785 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2786 }
2787
Chiachang Wang3bc52762021-11-25 14:17:57 +08002788 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
2789 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002790 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09002791 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09002792 if (!mSystemReady
2793 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002794 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002795 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002796 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002797 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002798 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002799 }
2800
Dianne Hackborn66dd0332015-12-09 17:22:26 -08002801 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07002802 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002803 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07002804 final NetworkInfo ni = intent.getParcelableExtra(
2805 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08002806 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2807 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2808 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08002809 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002810 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07002811 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00002812 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002813 } finally {
2814 Binder.restoreCallingIdentity(ident);
2815 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002816 }
2817 }
2818
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002819 /**
Aaron Huang96011892020-06-27 07:18:23 +08002820 * Called by SystemServer through ConnectivityManager when the system is ready.
2821 */
2822 @Override
2823 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002824 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08002825 throw new SecurityException("Calling Uid is not system uid.");
2826 }
2827 systemReadyInternal();
2828 }
2829
2830 /**
2831 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002832 */
2833 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08002834 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09002835 // Load flags after PackageManager is ready to query module version
2836 mFlags.loadFlags(mDeps, mContext);
2837
Aaron Huang9a57acf2020-12-08 10:03:29 +08002838 // Since mApps in PermissionMonitor needs to be populated first to ensure that
2839 // listening network request which is sent by MultipathPolicyTracker won't be added
2840 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
2841 // be called after PermissionMonitor#startMonitoring().
2842 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
2843 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
2844 // to ensure the tracking will be initialized correctly.
paulhuc62d3c22019-11-19 17:55:31 +08002845 mPermissionMonitor.startMonitoring();
Chalard Jeane4f9bd92018-06-08 12:47:42 +09002846 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08002847 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002848
Hugo Benichie5220992017-04-26 14:53:28 +09002849 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002850 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002851 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07002852 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002853 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002854 }
2855 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002856
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002857 // Create network requests for always-on networks.
2858 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00002859
2860 // Update mobile data preference if necessary.
2861 // Note that empty uid list can be skip here only because no uid rules applied before system
2862 // ready. Normally, the empty uid list means to clear the uids rules on netd.
2863 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
2864 updateMobileDataPreferredUids();
2865 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002866 }
2867
The Android Open Source Project28527d22009-03-03 19:31:44 -08002868 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002869 * Start listening for default data network activity state changes.
2870 */
2871 @Override
2872 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08002873 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002874 }
2875
2876 /**
2877 * Stop listening for default data network activity state changes.
2878 */
2879 @Override
2880 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08002881 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002882 }
2883
2884 /**
2885 * Check whether the default network radio is currently active.
2886 */
2887 @Override
2888 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08002889 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002890 }
2891
2892 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09002893 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09002894 * and set it on it's iface.
2895 */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002896 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2897 final String iface = newLp.getInterfaceName();
2898 final int mtu = newLp.getMtu();
Pierre Imai07c53a32016-02-08 16:01:40 +09002899 if (oldLp == null && mtu == 0) {
2900 // Silently ignore unset MTU value.
2901 return;
2902 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002903 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2904 if (VDBG) log("identical MTU - not setting");
2905 return;
2906 }
paulhucbbc3db2019-03-08 16:35:20 +08002907 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002908 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002909 return;
2910 }
sy.yun4aa73922013-09-02 05:24:09 +09002911
w19976e714f1d2014-08-05 15:18:11 -07002912 // Cannot set MTU without interface name
2913 if (TextUtils.isEmpty(iface)) {
2914 loge("Setting MTU size with null iface.");
2915 return;
2916 }
2917
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002918 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09002919 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08002920 mNetd.interfaceSetMtu(iface, mtu);
2921 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08002922 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002923 }
2924 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002925
Chenbo Feng15416292018-11-08 17:36:21 -08002926 @VisibleForTesting
2927 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04002928
lucaslin821c9782018-11-28 19:27:52 +08002929 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002930 String[] values = null;
2931 if (tcpBufferSizes != null) {
2932 values = tcpBufferSizes.split(",");
2933 }
2934
2935 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07002936 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002937 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2938 values = tcpBufferSizes.split(",");
2939 }
2940
2941 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2942
2943 try {
Aaron Huang6616df32020-10-30 22:04:25 +08002944 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002945
Chenbo Feng15416292018-11-08 17:36:21 -08002946 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2947 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2948 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002949 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08002950 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002951 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002952 }
2953 }
2954
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07002955 @Override
2956 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09002957 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07002958 NETWORK_RESTORE_DELAY_PROP_NAME);
2959 if(restoreDefaultNetworkDelayStr != null &&
2960 restoreDefaultNetworkDelayStr.length() != 0) {
2961 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01002962 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002963 } catch (NumberFormatException e) {
2964 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002965 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002966 // if the system property isn't set, use the value for the apn type
2967 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2968
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09002969 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
2970 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002971 }
2972 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002973 }
2974
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002975 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2976 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2977 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09002978 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08002979 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002980 // Start gathering diagnostic information.
2981 netDiags.add(new NetworkDiagnostics(
2982 nai.network,
2983 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08002984 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002985 DIAG_TIME_MS));
2986 }
2987
2988 for (NetworkDiagnostics netDiag : netDiags) {
2989 pw.println();
2990 netDiag.waitForMeasurements();
2991 netDiag.dump(pw);
2992 }
2993 }
2994
The Android Open Source Project28527d22009-03-03 19:31:44 -08002995 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09002996 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
2997 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08002998 if (!checkDumpPermission(mContext, TAG, writer)) return;
2999
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003000 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003001 }
3002
lucaslin99473f62020-12-10 15:10:54 +08003003 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3004 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3005 != PackageManager.PERMISSION_GRANTED) {
3006 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003007 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003008 + " due to missing android.permission.DUMP permission");
3009 return false;
3010 } else {
3011 return true;
3012 }
3013 }
3014
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003015 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003016 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003017
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003018 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003019 dumpNetworkDiagnostics(pw);
3020 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003021 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003022 dumpNetworks(pw);
3023 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003024 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003025 dumpNetworkRequests(pw);
3026 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003027 }
Erik Kline9647f382015-06-05 17:47:34 +09003028
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003029 pw.print("NetworkProviders for:");
3030 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
3031 pw.print(" " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003032 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09003033 pw.println();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003034 pw.println();
3035
Chalard Jean5b409c72021-02-04 13:12:59 +09003036 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003037 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003038 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003039 pw.println("none");
3040 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003041 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003042 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003043 pw.println();
3044
James Mattis8b298a02021-06-01 22:34:04 -07003045 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003046 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003047 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003048 pw.decreaseIndent();
3049 pw.println();
3050
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003051 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003052 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003053 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003054 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003055 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003056
junyulaif2c67e42018-08-07 19:50:45 +08003057 pw.println("Status for known UIDs:");
3058 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003059 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003060 for (int i = 0; i < size; i++) {
3061 // Don't crash if the array is modified while dumping in bugreports.
3062 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003063 final int uid = mUidBlockedReasons.keyAt(i);
3064 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3065 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003066 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003067 } catch (ArrayIndexOutOfBoundsException e) {
3068 pw.println(" ArrayIndexOutOfBoundsException");
3069 } catch (ConcurrentModificationException e) {
3070 pw.println(" ConcurrentModificationException");
3071 }
3072 }
3073 pw.println();
3074 pw.decreaseIndent();
3075
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003076 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003077 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003078 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003079 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003080 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003081
Robert Greenwalt94e22142014-07-30 16:31:24 -07003082 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003083
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003084 pw.println();
markchien5e866652019-09-30 14:40:57 +08003085 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003086
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003087 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003088 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003089
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003090 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003091
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003092 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003093 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003094 pw.println("mNetworkRequestInfoLogs (most recent first):");
3095 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003096 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003097 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003098
3099 pw.println();
3100 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3101 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003102 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003103 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003104
3105 pw.println();
3106 pw.println("NetTransition WakeLock activity (most recent first):");
3107 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003108 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3109 pw.println("total releases: " + mTotalWakelockReleases);
3110 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3111 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3112 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3113 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3114 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3115 }
James Mattiscb1e0362021-04-06 17:07:42 -07003116 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003117
3118 pw.println();
3119 pw.println("bandwidth update requests (by uid):");
3120 pw.increaseIndent();
3121 synchronized (mBandwidthRequests) {
3122 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3123 pw.println("[" + mBandwidthRequests.keyAt(i)
3124 + "]: " + mBandwidthRequests.valueAt(i));
3125 }
3126 }
3127 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003128 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003129
James Mattiscb1e0362021-04-06 17:07:42 -07003130 pw.println();
3131 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3132 pw.increaseIndent();
3133 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003134 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003135 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003136
3137 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003138
3139 pw.println();
3140 pw.println("Permission Monitor:");
3141 pw.increaseIndent();
3142 mPermissionMonitor.dump(pw);
3143 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003144
3145 pw.println();
3146 pw.println("Legacy network activity:");
3147 pw.increaseIndent();
3148 mNetworkActivityTracker.dump(pw);
3149 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003150 }
3151
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003152 private void dumpNetworks(IndentingPrintWriter pw) {
3153 for (NetworkAgentInfo nai : networksSortedById()) {
3154 pw.println(nai.toString());
3155 pw.increaseIndent();
3156 pw.println(String.format(
3157 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3158 nai.numForegroundNetworkRequests(),
3159 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3160 nai.numBackgroundNetworkRequests(),
3161 nai.numNetworkRequests()));
3162 pw.increaseIndent();
3163 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3164 pw.println(nai.requestAt(i).toString());
3165 }
3166 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003167 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003168 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003169 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003170 pw.decreaseIndent();
3171 pw.decreaseIndent();
3172 }
3173 }
3174
James Mattis8b298a02021-06-01 22:34:04 -07003175 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3176 if (!mProfileNetworkPreferences.isEmpty()) {
3177 pw.println("Profile preferences:");
3178 pw.increaseIndent();
3179 pw.println(mProfileNetworkPreferences.preferences);
3180 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003181 }
James Mattis8b298a02021-06-01 22:34:04 -07003182 if (!mOemNetworkPreferences.isEmpty()) {
3183 pw.println("OEM preferences:");
3184 pw.increaseIndent();
3185 pw.println(mOemNetworkPreferences);
3186 pw.decreaseIndent();
3187 }
3188 if (!mMobileDataPreferredUids.isEmpty()) {
3189 pw.println("Mobile data preferred UIDs:");
3190 pw.increaseIndent();
3191 pw.println(mMobileDataPreferredUids);
3192 pw.decreaseIndent();
3193 }
James Mattis45d81842021-01-10 14:24:24 -08003194
James Mattis8b298a02021-06-01 22:34:04 -07003195 pw.println("Default requests:");
3196 pw.increaseIndent();
3197 dumpPerAppDefaultRequests(pw);
3198 pw.decreaseIndent();
3199 }
3200
3201 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003202 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3203 if (mDefaultRequest == defaultRequest) {
3204 continue;
3205 }
3206
James Mattis8b298a02021-06-01 22:34:04 -07003207 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3208 final String networkOutput;
3209 if (null == satisfier) {
3210 networkOutput = "null";
3211 } else if (mNoServiceNetwork.equals(satisfier)) {
3212 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003213 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003214 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003215 }
James Mattis8b298a02021-06-01 22:34:04 -07003216 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3217 ? "" : " asUid: " + defaultRequest.mAsUid;
3218 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3219 + defaultRequest.mPid + asUidString + "]";
3220 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3221 + " Preference order: " + defaultRequest.mPreferenceOrder
3222 + " Tracked UIDs: " + defaultRequest.getUids();
3223 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003224 }
3225 }
3226
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003227 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003228 NetworkRequestInfo[] infos = null;
3229 while (infos == null) {
3230 try {
3231 infos = requestsSortedById();
3232 } catch (ConcurrentModificationException e) {
3233 // mNetworkRequests should only be accessed from handler thread, except dump().
3234 // As dump() is never called in normal usage, it would be needlessly expensive
3235 // to lock the collection only for its benefit. Instead, retry getting the
3236 // requests if ConcurrentModificationException is thrown during dump().
3237 }
3238 }
3239 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003240 pw.println(nri.toString());
3241 }
3242 }
3243
Chalard Jean524f0b12021-10-25 21:11:56 +09003244 private void dumpAllRequestInfoLogsToLogcat() {
3245 try (PrintWriter logPw = new PrintWriter(new Writer() {
3246 @Override
3247 public void write(final char[] cbuf, final int off, final int len) {
3248 // This method is called with 0-length and 1-length arrays for empty strings
3249 // or strings containing only the DEL character.
3250 if (len <= 1) return;
3251 Log.e(TAG, new String(cbuf, off, len));
3252 }
3253 @Override public void flush() {}
3254 @Override public void close() {}
3255 })) {
3256 mNetworkRequestInfoLogs.dump(logPw);
3257 }
3258 }
3259
Hugo Benichia480ba52018-09-03 08:19:02 +09003260 /**
3261 * Return an array of all current NetworkAgentInfos sorted by network id.
3262 */
3263 private NetworkAgentInfo[] networksSortedById() {
3264 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003265 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003266 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003267 return networks;
3268 }
3269
3270 /**
3271 * Return an array of all current NetworkRequest sorted by request id.
3272 */
James Mattis258ea3c2020-11-15 15:04:40 -08003273 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003274 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003275 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003276 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003277 // Sort the array based off the NRI containing the min requestId in its requests.
3278 Arrays.sort(requests,
3279 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3280 Comparator.comparingInt(req -> req.requestId)).requestId
3281 )
3282 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003283 return requests;
3284 }
3285
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003286 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003287 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003288 if (officialNai != null && officialNai.equals(nai)) return true;
3289 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003290 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003291 " - " + nai);
3292 }
3293 return false;
3294 }
3295
Robert Greenwalt2034b912009-08-12 16:08:25 -07003296 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003297 private class NetworkStateTrackerHandler extends Handler {
3298 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003299 super(looper);
3300 }
3301
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003302 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003303 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3304 final NetworkAgentInfo nai = arg.first;
3305 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003306 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003307 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003308 }
3309 return;
3310 }
3311
3312 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003313 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003314 NetworkCapabilities networkCapabilities = (NetworkCapabilities) arg.second;
lucaslin2240ef62019-03-12 13:08:03 +08003315 if (networkCapabilities.hasConnectivityManagedCapability()) {
Aaron Huang6616df32020-10-30 22:04:25 +08003316 Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003317 }
Chalard Jean5b639762020-03-09 21:25:37 +09003318 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
3319 // Make sure the original object is not mutated. NetworkAgent normally
3320 // makes a copy of the capabilities when sending the message through
3321 // the Messenger, but if this ever changes, not making a defensive copy
3322 // here will give attack vectors to clients using this code path.
3323 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Chiachang Wangc07315a2021-08-10 15:13:39 +08003324 networkCapabilities.restrictCapabilitiesForTestNetwork(nai.creatorUid);
Chalard Jean5b639762020-03-09 21:25:37 +09003325 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003326 processCapabilitiesFromAgent(nai, networkCapabilities);
Hugo Benichibbc15192016-09-15 18:18:48 +09003327 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003328 break;
3329 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003330 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003331 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003332 processLinkPropertiesFromAgent(nai, newLp);
3333 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003334 break;
3335 }
3336 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003337 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003338 updateNetworkInfo(nai, info);
3339 break;
3340 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003341 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003342 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003343 break;
3344 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003345 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003346 if (nai.everConnected) {
3347 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003348 // Note that if the NAI had been connected, this would affect the
3349 // score, and therefore would require re-mixing the score and performing
3350 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003351 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003352 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3353 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003354 // Mark the network as temporarily accepting partial connectivity so that it
3355 // will be validated (and possibly become default) even if it only provides
3356 // partial internet access. Note that if user connects to partial connectivity
3357 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3358 // out of wifi coverage) and if the same wifi is available again, the device
3359 // will auto connect to this wifi even though the wifi has "no internet".
3360 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003361 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003362 break;
3363 }
junyulai011b1f12019-01-03 18:50:15 +08003364 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003365 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003366 break;
3367 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003368 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003369 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003370 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003371
3372 if (isLegacyLockdownNai(nai)
3373 && (underlying == null || underlying.size() != 1)) {
3374 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3375 + " must have exactly one underlying network: " + underlying);
3376 }
3377
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003378 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3379 nai.declaredUnderlyingNetworks = (underlying != null)
3380 ? underlying.toArray(new Network[0]) : null;
3381
3382 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3383 if (DBG) {
3384 log(nai.toShortString() + " changed underlying networks to "
3385 + Arrays.toString(nai.declaredUnderlyingNetworks));
3386 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003387 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003388 notifyIfacesChangedForNetworkStats();
3389 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003390 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003391 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003392 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3393 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3394 nai.teardownDelayMs = msg.arg1;
3395 } else {
3396 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3397 }
Chalard Jean550b5212021-03-05 23:07:53 +09003398 break;
3399 }
3400 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3401 nai.setLingerDuration((int) arg.second);
3402 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003403 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003404 }
3405 }
3406
3407 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
3408 switch (msg.what) {
3409 default:
3410 return false;
lucasline117e2e2019-10-22 18:27:33 +08003411 case EVENT_PROBE_STATUS_CHANGED: {
3412 final Integer netId = (Integer) msg.obj;
3413 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3414 if (nai == null) {
3415 break;
3416 }
3417 final boolean probePrivateDnsCompleted =
3418 ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
3419 final boolean privateDnsBroken =
3420 ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
3421 if (probePrivateDnsCompleted) {
3422 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3423 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003424 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003425 }
3426 // Only show the notification when the private DNS is broken and the
3427 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003428 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003429 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3430 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003431 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003432 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3433 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3434 // private DNS is broken, it means this network is being reevaluated.
3435 // Either probing private DNS is not necessary any more or it hasn't been
3436 // done yet. In either case, the networkCapabilities should be updated to
3437 // reflect the new status.
3438 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003439 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003440 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003441 }
3442 break;
3443 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003444 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003445 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3446
3447 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(results.mNetId);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003448 if (nai == null) break;
3449
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003450 handleNetworkTested(nai, results.mTestResult,
3451 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003452 break;
3453 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003454 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09003455 final int netId = msg.arg2;
Hugo Benichif4210292017-04-21 15:07:12 +09003456 final boolean visible = toBool(msg.arg1);
Erik Kline9a62f012018-03-21 07:18:33 -07003457 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Ondada1452016-10-11 15:10:46 -07003458 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04003459 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3460 nai.lastCaptivePortalDetected = visible;
3461 nai.everCaptivePortalDetected |= visible;
Calvin Ondada1452016-10-11 15:10:46 -07003462 if (nai.lastCaptivePortalDetected &&
paulhu56e09df2021-03-17 20:30:33 +08003463 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3464 == getCaptivePortalMode()) {
Chalard Jean49707572019-12-10 21:07:02 +09003465 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003466 nai.onPreventAutomaticReconnect();
Calvin Ondada1452016-10-11 15:10:46 -07003467 teardownUnneededNetwork(nai);
3468 break;
3469 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003470 updateCapabilitiesForNetwork(nai);
Paul Jensen53f08952015-06-16 14:27:36 -04003471 }
3472 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003473 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003474 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003475 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3476 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003477 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003478 if (nai == null) {
3479 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3480 break;
3481 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003482 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003483 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003484 (PendingIntent) msg.obj,
3485 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003486 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003487 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003488 break;
3489 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003490 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline9a62f012018-03-21 07:18:33 -07003491 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003492 if (nai == null) break;
3493
Erik Kline9a62f012018-03-21 07:18:33 -07003494 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003495 break;
3496 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003497 case EVENT_CAPPORT_DATA_CHANGED: {
3498 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3499 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003500 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003501 break;
3502 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003503 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003504 return true;
3505 }
3506
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003507 private void handleNetworkTested(
3508 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
3509 final boolean wasPartial = nai.partialConnectivity;
3510 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3511 final boolean partialConnectivityChanged =
3512 (wasPartial != nai.partialConnectivity);
3513
3514 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3515 final boolean wasValidated = nai.lastValidated;
Chalard Jean5b409c72021-02-04 13:12:59 +09003516 final boolean wasDefault = isDefaultNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003517
3518 if (DBG) {
3519 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3520 ? " with redirect to " + redirectUrl
3521 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003522 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003523 }
3524 if (valid != nai.lastValidated) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003525 final int oldScore = nai.getCurrentScore();
3526 nai.lastValidated = valid;
3527 nai.everValidated |= valid;
3528 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003529 if (valid) {
3530 handleFreshlyValidatedNetwork(nai);
3531 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3532 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003533 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003534 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003535 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003536 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003537 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003538 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003539 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003540 NotificationType.PRIVATE_DNS_BROKEN);
3541 // If network becomes valid, the hasShownBroken should be reset for
3542 // that network so that the notification will be fired when the private
3543 // DNS is broken again.
3544 nai.networkAgentConfig.hasShownBroken = false;
3545 }
3546 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003547 updateCapabilitiesForNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003548 }
3549 updateInetCondition(nai);
3550 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003551 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003552 nai.onValidationStatusChanged(
3553 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3554 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003555
3556 // If NetworkMonitor detects partial connectivity before
3557 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3558 // immediately. Re-notify partial connectivity silently if no internet
3559 // notification already there.
3560 if (!wasPartial && nai.partialConnectivity) {
3561 // Remove delayed message if there is a pending message.
3562 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3563 handlePromptUnvalidated(nai.network);
3564 }
3565
3566 if (wasValidated && !nai.lastValidated) {
3567 handleNetworkUnvalidated(nai);
3568 }
3569 }
3570
Calvin Ondada1452016-10-11 15:10:46 -07003571 private int getCaptivePortalMode() {
3572 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08003573 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3574 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07003575 }
3576
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003577 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3578 switch (msg.what) {
3579 default:
3580 return false;
3581 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3582 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3583 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3584 handleLingerComplete(nai);
3585 }
3586 break;
3587 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003588 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3589 handleNetworkAgentRegistered(msg);
3590 break;
3591 }
3592 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3593 handleNetworkAgentDisconnected(msg);
3594 break;
3595 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003596 }
3597 return true;
3598 }
3599
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003600 @Override
3601 public void handleMessage(Message msg) {
lifraf3a3492021-03-10 13:58:14 +08003602 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09003603 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003604 maybeHandleNetworkAgentMessage(msg);
3605 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003606 }
3607 }
3608
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003609 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09003610 private final int mNetId;
3611 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003612
3613 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003614 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003615 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003616 }
3617
3618 @Override
3619 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3620 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09003621 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003622 }
3623
3624 @Override
3625 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003626 // Legacy version of notifyNetworkTestedWithExtras.
3627 // Would only be called if the system has a NetworkStack module older than the
3628 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08003629 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003630 }
3631
3632 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003633 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09003634 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3635 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003636 final Message msg = mTrackerHandler.obtainMessage(
3637 EVENT_NETWORK_TESTED,
3638 new NetworkTestedResults(
3639 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003640 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003641
3642 // Invoke ConnectivityReport generation for this Network test event.
3643 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3644 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003645
Cody Kestingf1120be2020-08-03 18:01:40 -07003646 // NetworkMonitor reports the network validation result as a bitmask while
3647 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
3648 // logical value for ConnectivityDiagnostics.
3649 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
3650 p.result);
3651
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003652 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07003653 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003654 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3655 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3656
Aaron Huang959d3642021-01-21 15:47:41 +08003657 ConnectivityReportEvent reportEvent =
3658 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3659 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
3660 ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003661 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003662 }
3663
3664 @Override
3665 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3666 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3667 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09003668 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003669 }
3670
3671 @Override
lucasline117e2e2019-10-22 18:27:33 +08003672 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3673 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3674 EVENT_PROBE_STATUS_CHANGED,
3675 probesCompleted, probesSucceeded, new Integer(mNetId)));
3676 }
3677
3678 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003679 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3680 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3681 EVENT_CAPPORT_DATA_CHANGED,
3682 0, mNetId, data));
3683 }
3684
3685 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003686 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003687 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003688 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003689
3690 final PendingIntent pendingIntent;
3691 // Only the system server can register notifications with package "android"
3692 final long token = Binder.clearCallingIdentity();
3693 try {
paulhu7746e4e2020-06-09 19:07:03 +08003694 pendingIntent = PendingIntent.getBroadcast(
3695 mContext,
3696 0 /* requestCode */,
3697 intent,
3698 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003699 } finally {
3700 Binder.restoreCallingIdentity(token);
3701 }
3702 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3703 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09003704 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003705 }
3706
3707 @Override
3708 public void hideProvisioningNotification() {
3709 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09003710 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003711 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003712
3713 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003714 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003715 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08003716 }
3717
3718 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003719 public int getInterfaceVersion() {
3720 return this.VERSION;
3721 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09003722
3723 @Override
3724 public String getInterfaceHash() {
3725 return this.HASH;
3726 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003727 }
3728
Cody Kestingf1120be2020-08-03 18:01:40 -07003729 /**
3730 * Converts the given NetworkMonitor-specific validation result bitmask to a
3731 * ConnectivityDiagnostics-specific validation result int.
3732 */
3733 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
3734 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
3735 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
3736 }
3737 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
3738 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
3739 }
3740 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
3741 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
3742 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
3743 }
3744
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003745 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07003746 log("Data stall detected with methods: " + p.detectionMethod);
3747
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003748 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07003749 int detectionMethod = 0;
3750 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
3751 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
3752 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
3753 }
3754 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
3755 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
3756 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
3757 p.tcpMetricsCollectionPeriodMillis);
3758 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003759 }
3760
Cody Kestingf53a0752020-04-15 12:33:28 -07003761 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003762 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08003763 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07003764
3765 // NetworkStateTrackerHandler currently doesn't take any actions based on data
3766 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
3767 // the cost of going through two handlers.
3768 mConnectivityDiagnosticsHandler.sendMessage(msg);
3769 }
3770
Cody Kestingb37958e2020-05-15 10:36:01 -07003771 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
3772 return (p.detectionMethod & detectionMethod) != 0;
3773 }
3774
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003775 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
3776 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07003777 }
3778
Erik Klinea73af002018-06-26 18:53:43 +09003779 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
3780 if (nai == null) return;
3781 // If the Private DNS mode is opportunistic, reprogram the DNS servers
3782 // in order to restart a validation pass from within netd.
3783 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3784 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003785 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09003786 }
3787 }
3788
Erik Kline31b4a9e2018-01-11 21:07:29 +09003789 private void handlePrivateDnsSettingsChanged() {
3790 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3791
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003792 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07003793 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003794 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05003795 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3796 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09003797 }
3798 }
3799
Erik Kline9a62f012018-03-21 07:18:33 -07003800 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
3801 // Private DNS only ever applies to networks that might provide
3802 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003803 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09003804
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003805 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07003806 // schedule DNS resolutions. If a DNS resolution is required the
3807 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09003808 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07003809
3810 // With Private DNS bypass support, we can proceed to update the
3811 // Private DNS config immediately, even if we're in strict mode
3812 // and have not yet resolved the provider name into a set of IPs.
3813 updatePrivateDns(nai, cfg);
3814 }
3815
3816 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
3817 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003818 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09003819 }
3820
dalyk1720e542018-03-05 12:42:22 -05003821 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
3822 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
3823 if (nai == null) {
3824 return;
3825 }
3826 mDnsManager.updatePrivateDnsValidation(update);
3827 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3828 }
3829
paulhu7c0a2e62021-01-08 00:51:49 +08003830 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003831 int prefixLength) {
3832 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
3833 if (nai == null) return;
3834
paulhu7c0a2e62021-01-08 00:51:49 +08003835 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
3836 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003837
3838 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08003839 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003840 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003841 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003842 prefixLength);
3843 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003844 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003845 return;
3846 }
3847 }
3848
Lorenzo Colittid523d142020-04-01 20:16:30 +09003849 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003850 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3851 }
3852
Hai Shalome58bdc62021-01-11 18:45:34 -08003853 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003854 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08003855 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003856 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
3857 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3858 }
3859
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003860 /**
junyulai2b6f0c22021-02-03 20:15:30 +08003861 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003862 * @param nai the agent info to update
3863 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08003864 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003865 */
junyulai2b6f0c22021-02-03 20:15:30 +08003866 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
3867 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
3868 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003869 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08003870 // one lingered request, set inactive.
3871 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08003872 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08003873 if (DBG) log("Unsetting inactive " + nai.toShortString());
3874 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003875 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08003876 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003877 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08003878 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
3879 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003880 }
junyulai2b6f0c22021-02-03 20:15:30 +08003881 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003882 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003883 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003884 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003885 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05003886 }
3887
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003888 private void handleNetworkAgentRegistered(Message msg) {
3889 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3890 if (!mNetworkAgentInfos.contains(nai)) {
3891 return;
3892 }
3893
3894 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
3895 if (VDBG) log("NetworkAgent registered");
3896 } else {
3897 loge("Error connecting NetworkAgent");
3898 mNetworkAgentInfos.remove(nai);
3899 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09003900 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003901 synchronized (mNetworkForNetId) {
3902 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003903 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003904 mNetIdManager.releaseNetId(nai.network.getNetId());
3905 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09003906 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003907 }
3908 }
3909 }
Paul Jensend5f53392014-11-25 15:26:53 -05003910
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003911 private void handleNetworkAgentDisconnected(Message msg) {
3912 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07003913 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003914 }
3915
Chalard Jeand9fffc32018-05-11 20:19:20 +09003916 // Destroys a network, remove references to it from the internal state managed by
3917 // ConnectivityService, free its interfaces and clean up.
3918 // Must be called on the Handler thread.
3919 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09003920 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07003921
3922 if (!mNetworkAgentInfos.contains(nai)) return;
3923
Chalard Jeand9fffc32018-05-11 20:19:20 +09003924 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09003925 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003926 }
lucaslinb25c9a62019-02-12 15:30:13 +08003927 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003928 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003929 // A network agent has disconnected.
3930 // TODO - if we move the logic to the network agent (have them disconnect
3931 // because they lost all their requests or because their score isn't good)
3932 // then they would disconnect organically, report their new state and then
3933 // disconnect the channel.
3934 if (nai.networkInfo.isConnected()) {
3935 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3936 null, null);
3937 }
Chalard Jean5b409c72021-02-04 13:12:59 +09003938 final boolean wasDefault = isDefaultNetwork(nai);
3939 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09003940 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09003941 }
3942 notifyIfacesChangedForNetworkStats();
3943 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
3944 // by other networks that are already connected. Perhaps that can be done by
3945 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
3946 // of rematchAllNetworksAndRequests
3947 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08003948 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07003949
3950 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09003951 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
3952 // Disable wakeup packet monitoring for each interface.
3953 wakeupModifyInterface(iface, nai.networkCapabilities, false);
3954 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09003955 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003956 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09003957 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09003958 synchronized (mNetworkForNetId) {
3959 // Remove the NetworkAgent, but don't mark the netId as
3960 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003961 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003962 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09003963 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09003964 // Remove all previously satisfied requests.
3965 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08003966 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09003967 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08003968 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08003969 if (currentNetwork != null
3970 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08003971 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09003972 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
3973 // rematch not to keep disconnected agents instead of setting it here ; this
3974 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08003975 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09003976 for (final NetworkOfferInfo noi : mNetworkOffers) {
3977 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08003978 }
James Mattise3ef1912020-12-20 11:09:58 -08003979
Chalard Jean5b409c72021-02-04 13:12:59 +09003980 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08003981 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09003982 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08003983 // network, because while incorrect this is the closest to the old (also
3984 // incorrect) behavior.
3985 mNetworkActivityTracker.updateDataActivityTracking(
3986 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08003987 ensureNetworkTransitionWakelock(nai.toShortString());
3988 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09003989 }
3990 }
junyulai2b6f0c22021-02-03 20:15:30 +08003991 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08003992 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09003993 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08003994 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09003995 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09003996 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09003997 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003998
3999 // Immediate teardown.
4000 if (nai.teardownDelayMs == 0) {
4001 destroyNetwork(nai);
4002 return;
4003 }
4004
4005 // Delayed teardown.
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304006 if (nai.created) {
4007 try {
4008 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4009 } catch (RemoteException e) {
4010 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4011 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004012 }
4013 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4014 }
4015
4016 private void destroyNetwork(NetworkAgentInfo nai) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004017 if (nai.created) {
4018 // Tell netd to clean up the configuration for this network
4019 // (routing rules, DNS, etc).
4020 // This may be slow as it requires a lot of netd shelling out to ip and
4021 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004022 // after we've rematched networks with requests (which might change the default
4023 // network or service a new request from an app), so network traffic isn't interrupted
4024 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004025 destroyNativeNetwork(nai);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004026 mDnsManager.removeNetwork(nai.network);
4027 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004028 mNetIdManager.releaseNetId(nai.network.getNetId());
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004029 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004030 }
4031
Ken Chen6df7a902021-04-09 15:08:42 +08004032 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004033 try {
4034 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004035 final NativeNetworkConfig config;
4036 if (nai.isVPN()) {
4037 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004038 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004039 return false;
4040 }
4041 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4042 INetd.PERMISSION_NONE,
4043 (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass),
4044 getVpnType(nai));
Luke Huangfdd11f82019-04-09 18:41:49 +08004045 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004046 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
4047 getNetworkPermission(nai.networkCapabilities), /*secure=*/ false,
4048 VpnManager.TYPE_VPN_NONE);
Luke Huangfdd11f82019-04-09 18:41:49 +08004049 }
Ken Chen6df7a902021-04-09 15:08:42 +08004050 mNetd.networkCreate(config);
4051 mDnsResolver.createNetworkCache(nai.network.getNetId());
4052 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4053 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004054 return true;
4055 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004056 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004057 return false;
4058 }
4059 }
4060
Ken Chen6df7a902021-04-09 15:08:42 +08004061 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004062 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004063 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004064 } catch (RemoteException | ServiceSpecificException e) {
4065 loge("Exception destroying network(networkDestroy): " + e);
4066 }
4067 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004068 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004069 } catch (RemoteException | ServiceSpecificException e) {
4070 loge("Exception destroying network: " + e);
4071 }
4072 }
4073
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004074 // If this method proves to be too slow then we can maintain a separate
4075 // pendingIntent => NetworkRequestInfo map.
4076 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4077 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004078 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4079 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4080 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004081 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004082 return entry.getValue();
4083 }
4084 }
4085 return null;
4086 }
4087
Chalard Jean524f0b12021-10-25 21:11:56 +09004088 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4089 if (SdkLevel.isAtLeastT()) {
4090 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4091 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4092 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4093 // bug is fixed.
4094 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004095 throw new IllegalStateException("This NRI is already registered. New : " + nri
4096 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004097 }
4098 }
4099 }
4100 }
4101
James Mattisf7027322020-12-13 16:28:14 -08004102 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004103 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004104 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4105 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4106 final NetworkRequestInfo existingRequest =
4107 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004108 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004109 if (DBG) {
4110 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4111 + nri.mRequests.get(0) + " because their intents matched.");
4112 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004113 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004114 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004115 }
Erik Kline05f2b402015-04-30 12:58:40 +09004116 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004117 }
4118
James Mattisf7027322020-12-13 16:28:14 -08004119 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004120 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004121 }
4122
James Mattis3ce3d3c2021-02-09 18:18:28 -08004123 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004124 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004125 for (final NetworkRequestInfo nri : nris) {
4126 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004127 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004128 for (final NetworkRequest req : nri.mRequests) {
4129 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004130 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004131 if (req.isListen()) {
4132 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4133 if (req.networkCapabilities.hasSignalStrength()
4134 && network.satisfiesImmutableCapabilitiesOf(req)) {
4135 updateSignalStrengthThresholds(network, "REGISTER", req);
4136 }
James Mattisf7027322020-12-13 16:28:14 -08004137 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004138 }
4139 }
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004140 // If this NRI has a satisfier already, it is replacing an older request that
4141 // has been removed. Track it.
4142 final NetworkRequest activeRequest = nri.getActiveRequest();
4143 if (null != activeRequest) {
4144 // If there is an active request, then for sure there is a satisfier.
4145 nri.getSatisfier().addRequest(activeRequest);
4146 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004147 }
James Mattisf7027322020-12-13 16:28:14 -08004148
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004149 if (mFlags.noRematchAllRequestsOnRegister()) {
4150 rematchNetworksAndRequests(nris);
4151 } else {
4152 rematchAllNetworksAndRequests();
4153 }
James Mattis45d81842021-01-10 14:24:24 -08004154
Chalard Jean0354d8c2021-01-12 10:58:56 +09004155 // Requests that have not been matched to a network will not have been sent to the
4156 // providers, because the old satisfier and the new satisfier are the same (null in this
4157 // case). Send these requests to the providers.
4158 for (final NetworkRequestInfo nri : nris) {
4159 for (final NetworkOfferInfo noi : mNetworkOffers) {
4160 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004161 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004162 }
4163 }
4164
James Mattisf7027322020-12-13 16:28:14 -08004165 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4166 final int callingUid) {
4167 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004168 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004169 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4170 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4171 handleReleaseNetworkRequest(
4172 nri.mRequests.get(0),
4173 callingUid,
4174 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004175 }
4176 }
4177
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004178 // Determines whether the network is the best (or could become the best, if it validated), for
4179 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4180 // on the value of reason:
4181 //
4182 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4183 // then it should be torn down.
4184 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4185 // then it should be lingered.
4186 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004187 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004188
4189 if (!nai.everConnected || nai.isVPN() || nai.isInactive()
4190 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4191 return false;
4192 }
4193
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004194 final int numRequests;
4195 switch (reason) {
4196 case TEARDOWN:
4197 numRequests = nai.numRequestNetworkRequests();
4198 break;
4199 case LINGER:
4200 numRequests = nai.numForegroundNetworkRequests();
4201 break;
4202 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004203 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004204 return true;
4205 }
4206
Chalard Jean947acd42021-03-08 22:29:27 +09004207 if (numRequests > 0) return false;
4208
Paul Jensende49eb12015-06-25 15:30:08 -04004209 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004210 if (reason == UnneededFor.LINGER
4211 && !nri.isMultilayerRequest()
4212 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004213 // Background requests don't affect lingering.
4214 continue;
4215 }
4216
James Mattis3d229892020-11-16 16:46:28 -08004217 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004218 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004219 }
4220 }
Paul Jensende49eb12015-06-25 15:30:08 -04004221 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004222 }
4223
James Mattis3d229892020-11-16 16:46:28 -08004224 private boolean isNetworkPotentialSatisfier(
4225 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4226 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004227 // request, return immediately. For multilayer requests, check to see if any of the
4228 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004229 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4230 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004231 return false;
4232 }
4233 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004234 // This multilayer listen request is satisfied therefore no further requests need to be
4235 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004236 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004237 return false;
4238 }
James Mattis3d229892020-11-16 16:46:28 -08004239 // As non-multilayer listen requests have already returned, the below would only happen
4240 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004241 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004242 continue;
4243 }
4244 // If this Network is already the highest scoring Network for a request, or if
4245 // there is hope for it to become one if it validated, then it is needed.
4246 if (candidate.satisfies(req)) {
4247 // As soon as a network is found that satisfies a request, return. Specifically for
4248 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4249 // is important so as to not evaluate lower priority requests further in
4250 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004251 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4252 ? nri.getSatisfier() : null;
4253 // Note that this catches two important cases:
4254 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4255 // is currently satisfying the request. This is desirable when
4256 // cellular ends up validating but WiFi does not.
4257 // 2. Unvalidated WiFi will not be reaped when validated cellular
4258 // is currently satisfying the request. This is desirable when
4259 // WiFi ends up validating and out scoring cellular.
4260 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004261 }
4262 }
4263
4264 return false;
4265 }
4266
Erik Kline0c04b742016-07-07 16:50:58 +09004267 private NetworkRequestInfo getNriForAppRequest(
4268 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004269 // Looking up the app passed param request in mRequests isn't possible since it may return
4270 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4271 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004272 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4273 // to avoid potential race conditions when validating a package->uid mapping when sending
4274 // the callback on the very low-chance that an application shuts down prior to the callback
4275 // being sent.
4276 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4277 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004278
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004279 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004280 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004281 log(String.format("UID %d attempted to %s for unowned request %s",
4282 callingUid, requestedOperation, nri));
4283 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004284 }
Erik Kline0c04b742016-07-07 16:50:58 +09004285 }
4286
4287 return nri;
4288 }
4289
James Mattisf7027322020-12-13 16:28:14 -08004290 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4291 final String callingMethod) {
4292 if (nri.isMultilayerRequest()) {
4293 throw new IllegalStateException(
4294 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004295 }
4296 }
4297
James Mattisf7027322020-12-13 16:28:14 -08004298 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004299 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004300 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4301 // single NetworkRequest and thus does not apply to multilayer requests.
4302 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4303 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004304 return;
4305 }
James Mattis2516da32021-01-31 17:06:19 -08004306 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004307 return;
4308 }
James Mattisf7027322020-12-13 16:28:14 -08004309 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4310 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004311 }
4312 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004313 callCallbackForRequest(
4314 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004315 }
4316
James Mattisf7027322020-12-13 16:28:14 -08004317 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4318 final int callingUid,
4319 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004320 final NetworkRequestInfo nri =
4321 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4322 if (nri == null) {
4323 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004324 }
James Mattisf7027322020-12-13 16:28:14 -08004325 if (VDBG || (DBG && request.isRequest())) {
4326 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004327 }
4328 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004329 if (callOnUnavailable) {
4330 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4331 }
Erik Kline155a59a2015-11-25 12:49:38 +09004332 }
Erik Kline0c04b742016-07-07 16:50:58 +09004333
James Mattisa076c532020-12-02 14:12:41 -08004334 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004335 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004336 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004337 if (null == mNetworkRequests.remove(req)) {
4338 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4339 continue;
4340 }
James Mattisa076c532020-12-02 14:12:41 -08004341 if (req.isListen()) {
4342 removeListenRequestFromNetworks(req);
4343 }
4344 }
James Mattis8f036802021-06-20 16:26:01 -07004345 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004346 if (mDefaultNetworkRequests.remove(nri)) {
4347 // If this request was one of the defaults, then the UID rules need to be updated
4348 // WARNING : if the app(s) for which this network request is the default are doing
4349 // traffic, this will kill their connected sockets, even if an equivalent request
4350 // is going to be reinstated right away ; unconnected traffic will go on the default
4351 // until the new default is set, which will happen very soon.
4352 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4353 // remove ranges for those requests that won't have a replacement
4354 final NetworkAgentInfo satisfier = nri.getSatisfier();
4355 if (null != satisfier) {
4356 try {
paulhu0e79d952021-06-09 16:11:35 +08004357 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4358 satisfier.network.getNetId(),
4359 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004360 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004361 } catch (RemoteException e) {
4362 loge("Exception setting network preference default network", e);
4363 }
4364 }
4365 }
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09004366 nri.decrementRequestCount();
Erik Kline0c04b742016-07-07 16:50:58 +09004367 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004368 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004369
4370 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004371 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004372 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004373 }
4374 }
4375
Chalard Jean0354d8c2021-01-12 10:58:56 +09004376 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4377 // needed for this offer.
4378 for (final NetworkOfferInfo noi : mNetworkOffers) {
4379 for (final NetworkRequest req : nri.mRequests) {
4380 if (req.isRequest() && noi.offer.neededFor(req)) {
4381 noi.offer.onNetworkUnneeded(req);
4382 }
4383 }
4384 }
James Mattisa076c532020-12-02 14:12:41 -08004385 }
4386
James Mattis3ce3d3c2021-02-09 18:18:28 -08004387 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4388 for (final NetworkRequestInfo nri : nris) {
4389 if (mDefaultRequest == nri) {
4390 // Make sure we never remove the default request.
4391 continue;
4392 }
4393 handleRemoveNetworkRequest(nri);
4394 }
4395 }
4396
James Mattisa076c532020-12-02 14:12:41 -08004397 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4398 // listens don't have a singular affected Network. Check all networks to see
4399 // if this listen request applies and remove it.
4400 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4401 nai.removeRequest(req.requestId);
4402 if (req.networkCapabilities.hasSignalStrength()
4403 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4404 updateSignalStrengthThresholds(nai, "RELEASE", req);
4405 }
4406 }
4407 }
4408
4409 /**
4410 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4411 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4412 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4413 */
4414 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4415 boolean wasKept = false;
4416 final NetworkAgentInfo nai = nri.getSatisfier();
4417 if (nai != null) {
4418 final int requestLegacyType = nri.getActiveRequest().legacyType;
4419 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4420 nai.removeRequest(nri.getActiveRequest().requestId);
4421 if (VDBG || DDBG) {
4422 log(" Removing from current network " + nai.toShortString()
4423 + ", leaving " + nai.numNetworkRequests() + " requests.");
4424 }
4425 // If there are still lingered requests on this network, don't tear it down,
4426 // but resume lingering instead.
4427 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004428 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004429 notifyNetworkLosing(nai, now);
4430 }
4431 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4432 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4433 teardownUnneededNetwork(nai);
4434 } else {
4435 wasKept = true;
4436 }
James Mattisa076c532020-12-02 14:12:41 -08004437 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4438 // Went from foreground to background.
4439 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004440 }
4441
Erik Kline0c04b742016-07-07 16:50:58 +09004442 // Maintain the illusion. When this request arrived, we might have pretended
4443 // that a network connected to serve it, even though the network was already
4444 // connected. Now that this request has gone away, we might have to pretend
4445 // that the network disconnected. LegacyTypeTracker will generate that
4446 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004447 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004448 boolean doRemove = true;
4449 if (wasKept) {
4450 // check if any of the remaining requests for this network are for the
4451 // same legacy type - if so, don't remove the nai
4452 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4453 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004454 if (otherRequest.legacyType == requestLegacyType
4455 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004456 if (DBG) log(" still have other legacy request - leaving");
4457 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004458 }
4459 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004460 }
4461
Erik Kline0c04b742016-07-07 16:50:58 +09004462 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004463 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004464 }
4465 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004466 }
4467 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004468
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004469 private PerUidCounter getRequestCounter(NetworkRequestInfo nri) {
4470 return checkAnyPermissionOf(
4471 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4472 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4473 }
4474
Lorenzo Colittid6459092016-07-04 12:55:44 +09004475 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004476 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004477 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004478 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004479 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004480 }
4481
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004482 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004483 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4484 enforceNetworkStackSettingsOrSetup();
4485 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4486 encodeBool(accept), encodeBool(always), network));
4487 }
4488
4489 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004490 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004491 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004492 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4493 }
4494
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004495 @Override
4496 public void setTestAllowBadWifiUntil(long timeMs) {
4497 enforceSettingsPermission();
4498 if (!Build.isDebuggable()) {
4499 throw new IllegalStateException("Does not support in non-debuggable build");
4500 }
4501
4502 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4503 throw new IllegalArgumentException("It should not exceed "
4504 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4505 }
4506
4507 mHandler.sendMessage(
4508 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
4509 }
4510
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004511 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4512 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4513 " accept=" + accept + " always=" + always);
4514
4515 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4516 if (nai == null) {
4517 // Nothing to do.
4518 return;
4519 }
4520
4521 if (nai.everValidated) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004522 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004523 return;
4524 }
4525
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004526 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08004527 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004528 }
4529
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004530 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4531 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004532 // If network becomes partial connectivity and user already accepted to use this
4533 // network, we should respect the user's option and don't need to popup the
4534 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004535 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004536 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004537 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004538 }
4539
4540 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004541 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004542 }
4543
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004544 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04004545 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004546 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09004547 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04004548 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004549 }
4550
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004551 }
4552
lucaslin2240ef62019-03-12 13:08:03 +08004553 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4554 boolean always) {
4555 if (DBG) {
4556 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4557 + " always=" + always);
4558 }
4559
4560 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4561 if (nai == null) {
4562 // Nothing to do.
4563 return;
4564 }
4565
4566 if (nai.lastValidated) {
4567 // The network validated while the dialog box was up. Take no action.
4568 return;
4569 }
4570
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004571 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4572 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004573 }
4574
4575 // TODO: Use the current design or save the user choice into IpMemoryStore.
4576 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004577 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08004578 }
4579
4580 if (!accept) {
4581 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004582 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08004583 // Tear down the network.
4584 teardownUnneededNetwork(nai);
4585 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08004586 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4587 // result in a partial connectivity result which will be processed by
4588 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08004589 //
4590 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4591 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004592 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08004593 }
4594 }
4595
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004596 private void handleSetAvoidUnvalidated(Network network) {
4597 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4598 if (nai == null || nai.lastValidated) {
4599 // Nothing to do. The network either disconnected or revalidated.
4600 return;
4601 }
4602 if (!nai.avoidUnvalidated) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004603 nai.avoidUnvalidated = true;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004604 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004605 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004606 }
4607 }
4608
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004609 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09004610 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004611 mHandler.sendMessageDelayed(
4612 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4613 PROMPT_UNVALIDATED_DELAY_MS);
4614 }
4615
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004616 @Override
4617 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08004618 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004619 mHandler.post(() -> {
4620 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4621 if (nai == null) return;
4622 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004623 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004624 });
4625 }
4626
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004627 /**
4628 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4629 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004630 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004631 * @param appExtras Bundle to use as intent extras for the captive portal application.
4632 * Must be treated as opaque to avoid preventing the captive portal app to
4633 * update its arguments.
4634 */
4635 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004636 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08004637 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4638 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004639
4640 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4641 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004642 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4643 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004644 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4645
lucaslin75ff7022020-12-17 04:14:35 +08004646 final long token = Binder.clearCallingIdentity();
4647 try {
4648 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4649 } finally {
4650 Binder.restoreCallingIdentity(token);
4651 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004652 }
4653
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004654 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4655 private final Network mNetwork;
4656
4657 private CaptivePortalImpl(Network network) {
4658 mNetwork = network;
4659 }
4660
4661 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004662 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004663 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
4664 enforceSettingsPermission();
4665 }
4666
Chiachang Wang938bfba2020-01-09 13:50:55 +08004667 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004668 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004669 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004670 }
4671
4672 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08004673 public void appRequest(final int request) {
4674 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4675 if (nm == null) return;
4676
4677 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08004678 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09004679 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08004680 }
4681 }
4682
4683 @Nullable
4684 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
4685 // getNetworkAgentInfoForNetwork is thread-safe
4686 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4687 if (nai == null) return null;
4688
4689 // nai.networkMonitor() is thread-safe
4690 return nai.networkMonitor();
4691 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004692 }
4693
Hugo Benichic9048bc2016-09-14 23:23:08 +00004694 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004695 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09004696 }
4697
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004698 /**
4699 * Return whether the device should maintain continuous, working connectivity by switching away
4700 * from WiFi networks having no connectivity.
4701 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
4702 */
4703 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004704 if (!checkNetworkStackPermission()) {
4705 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
4706 }
4707 return avoidBadWifi();
4708 }
4709
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004710 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09004711 ensureRunningOnConnectivityServiceThread();
4712 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004713 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09004714 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004715 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09004716 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
4717 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
4718 for (final NetworkOfferInfo noi : offersToUpdate) {
4719 updateOfferScore(noi.offer);
4720 }
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004721 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004722 }
4723
Erik Kline95ecfee2016-10-02 18:02:14 +09004724 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004725 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004726 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004727 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004728 if (!configRestrict) {
4729 pw.println("Bad Wi-Fi avoidance: unrestricted");
4730 return;
4731 }
4732
4733 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
4734 pw.increaseIndent();
4735 pw.println("Config restrict: " + configRestrict);
4736
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004737 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004738 String description;
4739 // Can't use a switch statement because strings are legal case labels, but null is not.
4740 if ("0".equals(value)) {
4741 description = "get stuck";
4742 } else if (value == null) {
4743 description = "prompt";
4744 } else if ("1".equals(value)) {
4745 description = "avoid";
4746 } else {
4747 description = value + " (?)";
4748 }
4749 pw.println("User setting: " + description);
4750 pw.println("Network overrides:");
4751 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09004752 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004753 if (nai.avoidUnvalidated) {
Chalard Jean49707572019-12-10 21:07:02 +09004754 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004755 }
4756 }
4757 pw.decreaseIndent();
4758 pw.decreaseIndent();
4759 }
4760
paulhu7746e4e2020-06-09 19:07:03 +08004761 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
4762 // unify the method.
4763 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
4764 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
4765 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
4766 return settingsComponent != null
4767 ? settingsComponent.getPackageName() : "com.android.settings";
4768 }
4769
lucaslinb1e8e382019-01-24 15:55:30 +08004770 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004771 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004772 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004773 switch (type) {
4774 case NO_INTERNET:
4775 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004776 // High priority because it is only displayed for explicitly selected networks.
4777 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004778 break;
lucasline117e2e2019-10-22 18:27:33 +08004779 case PRIVATE_DNS_BROKEN:
4780 action = Settings.ACTION_WIRELESS_SETTINGS;
4781 // High priority because we should let user know why there is no internet.
4782 highPriority = true;
4783 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004784 case LOST_INTERNET:
4785 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004786 // High priority because it could help the user avoid unexpected data usage.
4787 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004788 break;
lucaslin2240ef62019-03-12 13:08:03 +08004789 case PARTIAL_CONNECTIVITY:
4790 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004791 // Don't bother the user with a high-priority notification if the network was not
4792 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004793 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08004794 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004795 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004796 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004797 return;
4798 }
4799
4800 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08004801 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08004802 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08004803 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08004804 // Some OEMs have their own Settings package. Thus, need to get the current using
4805 // Settings package name instead of just use default name "com.android.settings".
4806 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
4807 intent.setClassName(settingsPkgName,
4808 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08004809 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004810
paulhu2af50222020-10-11 22:52:27 +08004811 PendingIntent pendingIntent = PendingIntent.getActivity(
4812 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08004813 0 /* requestCode */,
4814 intent,
paulhu2af50222020-10-11 22:52:27 +08004815 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004816
Serik Beketayevec8ad212020-12-07 22:43:07 -08004817 mNotifier.showNotification(
4818 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004819 }
4820
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004821 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
4822 // Don't prompt if the network is validated, and don't prompt on captive portals
4823 // because we're already prompting the user to sign in.
4824 if (nai.everValidated || nai.everCaptivePortalDetected) {
4825 return false;
4826 }
4827
4828 // If a network has partial connectivity, always prompt unless the user has already accepted
4829 // partial connectivity and selected don't ask again. This ensures that if the device
4830 // automatically connects to a network that has partial Internet access, the user will
4831 // always be able to use it, either because they've already chosen "don't ask again" or
4832 // because we have prompt them.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004833 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004834 return true;
4835 }
4836
4837 // If a network has no Internet access, only prompt if the network was explicitly selected
4838 // and if the user has not already told us to use the network regardless of whether it
4839 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004840 if (nai.networkAgentConfig.explicitlySelected
4841 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004842 return true;
4843 }
4844
4845 return false;
4846 }
4847
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004848 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09004849 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004850 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4851
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004852 if (nai == null || !shouldPromptUnvalidated(nai)) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004853 return;
4854 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09004855
4856 // Stop automatically reconnecting to this network in the future. Automatically connecting
4857 // to a network that provides no or limited connectivity is not useful, because the user
4858 // cannot use that network except through the notification shown by this method, and the
4859 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004860 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09004861
lucaslin2240ef62019-03-12 13:08:03 +08004862 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
4863 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
4864 // popup the notification immediately when the network is partial connectivity.
4865 if (nai.partialConnectivity) {
lucasline0118ab2019-03-21 11:59:22 +08004866 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08004867 } else {
4868 showNetworkNotification(nai, NotificationType.NO_INTERNET);
4869 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004870 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004871
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004872 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
4873 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09004874 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07004875
lucaslin2240ef62019-03-12 13:08:03 +08004876 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4877 return;
4878 }
4879
4880 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08004881 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004882 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004883 }
4884
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004885 @Override
4886 public int getMultipathPreference(Network network) {
4887 enforceAccessPermission();
4888
4889 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06004890 if (nai != null && nai.networkCapabilities
4891 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004892 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
4893 }
4894
Aaron Huang9a57acf2020-12-08 10:03:29 +08004895 final NetworkPolicyManager netPolicyManager =
4896 mContext.getSystemService(NetworkPolicyManager.class);
4897
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09004898 final long token = Binder.clearCallingIdentity();
4899 final int networkPreference;
4900 try {
4901 networkPreference = netPolicyManager.getMultipathPreference(network);
4902 } finally {
4903 Binder.restoreCallingIdentity(token);
4904 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08004905 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09004906 return networkPreference;
4907 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004908 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
4909 }
4910
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004911 @Override
4912 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09004913 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004914 }
4915
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004916 private class InternalHandler extends Handler {
4917 public InternalHandler(Looper looper) {
4918 super(looper);
4919 }
4920
4921 @Override
4922 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004923 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07004924 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004925 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09004926 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07004927 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004928 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004929 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09004930 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07004931 break;
4932 }
Jason Monka69f1b02013-10-10 14:02:51 -04004933 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08004934 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
4935 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04004936 break;
4937 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09004938 case EVENT_REGISTER_NETWORK_PROVIDER: {
4939 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07004940 break;
4941 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09004942 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
4943 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004944 break;
4945 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09004946 case EVENT_REGISTER_NETWORK_OFFER: {
4947 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
4948 break;
4949 }
4950 case EVENT_UNREGISTER_NETWORK_OFFER: {
4951 final NetworkOfferInfo offer =
4952 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
4953 if (null != offer) {
4954 handleUnregisterNetworkOffer(offer);
4955 }
4956 break;
4957 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004958 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004959 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
4960 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
4961 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004962 break;
4963 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004964 case EVENT_REGISTER_NETWORK_REQUEST:
4965 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09004966 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004967 break;
4968 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04004969 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
4970 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004971 handleRegisterNetworkRequestWithIntent(msg);
4972 break;
4973 }
Erik Kline155a59a2015-11-25 12:49:38 +09004974 case EVENT_TIMEOUT_NETWORK_REQUEST: {
4975 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
4976 handleTimedOutNetworkRequest(nri);
4977 break;
4978 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004979 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
4980 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
4981 break;
4982 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004983 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08004984 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
4985 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004986 break;
4987 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004988 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09004989 Network network = (Network) msg.obj;
4990 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004991 break;
4992 }
lucaslin2240ef62019-03-12 13:08:03 +08004993 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
4994 Network network = (Network) msg.obj;
4995 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
4996 toBool(msg.arg2));
4997 break;
4998 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004999 case EVENT_SET_AVOID_UNVALIDATED: {
5000 handleSetAvoidUnvalidated((Network) msg.obj);
5001 break;
5002 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005003 case EVENT_PROMPT_UNVALIDATED: {
5004 handlePromptUnvalidated((Network) msg.obj);
5005 break;
5006 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005007 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5008 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005009 break;
5010 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005011 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005012 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005013 mKeepaliveTracker.handleStartKeepalive(msg);
5014 break;
5015 }
5016 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005017 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005018 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5019 int slot = msg.arg1;
5020 int reason = msg.arg2;
5021 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
5022 break;
5023 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005024 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5025 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5026 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005027 break;
5028 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005029 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5030 handlePrivateDnsSettingsChanged();
5031 break;
dalyk1720e542018-03-05 12:42:22 -05005032 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5033 handlePrivateDnsValidationUpdate(
5034 (PrivateDnsValidationUpdate) msg.obj);
5035 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005036 case EVENT_UID_BLOCKED_REASON_CHANGED:
5037 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005038 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005039 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5040 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5041 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005042 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005043 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5044 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005045 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005046 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005047 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005048 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
5049 final Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener> arg =
5050 (Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener>)
5051 msg.obj;
5052 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005053 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005054 }
lucaslin1193a5d2021-01-21 02:04:15 +08005055 case EVENT_REPORT_NETWORK_ACTIVITY:
5056 mNetworkActivityTracker.handleReportNetworkActivity();
5057 break;
paulhu51f77dc2021-06-07 02:34:20 +00005058 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5059 handleMobileDataPreferredUidsChanged();
5060 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005061 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5062 final long timeMs = ((Long) msg.obj).longValue();
5063 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5064 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005065 }
5066 }
5067 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005068
Lorenzo Colittid6459092016-07-04 12:55:44 +09005069 @Override
markchien5776f962019-12-16 20:15:20 +08005070 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005071 public int getLastTetherError(String iface) {
markchien5776f962019-12-16 20:15:20 +08005072 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5073 Context.TETHERING_SERVICE);
5074 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005075 }
5076
Lorenzo Colittid6459092016-07-04 12:55:44 +09005077 @Override
markchien5776f962019-12-16 20:15:20 +08005078 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005079 public String[] getTetherableIfaces() {
markchien5776f962019-12-16 20:15:20 +08005080 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5081 Context.TETHERING_SERVICE);
5082 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005083 }
5084
Lorenzo Colittid6459092016-07-04 12:55:44 +09005085 @Override
markchien5776f962019-12-16 20:15:20 +08005086 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005087 public String[] getTetheredIfaces() {
markchien5776f962019-12-16 20:15:20 +08005088 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5089 Context.TETHERING_SERVICE);
5090 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005091 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005092
markchien5776f962019-12-16 20:15:20 +08005093
Lorenzo Colittid6459092016-07-04 12:55:44 +09005094 @Override
markchien5776f962019-12-16 20:15:20 +08005095 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005096 public String[] getTetheringErroredIfaces() {
markchien5776f962019-12-16 20:15:20 +08005097 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5098 Context.TETHERING_SERVICE);
5099
5100 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005101 }
5102
Lorenzo Colittid6459092016-07-04 12:55:44 +09005103 @Override
markchien5776f962019-12-16 20:15:20 +08005104 @Deprecated
5105 public String[] getTetherableUsbRegexs() {
5106 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5107 Context.TETHERING_SERVICE);
5108
5109 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005110 }
5111
Udam Saini8f7d6a72017-06-07 12:06:28 -07005112 @Override
markchien5776f962019-12-16 20:15:20 +08005113 @Deprecated
5114 public String[] getTetherableWifiRegexs() {
5115 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5116 Context.TETHERING_SERVICE);
5117 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005118 }
5119
Robert Greenwalte0b00512014-07-02 09:59:16 -07005120 // Called when we lose the default network and have no replacement yet.
5121 // This will automatically be cleared after X seconds or a new default network
5122 // becomes CONNECTED, whichever happens first. The timer is started by the
5123 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005124 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005125 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005126 if (mNetTransitionWakeLock.isHeld()) {
5127 return;
5128 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005129 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005130 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5131 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005132 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005133 mWakelockLogs.log("ACQUIRE for " + forWhom);
5134 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005135 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005136 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005137 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005138 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005139
Hugo Benichi471b62a2017-03-30 23:18:10 +09005140 // Called when we gain a new default network to release the network transition wakelock in a
5141 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5142 // message is cancelled.
5143 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005144 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005145 if (!mNetTransitionWakeLock.isHeld()) {
5146 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005147 }
5148 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005149 // Cancel self timeout on wakelock hold.
5150 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5151 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5152 mHandler.sendMessageDelayed(msg, 1000);
5153 }
5154
5155 // Called when either message of ensureNetworkTransitionWakelock or
5156 // scheduleReleaseNetworkTransitionWakelock is processed.
5157 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5158 String event = eventName(eventId);
5159 synchronized (this) {
5160 if (!mNetTransitionWakeLock.isHeld()) {
5161 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005162 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005163 return;
5164 }
5165 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005166 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5167 mTotalWakelockDurationMs += lockDuration;
5168 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5169 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005170 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005171 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005172 }
5173
Robert Greenwalt986c7412010-09-08 15:24:47 -07005174 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005175 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005176 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005177 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005178 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005179 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005180 }
5181
Lorenzo Colittid6459092016-07-04 12:55:44 +09005182 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005183 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005184 enforceAccessPermission();
5185 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005186 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005187 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005188
5189 final NetworkAgentInfo nai;
5190 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005191 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005192 } else {
5193 nai = getNetworkAgentInfoForNetwork(network);
5194 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005195
5196 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005197 mHandler.obtainMessage(
5198 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005199 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005200
Hugo Benichid6b510a2017-04-06 17:22:18 +09005201 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005202 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005203 if (nai == null
5204 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005205 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005206 return;
5207 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005208 // Revalidate if the app report does not match our current validated state.
Hugo Benichie9d321b2017-04-06 16:01:44 +09005209 if (hasConnectivity == nai.lastValidated) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005210 mConnectivityDiagnosticsHandler.sendMessage(
5211 mConnectivityDiagnosticsHandler.obtainMessage(
5212 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5213 new ReportedNetworkConnectivityInfo(
5214 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005215 return;
5216 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005217 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005218 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005219 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005220 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005221 // Validating a network that has not yet connected could result in a call to
5222 // rematchNetworkAndRequests() which is not meant to work on such networks.
5223 if (!nai.everConnected) {
5224 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005225 }
paulhu7aeba372020-12-30 00:42:19 +08005226 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5227 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005228 return;
5229 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005230
5231 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5232 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5233 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5234 // completed.
5235 mConnectivityDiagnosticsHandler.sendMessage(
5236 mConnectivityDiagnosticsHandler.obtainMessage(
5237 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5238 new ReportedNetworkConnectivityInfo(
5239 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005240 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005241 }
5242
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005243 // TODO: call into netd.
5244 private boolean queryUserAccess(int uid, Network network) {
5245 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5246 if (nai == null) return false;
5247
5248 // Any UID can use its default network.
5249 if (nai == getDefaultNetworkForUid(uid)) return true;
5250
5251 // Privileged apps can use any network.
5252 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5253 return true;
5254 }
5255
5256 // An unprivileged UID can use a VPN iff the VPN applies to it.
5257 if (nai.isVPN()) {
5258 return nai.networkCapabilities.appliesToUid(uid);
5259 }
5260
5261 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5262 // sockets, i.e., if it is the owner.
5263 final NetworkAgentInfo vpn = getVpnForUid(uid);
5264 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5265 && uid != vpn.networkCapabilities.getOwnerUid()) {
5266 return false;
5267 }
5268
5269 // The UID's permission must be at least sufficient for the network. Since the restricted
5270 // permission was already checked above, that just leaves background networks.
5271 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5272 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5273 }
5274
5275 // Unrestricted network. Anyone gets to use it.
5276 return true;
5277 }
5278
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005279 /**
5280 * Returns information about the proxy a certain network is using. If given a null network, it
5281 * it will return the proxy for the bound network for the caller app or the default proxy if
5282 * none.
5283 *
5284 * @param network the network we want to get the proxy information for.
5285 * @return Proxy information if a network has a proxy configured, or otherwise null.
5286 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005287 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005288 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005289 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005290 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005291 if (network == null) {
5292 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005293 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005294 true);
5295 if (activeNetwork == null) {
5296 return null;
5297 }
5298 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005299 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005300 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5301 // caller may not have.
5302 return getLinkPropertiesProxyInfo(network);
5303 }
5304 // No proxy info available if the calling UID does not have network access.
5305 return null;
5306 }
5307
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005308
5309 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005310 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5311 if (nai == null) return null;
5312 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005313 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5314 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005315 }
5316 }
5317
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005318 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005319 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhudf23d662021-01-25 18:53:17 +08005320 PermissionUtils.enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005321 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005322 }
5323
Chalard Jean777e2e52018-06-07 18:02:37 +09005324 @Override
5325 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005326 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005327 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005328 }
5329
Jason Monk4d5e20f2014-04-25 15:00:09 -04005330 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005331 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005332 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005333 proxy = null;
5334 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005335 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005336 }
5337
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005338 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5339 // when any network changes proxy.
5340 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5341 // multi-network world where an app might be bound to a non-default network.
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005342 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensenc0618a62014-12-10 15:12:18 -05005343 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5344 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5345
Chalard Jean7d97afc2018-06-07 17:41:29 +09005346 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005347 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005348 }
5349 }
5350
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005351 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005352 final private HashMap<Uri, Integer> mUriEventMap;
5353 final private Context mContext;
5354 final private Handler mHandler;
5355
5356 SettingsObserver(Context context, Handler handler) {
5357 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005358 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005359 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005360 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005361 }
5362
Erik Kline05f2b402015-04-30 12:58:40 +09005363 void observe(Uri uri, int what) {
5364 mUriEventMap.put(uri, what);
5365 final ContentResolver resolver = mContext.getContentResolver();
5366 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005367 }
5368
5369 @Override
5370 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005371 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005372 }
5373
5374 @Override
5375 public void onChange(boolean selfChange, Uri uri) {
5376 final Integer what = mUriEventMap.get(uri);
5377 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005378 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005379 } else {
5380 loge("No matching event to send for URI=" + uri);
5381 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005382 }
5383 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005384
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005385 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005386 Log.d(TAG, s);
5387 }
5388
5389 private static void logw(String s) {
5390 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005391 }
5392
Daniel Brightf9e945b2020-06-15 16:10:01 -07005393 private static void logwtf(String s) {
5394 Log.wtf(TAG, s);
5395 }
5396
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005397 private static void logwtf(String s, Throwable t) {
5398 Log.wtf(TAG, s, t);
5399 }
5400
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005401 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005402 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005403 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005404
Hugo Benichi39621362017-02-11 17:04:43 +09005405 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005406 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005407 }
5408
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005409 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005410 * Return the information of all ongoing VPNs.
5411 *
5412 * <p>This method is used to update NetworkStatsService.
5413 *
5414 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08005415 */
junyulai2050bed2021-01-23 09:46:34 +08005416 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005417 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09005418 if (mLockdownEnabled) {
5419 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08005420 }
junyulai2050bed2021-01-23 09:46:34 +08005421 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005422 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08005423 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005424 if (info != null) {
5425 infoList.add(info);
5426 }
5427 }
junyulai2050bed2021-01-23 09:46:34 +08005428 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08005429 }
5430
5431 /**
5432 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00005433 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08005434 */
junyulai2050bed2021-01-23 09:46:34 +08005435 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005436 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08005437 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5438 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09005439 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5440 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5441 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08005442 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5443 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00005444 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00005445 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08005446 }
5447 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005448
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005449 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005450
5451 List<String> interfaces = new ArrayList<>();
5452 for (Network network : underlyingNetworks) {
5453 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5454 if (underlyingNai == null) continue;
5455 LinkProperties lp = underlyingNai.linkProperties;
5456 for (String iface : lp.getAllInterfaceNames()) {
5457 if (!TextUtils.isEmpty(iface)) {
5458 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00005459 }
5460 }
Benedict Wong34857f82019-06-12 17:46:15 +00005461 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005462
5463 if (interfaces.isEmpty()) return null;
5464
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005465 // Must be non-null or NetworkStatsService will crash.
5466 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5467 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08005468 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08005469 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005470
junyulai2050bed2021-01-23 09:46:34 +08005471 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5472 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08005473 }
5474
James Mattisd31bdfa2020-12-23 16:37:26 -08005475 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08005476 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5477 Network[] underlyingNetworks) {
5478 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005479 if (underlyingNetworks == null && defaultNetwork != null) {
5480 // null underlying networks means to track the default.
5481 underlyingNetworks = new Network[] { defaultNetwork };
5482 }
5483 return underlyingNetworks;
5484 }
5485
5486 // Returns true iff |network| is an underlying network of |nai|.
5487 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5488 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5489 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09005490 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08005491 final Network[] underlying = underlyingNetworksOrDefault(
5492 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005493 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005494 }
5495
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005496 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005497 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005498 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005499 * When underlying networks change, such networks may have to update capabilities to reflect
5500 * things like the metered bit, their transports, and so on. The capabilities are calculated
5501 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005502 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005503 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005504 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005505 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005506 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005507 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005508 }
5509 }
5510 }
5511
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005512 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5513 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5514 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5515 // a VPN is not up.
5516 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5517 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5518 for (UidRange range : blockedUidRanges) {
5519 if (range.contains(uid)) return true;
5520 }
5521 return false;
5522 }
5523
5524 @Override
5525 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08005526 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005527 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5528 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5529 }
5530
5531 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5532 if (DBG) {
5533 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5534 + Arrays.toString(ranges));
5535 }
5536 // Cannot use a Set since the list of UID ranges might contain duplicates.
5537 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5538 for (int i = 0; i < ranges.length; i++) {
5539 if (requireVpn) {
5540 newVpnBlockedUidRanges.add(ranges[i]);
5541 } else {
5542 newVpnBlockedUidRanges.remove(ranges[i]);
5543 }
5544 }
5545
5546 try {
5547 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5548 } catch (RemoteException | ServiceSpecificException e) {
5549 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5550 + Arrays.toString(ranges) + "): netd command failed: " + e);
5551 }
5552
5553 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5554 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00005555 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5556 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005557 }
5558
5559 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5560 }
5561
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07005562 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005563 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08005564 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005565 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01005566 }
5567
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005568 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5569 return mLockdownEnabled
5570 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5571 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00005572 }
5573
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005574 private NetworkAgentInfo getLegacyLockdownNai() {
5575 if (!mLockdownEnabled) {
5576 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005577 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005578 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005579 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5580 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005581
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005582 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005583 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5584 // a local variable. There is no need to make a copy because its contents cannot change.
5585 final Network[] underlying = nai.declaredUnderlyingNetworks;
5586 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005587 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005588 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005589
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005590 // The legacy lockdown VPN always uses the default network.
5591 // If the VPN's underlying network is no longer the current default network, it means that
5592 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005593 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5594 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005595 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005596 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005597 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005598 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005599
5600 return nai;
5601 };
5602
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005603 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5604 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5605 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005606 private DetailedState getLegacyLockdownState(DetailedState origState) {
5607 if (origState != DetailedState.CONNECTED) {
5608 return origState;
5609 }
5610 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5611 ? DetailedState.CONNECTING
5612 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005613 }
5614
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005615 private void filterForLegacyLockdown(NetworkInfo ni) {
5616 if (!mLockdownEnabled || !ni.isConnected()) return;
5617 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5618 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5619 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5620 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5621 // network, this time with a state of CONNECTED.
5622 //
5623 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5624 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5625 // is not too far off the truth, since an always-on VPN, when not connected, is always
5626 // trying to reconnect.
5627 if (getLegacyLockdownNai() == null) {
5628 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5629 }
5630 }
5631
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005632 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005633 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04005634 String action) {
paulhu8e96a752019-08-12 16:25:11 +08005635 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09005636 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5637 return;
5638 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04005639 final long ident = Binder.clearCallingIdentity();
5640 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09005641 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09005642 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09005643 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04005644 } finally {
5645 Binder.restoreCallingIdentity(ident);
5646 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005647 }
Wink Savillecb117d32013-08-29 14:57:08 -07005648
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005649 @Override
5650 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01005651 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005652 final long ident = Binder.clearCallingIdentity();
5653 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005654 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09005655 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005656 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5657 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08005658 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005659 } finally {
5660 Binder.restoreCallingIdentity(ident);
5661 }
5662 }
5663
James Mattis02220e22021-03-13 19:27:21 -08005664 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005665 mPermissionMonitor.onUserAdded(user);
James Mattisae9aeb02021-03-01 17:09:11 -08005666 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5667 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5668 }
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005669 }
5670
James Mattis02220e22021-03-13 19:27:21 -08005671 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005672 mPermissionMonitor.onUserRemoved(user);
Chalard Jean0f57a492021-03-09 21:09:20 +09005673 // If there was a network preference for this user, remove it.
5674 handleSetProfileNetworkPreference(new ProfileNetworkPreferences.Preference(user, null),
5675 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08005676 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5677 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5678 }
junyulaid91e7052020-08-28 13:44:33 +08005679 }
5680
James Mattis02220e22021-03-13 19:27:21 -08005681 private void onPackageChanged(@NonNull final String packageName) {
5682 // This is necessary in case a package is added or removed, but also when it's replaced to
5683 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5684 // as one in the preferences, then it should follow the same routing as that other package,
5685 // which means updating the rules is never to be needed in this case (whether it joins or
5686 // leaves a UID with a preference).
5687 if (isMappedInOemNetworkPreference(packageName)) {
5688 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5689 }
5690 }
5691
5692 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005693 @Override
5694 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09005695 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005696 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005697 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08005698
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005699 // User should be filled for below intents, check the existence.
5700 if (user == null) {
5701 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5702 return;
5703 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005704
Lorenzo Colitticd675292021-02-04 17:32:07 +09005705 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005706 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005707 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005708 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09005709 } else {
junyulaid91e7052020-08-28 13:44:33 +08005710 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005711 }
5712 }
5713 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07005714
James Mattis02220e22021-03-13 19:27:21 -08005715 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5716 @Override
5717 public void onReceive(Context context, Intent intent) {
5718 ensureRunningOnConnectivityServiceThread();
5719 switch (intent.getAction()) {
5720 case Intent.ACTION_PACKAGE_ADDED:
5721 case Intent.ACTION_PACKAGE_REMOVED:
5722 case Intent.ACTION_PACKAGE_REPLACED:
5723 onPackageChanged(intent.getData().getSchemeSpecificPart());
5724 break;
5725 default:
5726 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5727 }
5728 }
5729 };
5730
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005731 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005732 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005733
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005734 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005735 public final String name;
5736 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005737 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005738 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005739
lifraf3a3492021-03-10 13:58:14 +08005740 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5741 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005742 this.name = name;
5743 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005744 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005745 mDeathRecipient = deathRecipient;
5746
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005747 if (mDeathRecipient == null) {
5748 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005749 }
5750 }
5751
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005752 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005753 try {
5754 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5755 } catch (RemoteException e) {
5756 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005757 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005758 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005759 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005760
James Mattis4fce5d12020-11-12 15:53:42 -08005761 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
5762 for (int i = 0; i < requests.size(); i++) {
5763 ensureNetworkRequestHasType(requests.get(i));
5764 }
5765 }
5766
Lorenzo Colitti70964d32016-07-05 01:22:13 +09005767 private void ensureNetworkRequestHasType(NetworkRequest request) {
5768 if (request.type == NetworkRequest.Type.NONE) {
5769 throw new IllegalArgumentException(
5770 "All NetworkRequests in ConnectivityService must have a type");
5771 }
5772 }
5773
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005774 /**
5775 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08005776 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005777 */
James Mattis258ea3c2020-11-15 15:04:40 -08005778 @VisibleForTesting
5779 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08005780 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
5781 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08005782 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08005783
James Mattisa076c532020-12-02 14:12:41 -08005784 // mSatisfier and mActiveRequest rely on one another therefore set them together.
5785 void setSatisfier(
5786 @Nullable final NetworkAgentInfo satisfier,
5787 @Nullable final NetworkRequest activeRequest) {
5788 mSatisfier = satisfier;
5789 mActiveRequest = activeRequest;
5790 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005791
James Mattisd31bdfa2020-12-23 16:37:26 -08005792 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005793 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09005794 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08005795 private NetworkAgentInfo mSatisfier;
5796 NetworkAgentInfo getSatisfier() {
5797 return mSatisfier;
5798 }
5799
5800 // The request in mRequests assigned to a network agent. This is null if none of the
5801 // requests in mRequests can be satisfied. This member has the constraint of only being
5802 // accessible on the handler thread.
5803 @Nullable
5804 private NetworkRequest mActiveRequest;
5805 NetworkRequest getActiveRequest() {
5806 return mActiveRequest;
5807 }
5808
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005809 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08005810 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08005811 @Nullable
5812 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005813
5814 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08005815 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005816 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005817 final int mPid;
5818 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08005819 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005820 @Nullable
5821 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005822
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005823 // Counter keeping track of this NRI.
5824 final PerUidCounter mPerUidCounter;
5825
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005826 // Effective UID of this request. This is different from mUid when a privileged process
5827 // files a request on behalf of another UID. This UID is used to determine blocked status,
5828 // UID matching, and so on. mUid above is used for permission checks and to enforce the
5829 // maximum limit of registered callbacks per UID.
5830 final int mAsUid;
5831
paulhu48291862021-07-14 14:53:57 +08005832 // Preference order of this request.
5833 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08005834
James Mattis3ce3d3c2021-02-09 18:18:28 -08005835 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
5836 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
5837 // maintained for keying off of. This is only a concern when the original nri
5838 // mNetworkRequests changes which happens currently for apps that register callbacks to
5839 // track the default network. In those cases, the nri is updated to have mNetworkRequests
5840 // that match the per-app default nri that currently tracks the calling app's uid so that
5841 // callbacks are fired at the appropriate time. When the callbacks fire,
5842 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
5843 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
5844 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
5845 @NonNull
5846 private final NetworkRequest mNetworkRequestForCallback;
5847 NetworkRequest getNetworkRequestForCallback() {
5848 return mNetworkRequestForCallback;
5849 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005850
James Mattisd31bdfa2020-12-23 16:37:26 -08005851 /**
5852 * Get the list of UIDs this nri applies to.
5853 */
5854 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00005855 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08005856 // networkCapabilities.getUids() returns a defensive copy.
5857 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00005858 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
5859 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08005860 }
5861
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005862 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
5863 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08005864 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08005865 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08005866 }
5867
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005868 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08005869 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08005870 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005871 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08005872 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08005873 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005874 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08005875 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005876 mBinder = null;
5877 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005878 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005879 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005880 mPerUidCounter = getRequestCounter(this);
5881 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005882 /**
5883 * Location sensitive data not included in pending intent. Only included in
5884 * {@link NetworkCallback}.
5885 */
5886 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005887 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08005888 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005889 }
5890
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005891 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08005892 @Nullable final IBinder binder,
5893 @NetworkCallback.Flag int callbackFlags,
5894 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005895 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
5896 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08005897 }
5898
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005899 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08005900 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08005901 @Nullable final IBinder binder,
5902 @NetworkCallback.Flag int callbackFlags,
5903 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005904 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08005905 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08005906 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08005907 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08005908 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005909 mBinder = binder;
5910 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005911 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005912 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005913 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005914 mPerUidCounter = getRequestCounter(this);
5915 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005916 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005917 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08005918 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07005919 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005920 }
5921
James Mattis3ce3d3c2021-02-09 18:18:28 -08005922 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
5923 @NonNull final List<NetworkRequest> r) {
5924 super();
5925 ensureAllNetworkRequestsHaveType(r);
5926 mRequests = initializeRequests(r);
5927 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005928 final NetworkAgentInfo satisfier = nri.getSatisfier();
5929 if (null != satisfier) {
5930 // If the old NRI was satisfied by an NAI, then it may have had an active request.
5931 // The active request is necessary to figure out what callbacks to send, in
5932 // particular then a network updates its capabilities.
5933 // As this code creates a new NRI with a new set of requests, figure out which of
5934 // the list of requests should be the active request. It is always the first
5935 // request of the list that can be satisfied by the satisfier since the order of
5936 // requests is a priority order.
5937 // Note even in the presence of a satisfier there may not be an active request,
5938 // when the satisfier is the no-service network.
5939 NetworkRequest activeRequest = null;
5940 for (final NetworkRequest candidate : r) {
5941 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
5942 activeRequest = candidate;
5943 break;
5944 }
5945 }
5946 setSatisfier(satisfier, activeRequest);
5947 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08005948 mMessenger = nri.mMessenger;
5949 mBinder = nri.mBinder;
5950 mPid = nri.mPid;
5951 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005952 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08005953 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09005954 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005955 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005956 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08005957 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08005958 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07005959 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08005960 }
5961
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005962 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08005963 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08005964 }
5965
paulhue9913722021-05-26 15:19:20 +08005966 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08005967 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08005968 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08005969 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08005970 }
5971
James Mattis2516da32021-01-31 17:06:19 -08005972 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
5973 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
5974 // false.
5975 boolean isBeingSatisfied() {
5976 return (null != mSatisfier && null != mActiveRequest);
5977 }
5978
James Mattis3d229892020-11-16 16:46:28 -08005979 boolean isMultilayerRequest() {
5980 return mRequests.size() > 1;
5981 }
5982
James Mattis45d81842021-01-10 14:24:24 -08005983 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
5984 // Creating a defensive copy to prevent the sender from modifying the list being
5985 // reflected in the return value of this method.
5986 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08005987 return Collections.unmodifiableList(tempRequests);
5988 }
5989
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005990 void decrementRequestCount() {
5991 mPerUidCounter.decrementCount(mUid);
5992 }
5993
James Mattisb1392002021-03-31 13:57:52 -07005994 void linkDeathRecipient() {
5995 if (null != mBinder) {
5996 try {
5997 mBinder.linkToDeath(this, 0);
5998 } catch (RemoteException e) {
5999 binderDied();
6000 }
6001 }
6002 }
6003
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006004 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006005 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006006 try {
6007 mBinder.unlinkToDeath(this, 0);
6008 } catch (NoSuchElementException e) {
6009 // Temporary workaround for b/194394697 pending analysis of additional logs
6010 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6011 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006012 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006013 }
6014
paulhu48291862021-07-14 14:53:57 +08006015 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6016 // Compare two preference orders.
6017 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006018 }
6019
paulhu48291862021-07-14 14:53:57 +08006020 int getPreferenceOrderForNetd() {
6021 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6022 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6023 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006024 }
paulhu48291862021-07-14 14:53:57 +08006025 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006026 }
6027
James Mattis4fce5d12020-11-12 15:53:42 -08006028 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006029 public void binderDied() {
6030 log("ConnectivityService NetworkRequestInfo binderDied(" +
Chalard Jean524f0b12021-10-25 21:11:56 +09006031 "uid/pid:" + mUid + "/" + mPid + ", " + mRequests + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09006032 // As an immutable collection, mRequests cannot change by the time the
6033 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6034 // is acceptable. Use handleReleaseNetworkRequest and not directly
6035 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6036 // the app already unregistered the request.
6037 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6038 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006039 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006040
James Mattis4fce5d12020-11-12 15:53:42 -08006041 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006042 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006043 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6044 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006045 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006046 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006047 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006048 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006049 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006050 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006051 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006052 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006053 }
6054
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006055 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
6056 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
6057 if (badCapability != null) {
6058 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenee52d232015-06-16 15:11:58 -04006059 }
6060 }
6061
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006062 // This checks that the passed capabilities either do not request a
6063 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006064 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006065 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006066 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006067 throw new SecurityException("Insufficient permissions to request a specific SSID");
6068 }
paulhu1a407652019-03-22 16:35:06 +08006069
6070 if (nc.hasSignalStrength()
6071 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6072 throw new SecurityException(
6073 "Insufficient permissions to request a specific signal strength");
6074 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006075 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006076
junyulai2217bec2021-04-14 23:33:31 +08006077 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006078 enforceNetworkFactoryPermission();
6079 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006080 }
6081
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006082 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006083 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006084 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006085 // mNetworkRequests may contain the same value multiple times in case of
6086 // multilayer requests. It won't matter in this case because the thresholds
6087 // will then be the same and be deduplicated as they enter the `thresholds` set.
6088 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006089 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6090 for (final NetworkRequest req : nri.mRequests) {
6091 if (req.networkCapabilities.hasSignalStrength()
6092 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6093 thresholds.add(req.networkCapabilities.getSignalStrength());
6094 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006095 }
6096 }
6097 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006098 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006099 }
6100
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006101 private void updateSignalStrengthThresholds(
6102 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006103 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006104
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006105 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006106 String detail;
6107 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6108 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6109 } else {
6110 detail = reason;
6111 }
6112 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006113 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006114 }
6115
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006116 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006117 }
6118
Etan Cohen1b6d4182017-04-03 17:42:34 -07006119 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
6120 if (nc == null) {
6121 return;
6122 }
6123 NetworkSpecifier ns = nc.getNetworkSpecifier();
6124 if (ns == null) {
6125 return;
6126 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006127 if (ns instanceof MatchAllNetworkSpecifier) {
6128 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6129 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006130 }
6131
lucasline117e2e2019-10-22 18:27:33 +08006132 private void ensureValid(NetworkCapabilities nc) {
6133 ensureValidNetworkSpecifier(nc);
6134 if (nc.isPrivateDnsBroken()) {
6135 throw new IllegalArgumentException("Can't request broken private DNS");
6136 }
6137 }
6138
Chiachang Wang3bc52762021-11-25 14:17:57 +08006139 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6140 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006141 private boolean isTargetSdkAtleast(int version, int callingUid,
6142 @NonNull String callingPackageName) {
6143 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006144 final PackageManager pm =
6145 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006146 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006147 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006148 if (callingVersion < version) return false;
6149 } catch (PackageManager.NameNotFoundException e) { }
6150 return true;
6151 }
6152
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006153 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006154 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006155 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006156 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006157 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006158 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006159 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6160 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006161 throw new SecurityException("Insufficient permissions to specify legacy type");
6162 }
markchienfac84a22020-03-18 21:16:15 +08006163 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006164 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006165 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006166 // Privileged callers can track the default network of another UID by passing in a UID.
6167 if (asUid != Process.INVALID_UID) {
6168 enforceSettingsPermission();
6169 } else {
6170 asUid = callingUid;
6171 }
junyulaiad010792021-01-11 16:53:38 +08006172 final NetworkRequest.Type reqType;
6173 try {
6174 reqType = NetworkRequest.Type.values()[reqTypeInt];
6175 } catch (ArrayIndexOutOfBoundsException e) {
6176 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6177 }
6178 switch (reqType) {
6179 case TRACK_DEFAULT:
6180 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006181 // is unused and will be replaced by ones appropriate for the UID (usually, the
6182 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006183 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006184 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006185 enforceAccessPermission();
6186 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006187 case TRACK_SYSTEM_DEFAULT:
6188 enforceSettingsPermission();
6189 networkCapabilities = new NetworkCapabilities(defaultNc);
6190 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006191 case BACKGROUND_REQUEST:
6192 enforceNetworkStackOrSettingsPermission();
6193 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006194 case REQUEST:
6195 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6196 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6197 callingAttributionTag);
6198 // TODO: this is incorrect. We mark the request as metered or not depending on
6199 // the state of the app when the request is filed, but we never change the
6200 // request if the app changes network state. http://b/29964605
6201 enforceMeteredApnPolicy(networkCapabilities);
6202 break;
junyulai1b1c8742021-03-12 20:05:08 +08006203 case LISTEN_FOR_BEST:
6204 enforceAccessPermission();
6205 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6206 break;
junyulaiad010792021-01-11 16:53:38 +08006207 default:
6208 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006209 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006210 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006211 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006212 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006213
junyulai1b1c8742021-03-12 20:05:08 +08006214 // Enforce FOREGROUND if the caller does not have permission to use background network.
6215 if (reqType == LISTEN_FOR_BEST) {
6216 restrictBackgroundRequestForCaller(networkCapabilities);
6217 }
6218
6219 // Set the UID range for this request to the single UID of the requester, unless the
6220 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006221 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6222 // are no visible methods to set the UIDs, an app could use reflection to try and get
6223 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006224 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006225 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6226 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006227
Etan Cohen85000162017-02-05 10:42:27 -08006228 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006229 throw new IllegalArgumentException("Bad timeout specified");
6230 }
lucasline117e2e2019-10-22 18:27:33 +08006231 ensureValid(networkCapabilities);
Etan Cohen9786d922015-11-18 10:56:15 -08006232
James Mattis3ce3d3c2021-02-09 18:18:28 -08006233 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006234 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006235 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006236 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006237 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006238 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006239
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006240 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6241 // copied from the default request above. (This is necessary to ensure, for example, that
6242 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6243 // changes don't alter request matching.
6244 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6245 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006246 throw new IllegalStateException(
6247 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006248 + networkCapabilities + " vs. " + defaultNc);
6249 }
6250
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006251 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006252 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006253 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006254 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006255 }
6256 return networkRequest;
6257 }
6258
James Mattis3ce3d3c2021-02-09 18:18:28 -08006259 /**
6260 * Return the nri to be used when registering a network request. Specifically, this is used with
6261 * requests registered to track the default request. If there is currently a per-app default
6262 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6263 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006264 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6265 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006266 * @param nr the network request for the nri.
6267 * @param msgr the messenger for the nri.
6268 * @param binder the binder for the nri.
6269 * @param callingAttributionTag the calling attribution tag for the nri.
6270 * @return the nri to register.
6271 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006272 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006273 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006274 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006275 @Nullable String callingAttributionTag) {
6276 final List<NetworkRequest> requests;
6277 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6278 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006279 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006280 } else {
6281 requests = Collections.singletonList(nr);
6282 }
Roshan Pius951c0032020-12-22 15:10:42 -08006283 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006284 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006285 }
6286
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006287 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
6288 String callingPackageName, String callingAttributionTag) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006289 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichibd0cc762016-07-19 15:59:27 +09006290 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006291 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006292 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006293 }
6294 }
6295
fenglu3f357402015-03-20 11:29:56 -07006296 @Override
fenglub00f4882015-04-21 17:12:05 -07006297 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006298 enforceAccessPermission();
6299 NetworkAgentInfo nai = null;
6300 if (network == null) {
6301 return false;
6302 }
6303 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006304 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006305 }
6306 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006307 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006308 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006309 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006310 Integer uidReqs = mBandwidthRequests.get(uid);
6311 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006312 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006313 }
6314 mBandwidthRequests.put(uid, ++uidReqs);
6315 }
fenglu3f357402015-03-20 11:29:56 -07006316 return true;
6317 }
6318 return false;
6319 }
6320
Felipe Leme0a5ae422016-06-20 16:36:29 -07006321 private boolean isSystem(int uid) {
6322 return uid < Process.FIRST_APPLICATION_UID;
6323 }
fenglu3f357402015-03-20 11:29:56 -07006324
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006325 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006326 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006327 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006328 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006329 return;
6330 }
Hugo Benichi39621362017-02-11 17:04:43 +09006331 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6332 // Policy already enforced.
6333 return;
6334 }
paulhuaf50d7d2020-12-24 19:47:34 +08006335 final long ident = Binder.clearCallingIdentity();
6336 try {
6337 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6338 // If UID is restricted, don't allow them to bring up metered APNs.
6339 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6340 }
6341 } finally {
6342 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006343 }
6344 }
6345
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006346 @Override
6347 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006348 PendingIntent operation, @NonNull String callingPackageName,
6349 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006350 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006351 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006352 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006353 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6354 callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006355 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006356 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006357 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006358 Binder.getCallingPid(), callingUid, callingPackageName);
Etan Cohen1b6d4182017-04-03 17:42:34 -07006359 ensureValidNetworkSpecifier(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006360 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6361 callingUid, callingPackageName);
Etan Cohen89134542017-04-03 12:17:51 -07006362
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006363 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006364 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006365 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6366 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006367 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006368 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6369 nri));
6370 return networkRequest;
6371 }
6372
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006373 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6374 mHandler.sendMessageDelayed(
6375 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006376 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006377 }
6378
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006379 @Override
6380 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006381 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006382 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006383 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006384 }
6385
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006386 // In order to implement the compatibility measure for pre-M apps that call
6387 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6388 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6389 // This ensures it has permission to do so.
6390 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6391 if (nc == null) {
6392 return false;
6393 }
6394 int[] transportTypes = nc.getTransportTypes();
6395 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6396 return false;
6397 }
6398 try {
6399 mContext.enforceCallingOrSelfPermission(
6400 android.Manifest.permission.ACCESS_WIFI_STATE,
6401 "ConnectivityService");
6402 } catch (SecurityException e) {
6403 return false;
6404 }
6405 return true;
6406 }
6407
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006408 @Override
6409 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08006410 Messenger messenger, IBinder binder,
6411 @NetworkCallback.Flag int callbackFlags,
6412 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006413 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006414 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6415 enforceAccessPermission();
6416 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006417
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006418 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006419 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006420 Binder.getCallingPid(), callingUid, callingPackageName);
6421 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09006422 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6423 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6424 // onLost and onAvailable callbacks when networks move in and out of the background.
6425 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6426 // can't request networks.
6427 restrictBackgroundRequestForCaller(nc);
lucasline117e2e2019-10-22 18:27:33 +08006428 ensureValid(nc);
Etan Cohen89134542017-04-03 12:17:51 -07006429
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006430 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006431 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08006432 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006433 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08006434 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006435 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006436
6437 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6438 return networkRequest;
6439 }
6440
6441 @Override
6442 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08006443 PendingIntent operation, @NonNull String callingPackageName,
6444 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006445 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006446 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04006447 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6448 enforceAccessPermission();
6449 }
lucasline117e2e2019-10-22 18:27:33 +08006450 ensureValid(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006451 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006452 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006453 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006454 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006455
6456 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006457 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006458 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6459 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006460 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04006461
WeiZhang1cc3f172021-06-03 19:02:04 -05006462 mHandler.sendMessage(mHandler.obtainMessage(
6463 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006464 }
6465
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006466 /** Returns the next Network provider ID. */
6467 public final int nextNetworkProviderId() {
6468 return mNextNetworkProviderId.getAndIncrement();
6469 }
6470
Erik Kline0c04b742016-07-07 16:50:58 +09006471 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006472 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006473 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09006474 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006475 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006476 }
6477
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006478 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6479 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006480 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6481 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6482 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08006483 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006484 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006485 return;
6486 }
6487
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006488 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6489 mNetworkProviderInfos.put(npi.messenger, npi);
6490 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006491 }
6492
6493 @Override
6494 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006495 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08006496 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006497 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08006498 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006499 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6500 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006501 }
6502
6503 @Override
6504 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006505 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006506 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006507 }
6508
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006509 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09006510 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006511 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6512 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09006513 Objects.requireNonNull(score);
6514 Objects.requireNonNull(caps);
6515 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09006516 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006517 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09006518 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
6519 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006520 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6521 }
6522
Chalard Jeanbb902a52021-08-18 01:35:19 +09006523 private void updateOfferScore(final NetworkOffer offer) {
6524 final boolean yieldToBadWiFi =
6525 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
6526 final NetworkOffer newOffer = new NetworkOffer(
6527 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
6528 offer.caps, offer.callback, offer.providerId);
6529 if (offer.equals(newOffer)) return;
6530 handleRegisterNetworkOffer(newOffer);
6531 }
6532
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006533 @Override
6534 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6535 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6536 }
6537
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006538 private void handleUnregisterNetworkProvider(Messenger messenger) {
6539 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6540 if (npi == null) {
6541 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006542 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006543 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006544 // Unregister all the offers from this provider
6545 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6546 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09006547 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006548 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6549 toRemove.add(noi);
6550 }
6551 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09006552 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006553 handleUnregisterNetworkOffer(noi);
6554 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006555 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006556 }
6557
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006558 @Override
James Mattisf7027322020-12-13 16:28:14 -08006559 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006560 if (request.hasTransport(TRANSPORT_TEST)) {
6561 enforceNetworkFactoryOrTestNetworksPermission();
6562 } else {
6563 enforceNetworkFactoryPermission();
6564 }
James Mattisf7027322020-12-13 16:28:14 -08006565 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6566 if (nri != null) {
6567 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6568 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6569 mHandler.post(() -> handleReleaseNetworkRequest(
6570 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6571 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006572 }
6573
Paul Jensen1f567382015-02-13 14:18:39 -05006574 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6575 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006576 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05006577 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006578 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05006579 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006580 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006581
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09006582 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05006583 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006584 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006585
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006586 // UID ranges for users that are currently blocked by VPNs.
6587 // This array is accessed and iterated on multiple threads without holding locks, so its
6588 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6589 // (on the handler thread).
6590 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6591
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006592 // Must only be accessed on the handler thread
6593 @NonNull
6594 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6595
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006596 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006597 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006598
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006599 // Current OEM network preferences. This object must only be written to on the handler thread.
6600 // Since it is immutable and always non-null, other threads may read it if they only care
6601 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08006602 @NonNull
6603 private OemNetworkPreferences mOemNetworkPreferences =
6604 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006605 // Current per-profile network preferences. This object follows the same threading rules as
6606 // the OEM network preferences above.
6607 @NonNull
6608 private ProfileNetworkPreferences mProfileNetworkPreferences = new ProfileNetworkPreferences();
James Mattis45d81842021-01-10 14:24:24 -08006609
paulhu51f77dc2021-06-07 02:34:20 +00006610 // A set of UIDs that should use mobile data preferentially if available. This object follows
6611 // the same threading rules as the OEM network preferences above.
6612 @NonNull
6613 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
6614
James Mattiscb1e0362021-04-06 17:07:42 -07006615 // OemNetworkPreferences activity String log entries.
6616 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6617 @NonNull
6618 private final LocalLog mOemNetworkPreferencesLogs =
6619 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6620
James Mattis02220e22021-03-13 19:27:21 -08006621 /**
6622 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6623 * @param packageName the package name to check existence of a mapping for.
6624 * @return true if a mapping exists, false otherwise
6625 */
6626 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6627 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6628 }
6629
James Mattise3ef1912020-12-20 11:09:58 -08006630 // The always-on request for an Internet-capable network that apps without a specific default
6631 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08006632 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09006633 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006634 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08006635 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08006636 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08006637 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006638 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006639
James Mattisd31bdfa2020-12-23 16:37:26 -08006640 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6641 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6642 }
6643
6644 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08006645 * Return the default network request currently tracking the given uid.
6646 * @param uid the uid to check.
6647 * @return the NetworkRequestInfo tracking the given uid.
6648 */
6649 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08006650 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08006651 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006652 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006653 // Checking the first request is sufficient as only multilayer requests will have more
6654 // than one request and for multilayer, all requests will track the same uids.
6655 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08006656 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08006657 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08006658 highestPriorityNri = nri;
6659 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006660 }
6661 }
paulhuaa0743d2021-05-26 21:56:03 +08006662 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006663 }
6664
6665 /**
6666 * Get a copy of the network requests of the default request that is currently tracking the
6667 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006668 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6669 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006670 * @param requestorUid the uid to check the default for.
6671 * @param requestorPackageName the requestor's package name.
6672 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6673 */
6674 @NonNull
6675 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006676 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006677 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006678 getDefaultRequestTrackingUid(asUid).mRequests,
6679 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006680 }
6681
6682 /**
6683 * Copy the given nri's NetworkRequest collection.
6684 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006685 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6686 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006687 * @param requestorUid the uid to set on the copied collection.
6688 * @param requestorPackageName the package name to set on the copied collection.
6689 * @return the copied NetworkRequest collection.
6690 */
6691 @NonNull
6692 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006693 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6694 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006695 final List<NetworkRequest> requests = new ArrayList<>();
6696 for (final NetworkRequest nr : requestsToCopy) {
6697 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006698 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08006699 nr.legacyType, nextNetworkRequestId(), nr.type));
6700 }
6701 return requests;
6702 }
6703
6704 @NonNull
6705 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006706 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6707 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09006708 // These capabilities are for a TRACK_DEFAULT callback, so:
6709 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6710 // mDefaultRequest and a per-UID default request.
6711 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006712 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09006713 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006714 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6715 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006716 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006717 restrictRequestUidsForCallerAndSetRequestorInfo(
6718 netCap, requestorUid, requestorPackageName);
6719 return netCap;
6720 }
6721
6722 /**
6723 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6724 * @param nr the network request to check for equality against.
6725 * @return the nri if one exists, null otherwise.
6726 */
6727 @Nullable
6728 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6729 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6730 if (nri.getNetworkRequestForCallback().equals(nr)) {
6731 return nri;
6732 }
6733 }
6734 return null;
6735 }
6736
6737 /**
6738 * Check if an nri is currently being managed by per-app default networking.
6739 * @param nri the nri to check.
6740 * @return true if this nri is currently being managed by per-app default networking.
6741 */
6742 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
6743 // nri.mRequests.get(0) is only different from the original request filed in
6744 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
6745 // functionality therefore if these two don't match, it means this particular nri is
6746 // currently being managed by a per-app default.
6747 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
6748 }
6749
6750 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08006751 * Determine if an nri is a managed default request that disallows default networking.
6752 * @param nri the request to evaluate
6753 * @return true if device-default networking is disallowed
6754 */
6755 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
6756 // Check if this nri is a managed default that supports the default network at its
6757 // lowest priority request.
6758 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
6759 final NetworkCapabilities lowestPriorityNetCap =
6760 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
6761 return isPerAppDefaultRequest(nri)
6762 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
6763 lowestPriorityNetCap));
6764 }
6765
Erik Kline05f2b402015-04-30 12:58:40 +09006766 // Request used to optionally keep mobile data active even when higher
6767 // priority networks like Wi-Fi are active.
6768 private final NetworkRequest mDefaultMobileDataRequest;
6769
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006770 // Request used to optionally keep wifi data active even when higher
6771 // priority networks like ethernet are active.
6772 private final NetworkRequest mDefaultWifiRequest;
6773
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08006774 // Request used to optionally keep vehicle internal network always active
6775 private final NetworkRequest mDefaultVehicleRequest;
6776
James Mattisd31bdfa2020-12-23 16:37:26 -08006777 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
6778 // network with no service. This NAI should never be matched against, nor should any public API
6779 // ever return the associated network. For this reason, this NAI is not in the list of available
6780 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
6781 // default requests that don't support using the device default network which will ultimately
6782 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
6783 @VisibleForTesting
6784 final NetworkAgentInfo mNoServiceNetwork;
6785
Chalard Jean5b409c72021-02-04 13:12:59 +09006786 // The NetworkAgentInfo currently satisfying the default request, if any.
6787 private NetworkAgentInfo getDefaultNetwork() {
6788 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09006789 }
6790
James Mattis2516da32021-01-31 17:06:19 -08006791 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08006792 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08006793 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6794 // Currently, all network requests will have the same uids therefore checking the first
6795 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006796 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08006797 if (null == uids) {
6798 continue;
6799 }
6800 for (final UidRange range : uids) {
6801 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08006802 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08006803 highestPriorityNri = nri;
6804 }
James Mattis2516da32021-01-31 17:06:19 -08006805 }
6806 }
6807 }
paulhuaa0743d2021-05-26 21:56:03 +08006808 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08006809 }
6810
Varun Ananddf569952019-02-06 10:13:38 -08006811 @Nullable
6812 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
6813 return nai != null ? nai.network : null;
6814 }
6815
6816 private void ensureRunningOnConnectivityServiceThread() {
6817 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
6818 throw new IllegalStateException(
6819 "Not running on ConnectivityService thread: "
6820 + Thread.currentThread().getName());
6821 }
6822 }
6823
Chalard Jean3a3f5f22019-04-10 23:07:55 +09006824 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09006825 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
6826 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006827 }
6828
Chalard Jean29d06db2018-05-02 21:14:54 +09006829 /**
6830 * Register a new agent with ConnectivityService to handle a network.
6831 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006832 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09006833 * @param networkInfo the initial info associated with this network. It can be updated later :
6834 * see {@link #updateNetworkInfo}.
6835 * @param linkProperties the initial link properties of this network. They can be updated
6836 * later : see {@link #updateLinkProperties}.
6837 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09006838 * later : see {@link #updateCapabilities}.
Chalard Jean28018572020-12-21 18:36:52 +09006839 * @param initialScore the initial score of the network. See
Chalard Jean29d06db2018-05-02 21:14:54 +09006840 * {@link NetworkAgentInfo#getCurrentScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006841 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006842 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09006843 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09006844 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006845 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09006846 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09006847 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
6848 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09006849 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
6850 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
6851 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09006852 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09006853 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09006854 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6855 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006856 } else {
6857 enforceNetworkFactoryPermission();
6858 }
6859
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006860 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006861 final long token = Binder.clearCallingIdentity();
6862 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006863 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09006864 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006865 } finally {
6866 Binder.restoreCallingIdentity(token);
6867 }
6868 }
6869
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006870 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006871 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09006872 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
6873 int uid) {
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006874 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
Chalard Jean5b639762020-03-09 21:25:37 +09006875 // Strictly, sanitizing here is unnecessary as the capabilities will be sanitized in
6876 // the call to mixInCapabilities below anyway, but sanitizing here means the NAI never
6877 // sees capabilities that may be malicious, which might prevent mistakes in the future.
6878 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Chiachang Wangc07315a2021-08-10 15:13:39 +08006879 networkCapabilities.restrictCapabilitiesForTestNetwork(uid);
Chalard Jean5b639762020-03-09 21:25:37 +09006880 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006881
Rubin Xuffd77d82017-09-05 18:40:49 +01006882 LinkProperties lp = new LinkProperties(linkProperties);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006883
Chalard Jeana23bc9e2018-01-30 22:41:41 +09006884 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006885 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006886 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo), lp, nc,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09006887 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09006888 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
6889 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006890
6891 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006892 processCapabilitiesFromAgent(nai, nc);
Chalard Jean05edd052019-11-22 22:39:56 +09006893 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006894 processLinkPropertiesFromAgent(nai, nai.linkProperties);
6895
Chalard Jeanf2da1772018-04-26 16:16:10 +09006896 final String extraInfo = networkInfo.getExtraInfo();
6897 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09006898 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07006899 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006900 mDeps.getNetworkStack().makeNetworkMonitor(
6901 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006902 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
6903 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006904 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006905 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09006906 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006907 }
6908
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006909 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
6910 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006911 if (VDBG) log("Got NetworkAgent Messenger");
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006912 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05006913 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006914 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05006915 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006916
6917 try {
6918 networkMonitor.start();
6919 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08006920 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006921 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006922 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09006923 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09006924 updateNetworkInfo(nai, networkInfo);
6925 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006926 }
6927
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006928 private class NetworkOfferInfo implements IBinder.DeathRecipient {
6929 @NonNull public final NetworkOffer offer;
6930
6931 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
6932 this.offer = offer;
6933 }
6934
6935 @Override
6936 public void binderDied() {
6937 mHandler.post(() -> handleUnregisterNetworkOffer(this));
6938 }
6939 }
6940
Chalard Jeandd35f2d2021-03-24 14:31:38 +09006941 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
6942 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
6943 if (npi.providerId == providerId) return true;
6944 }
6945 return false;
6946 }
6947
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006948 /**
6949 * Register or update a network offer.
6950 * @param newOffer The new offer. If the callback member is the same as an existing
6951 * offer, it is an update of that offer.
6952 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09006953 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006954 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
6955 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09006956 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006957 // This may actually happen if a provider updates its score or registers and then
6958 // immediately unregisters. The offer would still be in the handler queue, but the
6959 // provider would have been removed.
6960 if (DBG) log("Received offer from an unregistered provider");
6961 return;
6962 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006963 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
6964 if (null != existingOffer) {
6965 handleUnregisterNetworkOffer(existingOffer);
6966 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09006967 if (DBG) {
6968 // handleUnregisterNetworkOffer has already logged the old offer
6969 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
6970 }
6971 } else {
6972 if (DBG) {
6973 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
6974 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006975 }
6976 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
6977 try {
Chalard Jean30689b82021-03-22 22:44:02 +09006978 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006979 } catch (RemoteException e) {
6980 noi.binderDied();
6981 return;
6982 }
6983 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09006984 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006985 }
6986
6987 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
6988 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09006989 if (DBG) {
6990 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
6991 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07006992
6993 // If the provider removes the offer and dies immediately afterwards this
6994 // function may be called twice in a row, but the array will no longer contain
6995 // the offer.
6996 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09006997 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006998 }
6999
7000 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7001 @NonNull final INetworkOfferCallback callback) {
7002 ensureRunningOnConnectivityServiceThread();
7003 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007004 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007005 }
7006 return null;
7007 }
7008
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007009 /**
7010 * Called when receiving LinkProperties directly from a NetworkAgent.
7011 * Stores into |nai| any data coming from the agent that might also be written to the network's
7012 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7013 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007014 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007015 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007016 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7017 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007018 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007019 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007020 }
7021
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007022 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007023 @NonNull LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007024 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007025
Lorenzo Colittid523d142020-04-01 20:16:30 +09007026 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7027 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7028 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007029 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007030
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007031 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007032
7033 // update filtering rules, need to happen after the interface update so netd knows about the
7034 // new interface (the interface name -> index map becomes initialized)
7035 updateVpnFiltering(newLp, oldLp, networkAgent);
7036
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007037 updateMtu(newLp, oldLp);
7038 // TODO - figure out what to do for clat
7039// for (LinkProperties lp : newLp.getStackedLinks()) {
7040// updateMtu(lp, null);
7041// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007042 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007043 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7044 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007045
Erik Klineb9888902016-04-05 13:30:49 +09007046 updateRoutes(newLp, oldLp, netId);
7047 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007048 // Make sure LinkProperties represents the latest private DNS status.
7049 // This does not need to be done before updateDnses because the
7050 // LinkProperties are not the source of the private DNS configuration.
7051 // updateDnses will fetch the private DNS configuration from DnsManager.
7052 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007053
Chalard Jean5b409c72021-02-04 13:12:59 +09007054 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007055 handleApplyDefaultProxy(newLp.getHttpProxy());
7056 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007057 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007058 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007059
7060 updateWakeOnLan(newLp);
7061
Hai Shalome58bdc62021-01-11 18:45:34 -08007062 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7063 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7064 // does, it needs to be merged here.
7065 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7066 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007067
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007068 // TODO - move this check to cover the whole function
7069 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007070 synchronized (networkAgent) {
7071 networkAgent.linkProperties = newLp;
7072 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007073 // Start or stop DNS64 detection and 464xlat according to network state.
7074 networkAgent.clatd.update();
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08007075 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007076 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7077 new LinkProperties(newLp, true /* parcelSensitiveFields */));
lucaslin74fa3972018-11-28 12:51:55 +08007078 if (networkAgent.everConnected) {
7079 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
7080 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007081 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007082
7083 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007084 }
7085
Hai Shalome58bdc62021-01-11 18:45:34 -08007086 /**
7087 * @param naData captive portal data from NetworkAgent
7088 * @param apiData captive portal data from capport API
7089 */
7090 @Nullable
7091 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7092 CaptivePortalData apiData) {
7093 if (naData == null || apiData == null) {
7094 return naData == null ? apiData : naData;
7095 }
7096 final CaptivePortalData.Builder captivePortalBuilder =
7097 new CaptivePortalData.Builder(naData);
7098
7099 if (apiData.isCaptive()) {
7100 captivePortalBuilder.setCaptive(true);
7101 }
7102 if (apiData.isSessionExtendable()) {
7103 captivePortalBuilder.setSessionExtendable(true);
7104 }
7105 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7106 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7107 // otherwise data would be inconsistent. Prefer the capport API info if present,
7108 // as it can generally be refreshed more often.
7109 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7110 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7111 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7112 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7113 // No source has time / bytes remaining information: surface the newest refresh time
7114 // for other fields
7115 captivePortalBuilder.setRefreshTime(
7116 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7117 }
7118
Hai Shalom7c6ab402021-02-04 19:34:06 -08007119 // Prioritize the user portal URL from the network agent if the source is authenticated.
7120 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7121 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7122 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7123 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007124 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007125 // Prioritize the venue information URL from the network agent if the source is
7126 // authenticated.
7127 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7128 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7129 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7130 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007131 }
7132 return captivePortalBuilder.build();
7133 }
7134
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007135 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007136 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007137 // marks on unsupported interfaces is harmless.
7138 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7139 return;
7140 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007141
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007142 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7143 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7144
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007145 // Mask/mark of zero will not detect anything interesting.
7146 // Don't install rules unless both values are nonzero.
7147 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007148 return;
7149 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007150
7151 final String prefix = "iface:" + iface;
7152 try {
7153 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007154 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007155 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007156 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007157 }
7158 } catch (Exception e) {
7159 loge("Exception modifying wakeup packet monitoring: " + e);
7160 }
7161
Joel Scherpelza235a812017-05-22 13:47:41 +09007162 }
7163
Chalard Jean9589e722019-11-19 19:03:53 +09007164 private void updateInterfaces(final @Nullable LinkProperties newLp,
7165 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007166 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09007167 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fa7d9e2017-08-22 16:35:52 +01007168 oldLp != null ? oldLp.getAllInterfaceNames() : null,
7169 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jean9589e722019-11-19 19:03:53 +09007170 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007171 for (final String iface : interfaceDiff.added) {
7172 try {
7173 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007174 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09007175 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007176 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7177 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007178 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007179 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007180 }
Paul Jensenbff73492014-04-28 10:33:11 -04007181 }
7182 }
Chalard Jean9589e722019-11-19 19:03:53 +09007183 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007184 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007185 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007186 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007187 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007188 } catch (Exception e) {
7189 loge("Exception removing interface: " + e);
7190 }
7191 }
7192 }
7193
Tyler Weare4314862019-12-05 14:55:30 -08007194 // TODO: move to frameworks/libs/net.
7195 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7196 final String nextHop;
7197
7198 switch (route.getType()) {
7199 case RouteInfo.RTN_UNICAST:
7200 if (route.hasGateway()) {
7201 nextHop = route.getGateway().getHostAddress();
7202 } else {
7203 nextHop = INetd.NEXTHOP_NONE;
7204 }
7205 break;
7206 case RouteInfo.RTN_UNREACHABLE:
7207 nextHop = INetd.NEXTHOP_UNREACHABLE;
7208 break;
7209 case RouteInfo.RTN_THROW:
7210 nextHop = INetd.NEXTHOP_THROW;
7211 break;
7212 default:
7213 nextHop = INetd.NEXTHOP_NONE;
7214 break;
7215 }
7216
7217 final RouteInfoParcel rip = new RouteInfoParcel();
7218 rip.ifName = route.getInterface();
7219 rip.destination = route.getDestination().toString();
7220 rip.nextHop = nextHop;
7221 rip.mtu = route.getMtu();
7222
7223 return rip;
7224 }
7225
Paul Jensene0fd4a82014-08-06 15:51:33 -04007226 /**
7227 * Have netd update routes from oldLp to newLp.
7228 * @return true if routes changed between oldLp and newLp
7229 */
7230 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007231 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007232 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7233 new CompareOrUpdateResult<>(
7234 oldLp != null ? oldLp.getAllRoutes() : null,
7235 newLp != null ? newLp.getAllRoutes() : null,
7236 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007237
7238 // add routes before removing old in case it helps with continuous connectivity
7239
Chalard Jean9dd11612018-06-04 16:52:49 +09007240 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007241 for (RouteInfo route : routeDiff.added) {
7242 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007243 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007244 try {
Tyler Weare4314862019-12-05 14:55:30 -08007245 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007246 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007247 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007248 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007249 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007250 }
7251 }
7252 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007253 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007254 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007255 try {
Tyler Weare4314862019-12-05 14:55:30 -08007256 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007257 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007258 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007259 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007260 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007261 }
7262 }
7263
7264 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007265 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007266 try {
Tyler Weare4314862019-12-05 14:55:30 -08007267 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007268 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007269 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007270 }
7271 }
Tyler Weare4314862019-12-05 14:55:30 -08007272
7273 for (RouteInfo route : routeDiff.updated) {
7274 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7275 try {
7276 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7277 } catch (Exception e) {
7278 loge("Exception in networkUpdateRouteParcel: " + e);
7279 }
7280 }
7281 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7282 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007283 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007284
Erik Klineb9888902016-04-05 13:30:49 +09007285 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7286 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7287 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007288 }
Erik Klineb9888902016-04-05 13:30:49 +09007289
Erik Kline31b4a9e2018-01-11 21:07:29 +09007290 if (DBG) {
7291 final Collection<InetAddress> dnses = newLp.getDnsServers();
7292 log("Setting DNS servers for network " + netId + " to " + dnses);
7293 }
Erik Klineb9888902016-04-05 13:30:49 +09007294 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007295 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007296 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007297 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007298 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007299 }
Erik Kline54e35c02017-04-07 15:29:29 +09007300 }
7301
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007302 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7303 NetworkAgentInfo nai) {
7304 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
7305 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
7306 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
7307 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
7308
7309 if (!wasFiltering && !needsFiltering) {
7310 // Nothing to do.
7311 return;
7312 }
7313
7314 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7315 // Nothing changed.
7316 return;
7317 }
7318
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007319 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Qingxi Libb8da982020-01-17 17:54:27 -08007320 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007321 // TODO: this create a window of opportunity for apps to receive traffic between the time
7322 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007323 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007324 // old rules are being removed.
7325 if (wasFiltering) {
7326 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7327 }
7328 if (needsFiltering) {
7329 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7330 }
7331 }
7332
Valentin Iftime9fa35092019-09-24 13:32:13 +02007333 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007334 if (mWolSupportedInterfaces == null) {
7335 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007336 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007337 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007338 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7339 }
7340
Luke Huangb913c812018-08-24 20:33:16 +08007341 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007342 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007343 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007344 }
7345 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007346 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007347 }
Luke Huangb913c812018-08-24 20:33:16 +08007348 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007349 }
7350
Chalard Jean62edfd82019-12-02 18:39:29 +09007351 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7352 @NonNull final NetworkCapabilities newNc) {
7353 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7354 final int newPermission = getNetworkPermission(newNc);
7355 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7356 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007357 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08007358 } catch (RemoteException | ServiceSpecificException e) {
7359 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09007360 }
7361 }
7362 }
7363
Paul Jensen53f08952015-06-16 14:27:36 -04007364 /**
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007365 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7366 * Stores into |nai| any data coming from the agent that might also be written to the network's
7367 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7368 * agent is not lost when updateCapabilities is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007369 * This method should never alter the agent's NetworkCapabilities, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007370 */
7371 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007372 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7373 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7374 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7375 // the owner UID here and behave as if the agent had never tried to change it.
Lorenzo Colitti93401342020-12-09 18:30:52 +09007376 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7377 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7378 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7379 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7380 }
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007381 nai.declaredCapabilities = new NetworkCapabilities(nc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007382 }
7383
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007384 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007385 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09007386 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007387 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08007388 underlyingNetworks = underlyingNetworksOrDefault(
7389 agentCaps.getOwnerUid(), underlyingNetworks);
lifrade6c2a2021-03-04 14:08:08 +08007390 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007391 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7392 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007393 // metered if any underlying is metered, or originally declared metered by the agent.
7394 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007395 boolean roaming = false; // roaming if any underlying is roaming
7396 boolean congested = false; // congested if any underlying is congested
7397 boolean suspended = true; // suspended if all underlying are suspended
7398
7399 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08007400 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007401 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08007402 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007403 for (Network underlyingNetwork : underlyingNetworks) {
7404 final NetworkAgentInfo underlying =
7405 getNetworkAgentInfoForNetwork(underlyingNetwork);
7406 if (underlying == null) continue;
7407
7408 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7409 hadUnderlyingNetworks = true;
7410 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007411 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007412 }
7413
7414 // Merge capabilities of this underlying network. For bandwidth, assume the
7415 // worst case.
7416 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7417 underlyingCaps.getLinkDownstreamBandwidthKbps());
7418 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7419 underlyingCaps.getLinkUpstreamBandwidthKbps());
7420 // If this underlying network is metered, the VPN is metered (it may cost money
7421 // to send packets on this network).
7422 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7423 // If this underlying network is roaming, the VPN is roaming (the billing structure
7424 // is different than the usual, local one).
7425 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7426 // If this underlying network is congested, the VPN is congested (the current
7427 // condition of the network affects the performance of this network).
7428 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7429 // If this network is not suspended, the VPN is not suspended (the VPN
7430 // is able to transfer some data).
7431 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08007432 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007433 }
7434 }
7435 if (!hadUnderlyingNetworks) {
7436 // No idea what the underlying networks are; assume reasonable defaults
7437 metered = true;
7438 roaming = false;
7439 congested = false;
7440 suspended = false;
7441 }
7442
lifrade6c2a2021-03-04 14:08:08 +08007443 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007444 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7445 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7446 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7447 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7448 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7449 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08007450 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007451 }
7452
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007453 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007454 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7455 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7456 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04007457 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007458 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007459 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09007460 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007461 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7462 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007463 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007464 // avoid connect/teardown loops.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007465 if (nai.everConnected &&
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007466 !nai.isVPN() &&
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007467 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7468 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09007469 // does not cause any request (that is not a listen) currently matching that agent to
7470 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007471 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09007472 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007473 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09007474 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007475 }
7476
Paul Jensen53f08952015-06-16 14:27:36 -04007477 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007478 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensende49eb12015-06-25 15:30:08 -04007479 if (nai.lastValidated) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007480 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007481 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007482 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007483 }
Paul Jensende49eb12015-06-25 15:30:08 -04007484 if (nai.lastCaptivePortalDetected) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007485 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007486 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007487 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007488 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007489 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007490 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007491 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007492 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007493 }
lucaslin2240ef62019-03-12 13:08:03 +08007494 if (nai.partialConnectivity) {
7495 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7496 } else {
7497 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7498 }
lucasline117e2e2019-10-22 18:27:33 +08007499 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007500
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007501 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09007502 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7503 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007504 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09007505 }
7506
Lorenzo Colittibd079452021-07-02 11:47:57 +09007507 if (nai.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007508 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7509 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007510 }
7511
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007512 return newNc;
7513 }
7514
Lorenzo Colitti44840702021-01-11 22:27:57 +09007515 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7516 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7517 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7518 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7519 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7520 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7521 if (prevSuspended != suspended) {
7522 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7523 // onResumed have been removed.
7524 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7525 : ConnectivityManager.CALLBACK_RESUMED);
7526 }
7527 if (prevSuspended != suspended || prevRoaming != roaming) {
7528 // updateNetworkInfo will mix in the suspended info from the capabilities and
7529 // take appropriate action for the network having possibly changed state.
7530 updateNetworkInfo(nai, nai.networkInfo);
7531 }
7532 }
7533
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007534 /**
7535 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7536 *
7537 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7538 * capabilities we manage and store in {@code nai}, such as validated status and captive
7539 * portal status)
7540 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7541 * potentially triggers rematches.
7542 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7543 * change.)
7544 *
7545 * @param oldScore score of the network before any of the changes that prompted us
7546 * to call this function.
7547 * @param nai the network having its capabilities updated.
7548 * @param nc the new network capabilities.
7549 */
Chalard Jean62edfd82019-12-02 18:39:29 +09007550 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7551 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007552 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007553 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean62edfd82019-12-02 18:39:29 +09007554 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09007555 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007556
Chalard Jeanb2a49912018-01-16 18:43:05 +09007557 updateUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09007558 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007559
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007560 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007561 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7562 // the change we're processing can't affect any requests, it can only affect the listens
7563 // on this network. We might have been called by rematchNetworkAndRequests when a
7564 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09007565 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007566 } else {
7567 // If the requestable capabilities have changed or the score changed, we can't have been
7568 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09007569 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04007570 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07007571 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09007572 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007573
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007574 final boolean oldMetered = prevNc.isMetered();
7575 final boolean newMetered = newNc.isMetered();
7576 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08007577
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007578 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00007579 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7580 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007581 }
junyulaif2c67e42018-08-07 19:50:45 +08007582
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007583 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7584 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08007585
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007586 // Report changes that are interesting for network statistics tracking.
7587 if (meteredChanged || roamingChanged) {
7588 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06007589 }
7590
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007591 // This network might have been underlying another network. Propagate its capabilities.
7592 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08007593
7594 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007595 mDnsManager.updateTransportsForNetwork(
7596 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08007597 }
lucaslin53e8a262021-06-08 01:43:59 +08007598
7599 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007600 }
7601
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007602 /** Convenience method to update the capabilities for a given network. */
7603 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7604 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7605 }
7606
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007607 /**
7608 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7609 * network.
7610 *
7611 * Ingress interface filtering enforces that all apps under the given network can only receive
7612 * packets from the network's interface (and loopback). This is important for VPNs because
7613 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7614 * non-VPN interfaces.
7615 *
7616 * As a result, this method should return true iff
7617 * 1. the network is an app VPN (not legacy VPN)
7618 * 2. the VPN does not allow bypass
7619 * 3. the VPN is fully-routed
7620 * 4. the VPN interface is non-null
7621 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007622 * @see INetd#firewallAddUidInterfaceRules
7623 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007624 */
7625 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7626 LinkProperties lp) {
7627 if (nc == null || lp == null) return false;
7628 return nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007629 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08007630 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007631 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08007632 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7633 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007634 }
7635
Chiachang Wang28afaff2020-12-10 22:24:47 +08007636 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7637 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7638 int index = 0;
7639 for (UidRange range : ranges) {
7640 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7641 index++;
7642 }
7643 return stableRanges;
7644 }
7645
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007646 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7647 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7648 for (int i = 0; i < ranges.length; i++) {
7649 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7650 }
7651 return stableRanges;
7652 }
7653
Ken Chen5e65a852020-12-24 12:59:10 +08007654 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7655 int[] exemptUids) {
7656 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7657 try {
7658 mNetd.socketDestroy(ranges, exemptUids);
7659 } catch (Exception e) {
7660 loge("Exception in socket destroy: ", e);
7661 }
7662 }
7663 }
7664
paulhuaa0743d2021-05-26 21:56:03 +08007665 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08007666 int[] exemptUids = new int[2];
7667 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7668 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7669 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7670 exemptUids[0] = VPN_UID;
7671 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7672 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7673
7674 maybeCloseSockets(nai, ranges, exemptUids);
7675 try {
7676 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08007677 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007678 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08007679 } else {
paulhu0e79d952021-06-09 16:11:35 +08007680 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007681 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08007682 }
7683 } catch (Exception e) {
7684 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7685 " on netId " + nai.network.netId + ". " + e);
7686 }
7687 maybeCloseSockets(nai, ranges, exemptUids);
7688 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007689
lucaslin53e8a262021-06-08 01:43:59 +08007690 private boolean isProxySetOnAnyDefaultNetwork() {
7691 ensureRunningOnConnectivityServiceThread();
7692 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7693 final NetworkAgentInfo nai = nri.getSatisfier();
7694 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
7695 return true;
7696 }
7697 }
7698 return false;
7699 }
7700
7701 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7702 NetworkCapabilities newNc) {
7703 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
7704 // the proxy might be changed since the default network satisfied by the apps might also
7705 // changed.
7706 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
7707 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09007708 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
7709 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
7710 if (nai.isVPN() && nai.everConnected && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08007711 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
7712 mProxyTracker.sendProxyBroadcast();
7713 }
7714 }
7715
Chalard Jeanb2a49912018-01-16 18:43:05 +09007716 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7717 NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007718 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7719 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007720 if (null == prevRanges) prevRanges = new ArraySet<>();
7721 if (null == newRanges) newRanges = new ArraySet<>();
7722 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
7723
7724 prevRanges.removeAll(newRanges);
7725 newRanges.removeAll(prevRangesCopy);
7726
7727 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007728 // When updating the VPN uid routing rules, add the new range first then remove the old
7729 // range. If old range were removed first, there would be a window between the old
7730 // range being removed and the new range being added, during which UIDs contained
7731 // in both ranges are not subject to any VPN routing rules. Adding new range before
7732 // removing old range works because, unlike the filtering rules below, it's possible to
7733 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08007734 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
7735 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
7736 // [1-5] & [1-2],[4-5] == [3]
7737 // Then we can do:
7738 // maybeCloseSockets([3])
7739 // mNetd.networkAddUidRanges([1-2],[4-5])
7740 // mNetd.networkRemoveUidRanges([1-5])
7741 // maybeCloseSockets([3])
7742 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
7743 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09007744 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08007745 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007746 }
7747 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08007748 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007749 }
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007750 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
7751 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
7752 final String iface = nai.linkProperties.getInterfaceName();
7753 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09007754 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007755 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
7756 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
7757 // were added first and then newRanges got removed later, there would be only one uid
7758 // 10013 left. A consequence of removing old ranges before adding new ranges is that
7759 // there is now a window of opportunity when the UIDs are not subject to any filtering.
7760 // Note that this is in contrast with the (more robust) update of VPN routing rules
7761 // above, where the addition of new ranges happens before the removal of old ranges.
7762 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
7763 // to be removed will never overlap with the new range to be added.
7764 if (wasFiltering && !prevRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08007765 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007766 }
7767 if (shouldFilter && !newRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08007768 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007769 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09007770 } catch (Exception e) {
7771 // Never crash!
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007772 loge("Exception in updateUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007773 }
7774 }
7775
Hugo Benichi9d35b752017-09-01 01:23:32 +00007776 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09007777 ensureRunningOnConnectivityServiceThread();
7778
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007779 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00007780 // Ignore updates for disconnected networks
7781 return;
7782 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007783 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09007784 log("Update of LinkProperties for " + nai.toShortString()
7785 + "; created=" + nai.created
7786 + "; everConnected=" + nai.everConnected);
Hugo Benichi9d35b752017-09-01 01:23:32 +00007787 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007788 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
7789 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08007790 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00007791 }
7792
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007793 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
7794 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007795 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007796 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08007797 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08007798 // If apps could file multi-layer requests with PendingIntents, they'd need to know
7799 // which of the layer is satisfied alongside with some ID for the request. Hence, if
7800 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09007801 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
7802 // need to be sent as a separate extra.
7803 final NetworkRequest req = nri.isMultilayerRequest()
7804 ? nri.getActiveRequest()
7805 // Non-multilayer listen requests do not have an active request
7806 : nri.mRequests.get(0);
7807 if (req == null) {
7808 Log.wtf(TAG, "No request in NRI " + nri);
7809 }
7810 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007811 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007812 sendIntent(nri.mPendingIntent, intent);
7813 }
7814 // else not handled
7815 }
7816
7817 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
7818 mPendingIntentWakeLock.acquire();
7819 try {
7820 if (DBG) log("Sending " + pendingIntent);
7821 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
7822 } catch (PendingIntent.CanceledException e) {
7823 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
7824 mPendingIntentWakeLock.release();
7825 releasePendingNetworkRequest(pendingIntent);
7826 }
7827 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
7828 }
7829
7830 @Override
7831 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
7832 String resultData, Bundle resultExtras) {
7833 if (DBG) log("Finished sending " + pendingIntent);
7834 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007835 // Release with a delay so the receiving client has an opportunity to put in its
7836 // own request.
7837 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007838 }
7839
James Mattis212df9e2020-12-03 19:57:41 -08007840 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
7841 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
7842 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08007843 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08007844 // Default request has no msgr. Also prevents callbacks from being invoked for
7845 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
7846 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
7847 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007848 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007849 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08007850 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007851 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007852 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08007853 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007854 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007855 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
7856 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007857 }
Roshan Pius951c0032020-12-22 15:10:42 -08007858 final boolean includeLocationSensitiveInfo =
7859 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007860 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09007861 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08007862 final NetworkCapabilities nc =
7863 networkCapabilitiesRestrictedForCallerPermissions(
7864 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7865 putParcelable(
7866 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08007867 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08007868 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08007869 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08007870 nri.mCallingAttributionTag));
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09007871 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7872 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08007873 // For this notification, arg1 contains the blocked status.
7874 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09007875 break;
7876 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007877 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007878 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007879 break;
7880 }
7881 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09007882 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08007883 final NetworkCapabilities netCap =
7884 networkCapabilitiesRestrictedForCallerPermissions(
7885 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7886 putParcelable(
7887 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08007888 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08007889 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08007890 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08007891 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007892 break;
7893 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007894 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09007895 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7896 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007897 break;
7898 }
junyulaif2c67e42018-08-07 19:50:45 +08007899 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09007900 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08007901 msg.arg1 = arg1;
7902 break;
7903 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007904 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007905 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007906 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007907 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007908 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09007909 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08007910 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007911 }
James Mattis45d81842021-01-10 14:24:24 -08007912 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007913 } catch (RemoteException e) {
7914 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08007915 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007916 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007917 }
7918
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007919 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
7920 bundle.putParcelable(t.getClass().getSimpleName(), t);
7921 }
7922
Chalard Jean0702f982021-09-16 21:50:07 +09007923 /**
7924 * Returns whether reassigning a request from an NAI to another can be done gracefully.
7925 *
7926 * When a request should be assigned to a new network, it is normally lingered to give
7927 * time for apps to gracefully migrate their connections. When both networks are on the same
7928 * radio, but that radio can't do time-sharing efficiently, this may end up being
7929 * counter-productive because any traffic on the old network may drastically reduce the
7930 * performance of the new network.
7931 * The stack supports a configuration to let modem vendors state that their radio can't
7932 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
7933 * from one cell network to another can't be done gracefully.
7934 *
7935 * @param oldNai the old network serving the request
7936 * @param newNai the new network serving the request
7937 * @return whether the switch can be graceful
7938 */
7939 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
7940 @NonNull final NetworkAgentInfo newSatisfier) {
7941 if (mCellularRadioTimesharingCapable) return true;
7942 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
7943 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
7944 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
7945 }
7946
Paul Jensenaf94b982014-09-30 15:37:41 -04007947 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09007948 if (nai.numRequestNetworkRequests() != 0) {
7949 for (int i = 0; i < nai.numNetworkRequests(); i++) {
7950 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007951 // Ignore listening and track default requests.
7952 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09007953 loge("Dead network still had at least " + nr);
7954 break;
7955 }
Paul Jensenaf94b982014-09-30 15:37:41 -04007956 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007957 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04007958 }
7959
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007960 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
7961 if (oldNetwork == null) {
7962 loge("Unknown NetworkAgentInfo in handleLingerComplete");
7963 return;
7964 }
Chalard Jean49707572019-12-10 21:07:02 +09007965 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007966
7967 // If we get here it means that the last linger timeout for this network expired. So there
7968 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08007969 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007970
Lorenzo Colitti2666be82016-09-09 18:48:56 +09007971 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007972 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007973 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007974 } else {
junyulai0ac374f2020-12-14 18:41:52 +08007975 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007976 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007977 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007978 }
7979
James Mattise3ef1912020-12-20 11:09:58 -08007980 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
7981 boolean isDefaultChanged = false;
7982 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
7983 final NetworkReassignment.RequestReassignment reassignment =
7984 changes.getReassignment(defaultRequestInfo);
7985 if (null == reassignment) {
7986 continue;
7987 }
7988 // reassignment only contains those instances where the satisfying network changed.
7989 isDefaultChanged = true;
7990 // Notify system services of the new default.
7991 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
7992 }
Chiachang Wang087fd272018-09-28 22:42:48 +08007993
James Mattise3ef1912020-12-20 11:09:58 -08007994 if (isDefaultChanged) {
7995 // Hold a wakelock for a short time to help apps in migrating to a new default.
7996 scheduleReleaseNetworkTransitionWakelock();
7997 }
7998 }
7999
8000 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8001 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8002 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8003 if (DBG) {
8004 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8005 }
Chalard Jean8e382112019-12-03 20:45:30 +09008006
James Mattisd31bdfa2020-12-23 16:37:26 -08008007 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8008 if (newDefaultNetwork != null) {
8009 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008010 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008011
James Mattisd31bdfa2020-12-23 16:37:26 -08008012 // Set an app level managed default and return since further processing only applies to the
8013 // default network.
8014 if (mDefaultRequest != nri) {
8015 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8016 return;
8017 }
8018
8019 makeDefaultNetwork(newDefaultNetwork);
8020
James Mattise3ef1912020-12-20 11:09:58 -08008021 if (oldDefaultNetwork != null) {
8022 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8023 }
8024 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008025 handleApplyDefaultProxy(null != newDefaultNetwork
8026 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8027 updateTcpBufferSizes(null != newDefaultNetwork
8028 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008029 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008030 }
8031
James Mattisd31bdfa2020-12-23 16:37:26 -08008032 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8033 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8034 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8035 try {
8036 if (VDBG) {
8037 log("Setting default network for " + nri
8038 + " using UIDs " + nri.getUids()
8039 + " with old network " + (oldDefaultNetwork != null
8040 ? oldDefaultNetwork.network().getNetId() : "null")
8041 + " and new network " + (newDefaultNetwork != null
8042 ? newDefaultNetwork.network().getNetId() : "null"));
8043 }
8044 if (nri.getUids().isEmpty()) {
8045 throw new IllegalStateException("makeDefaultForApps called without specifying"
8046 + " any applications to set as the default." + nri);
8047 }
8048 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008049 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008050 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008051 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008052 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008053 }
8054 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008055 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008056 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008057 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008058 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008059 }
8060 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008061 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008062 }
8063 }
8064
8065 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8066 try {
8067 if (null != newDefaultNetwork) {
8068 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8069 } else {
8070 mNetd.networkClearDefault();
8071 }
8072 } catch (RemoteException | ServiceSpecificException e) {
8073 loge("Exception setting default network :" + e);
8074 }
8075 }
8076
Chalard Jean05cbe972019-12-09 11:50:38 +09008077 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008078 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09008079 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09008080 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09008081 processNewlySatisfiedListenRequests(nai);
8082 }
8083
8084 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008085 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8086 if (nri.isMultilayerRequest()) {
8087 continue;
8088 }
8089 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008090 if (!nr.isListen()) continue;
8091 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08008092 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008093 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
8094 }
8095 }
Chalard Jeancd397a22019-11-22 22:33:33 +09008096 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008097
Chalard Jeancd397a22019-11-22 22:33:33 +09008098 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008099 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8100 if (nri.isMultilayerRequest()) {
8101 continue;
8102 }
8103 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008104 if (!nr.isListen()) continue;
8105 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
8106 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09008107 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008108 }
8109 }
8110 }
8111
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008112 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008113 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008114 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08008115 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09008116 @Nullable public final NetworkRequest mOldNetworkRequest;
8117 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008118 @Nullable public final NetworkAgentInfo mOldNetwork;
8119 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08008120 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008121 @Nullable final NetworkRequest oldNetworkRequest,
8122 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008123 @Nullable final NetworkAgentInfo oldNetwork,
8124 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008125 mNetworkRequestInfo = networkRequestInfo;
8126 mOldNetworkRequest = oldNetworkRequest;
8127 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008128 mOldNetwork = oldNetwork;
8129 mNewNetwork = newNetwork;
8130 }
Chalard Jean49707572019-12-10 21:07:02 +09008131
8132 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09008133 final NetworkRequest requestToShow = null != mNewNetworkRequest
8134 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
8135 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08008136 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
8137 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09008138 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008139 }
8140
Chalard Jean46a62372019-12-10 21:25:24 +09008141 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008142
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008143 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09008144 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008145 }
8146
8147 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09008148 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09008149 // The code is never supposed to add two reassignments of the same request. Make
8150 // sure this stays true, but without imposing this expensive check on all
8151 // reassignments on all user devices.
8152 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08008153 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09008154 throw new IllegalStateException("Trying to reassign ["
8155 + reassignment + "] but already have ["
8156 + existing + "]");
8157 }
8158 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09008159 }
Chalard Jean46a62372019-12-10 21:25:24 +09008160 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008161 }
8162
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008163 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09008164 // the passed request.
8165 @Nullable
8166 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008167 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008168 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008169 }
8170 return null;
8171 }
Chalard Jean49707572019-12-10 21:07:02 +09008172
8173 public String toString() {
8174 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8175 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09008176 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008177 for (final RequestReassignment rr : getRequestReassignments()) {
8178 sj.add(rr.toString());
8179 }
8180 return sj.toString();
8181 }
8182
8183 public String debugString() {
8184 final StringBuilder sb = new StringBuilder();
8185 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09008186 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008187 for (final RequestReassignment rr : getRequestReassignments()) {
8188 sb.append("\n ").append(rr);
8189 }
8190 return sb.append("\n").toString();
8191 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008192 }
8193
Chalard Jean24344d72019-12-04 13:32:31 +09008194 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008195 @Nullable final NetworkRequest previousRequest,
8196 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09008197 @Nullable final NetworkAgentInfo previousSatisfier,
8198 @Nullable final NetworkAgentInfo newSatisfier,
8199 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08008200 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09008201 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09008202 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008203 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008204 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09008205 }
James Mattisa076c532020-12-02 14:12:41 -08008206 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean0702f982021-09-16 21:50:07 +09008207 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)) {
8208 // If this network switch can't be supported gracefully, the request is not
8209 // lingered. This allows letting go of the network sooner to reclaim some
8210 // performance on the new network, since the radio can't do both at the same
8211 // time while preserving good performance.
8212 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8213 }
Chalard Jean24344d72019-12-04 13:32:31 +09008214 } else {
8215 if (VDBG || DDBG) log(" accepting network in place of null");
8216 }
junyulai0ac374f2020-12-14 18:41:52 +08008217
8218 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8219 // and immediately satisfies a request then remove the timer. This will happen for
8220 // all networks except in the case of an underlying network for a VCN.
8221 if (newSatisfier.isNascent()) {
8222 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08008223 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008224 }
8225
Chalard Jean5d6e23b2021-03-01 22:00:20 +09008226 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08008227 newSatisfier.unlingerRequest(newRequest.requestId);
8228 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008229 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08008230 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008231 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09008232 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008233 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008234 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08008235 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008236 }
James Mattisa076c532020-12-02 14:12:41 -08008237 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008238 }
James Mattisa076c532020-12-02 14:12:41 -08008239 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008240 }
8241
James Mattisa076c532020-12-02 14:12:41 -08008242 /**
8243 * This function is triggered when something can affect what network should satisfy what
8244 * request, and it computes the network reassignment from the passed collection of requests to
8245 * network match to the one that the system should now have. That data is encoded in an
8246 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8247 * satisfier.
8248 *
8249 * After the reassignment is computed, it is applied to the state objects.
8250 *
8251 * @param networkRequests the nri objects to evaluate for possible network reassignment
8252 * @return NetworkReassignment listing of proposed network assignment changes
8253 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008254 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08008255 private NetworkReassignment computeNetworkReassignment(
8256 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09008257 final NetworkReassignment changes = new NetworkReassignment();
8258
Chalard Jeanc81d4c32021-04-07 17:06:19 +09008259 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09008260 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008261 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattisa076c532020-12-02 14:12:41 -08008262 if (!nai.everConnected) {
8263 continue;
8264 }
Chalard Jean857a1712019-12-10 21:08:07 +09008265 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09008266 }
Chalard Jean857a1712019-12-10 21:08:07 +09008267
James Mattisa076c532020-12-02 14:12:41 -08008268 for (final NetworkRequestInfo nri : networkRequests) {
8269 // Non-multilayer listen requests can be ignored.
8270 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8271 continue;
8272 }
8273 NetworkAgentInfo bestNetwork = null;
8274 NetworkRequest bestRequest = null;
8275 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09008276 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08008277 // Stop evaluating as the highest possible priority request is satisfied.
8278 if (null != bestNetwork) {
8279 bestRequest = req;
8280 break;
8281 }
8282 }
James Mattisd31bdfa2020-12-23 16:37:26 -08008283 if (null == bestNetwork && isDefaultBlocked(nri)) {
8284 // Remove default networking if disallowed for managed default requests.
8285 bestNetwork = mNoServiceNetwork;
8286 }
8287 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09008288 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09008289 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08008290 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09008291 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008292 }
8293 return changes;
8294 }
8295
James Mattisa076c532020-12-02 14:12:41 -08008296 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8297 return new HashSet<>(mNetworkRequests.values());
8298 }
8299
Paul Jensenc88b39b2015-06-16 14:27:36 -04008300 /**
James Mattisa076c532020-12-02 14:12:41 -08008301 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04008302 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04008303 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008304 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08008305 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8306 }
8307
8308 /**
8309 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8310 * being disconnected.
8311 */
8312 private void rematchNetworksAndRequests(
8313 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8314 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09008315 // TODO: This may be slow, and should be optimized.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008316 final long now = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08008317 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jean49707572019-12-10 21:07:02 +09008318 if (VDBG || DDBG) {
8319 log(changes.debugString());
8320 } else if (DBG) {
8321 log(changes.toString()); // Shorter form, only one line of log
8322 }
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008323 applyNetworkReassignment(changes, now);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008324 issueNetworkNeeds();
Chalard Jeand7f762d2019-12-10 19:01:29 +09008325 }
Chalard Jean64520dc2019-12-04 19:55:32 +09008326
Chalard Jeand7f762d2019-12-10 19:01:29 +09008327 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008328 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008329 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09008330
8331 // Since most of the time there are only 0 or 1 background networks, it would probably
8332 // be more efficient to just use an ArrayList here. TODO : measure performance
8333 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8334 for (final NetworkAgentInfo nai : nais) {
8335 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8336 }
8337
Chalard Jeand7f762d2019-12-10 19:01:29 +09008338 // First, update the lists of satisfied requests in the network agents. This is necessary
8339 // because some code later depends on this state to be correct, most prominently computing
8340 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09008341 for (final NetworkReassignment.RequestReassignment event :
8342 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008343 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8344 event.mOldNetworkRequest, event.mNewNetworkRequest,
8345 event.mOldNetwork, event.mNewNetwork,
8346 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09008347 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008348
James Mattise3ef1912020-12-20 11:09:58 -08008349 // Process default network changes if applicable.
8350 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008351
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008352 // Notify requested networks are available after the default net is switched, but
8353 // before LegacyTypeTracker sends legacy broadcasts
8354 for (final NetworkReassignment.RequestReassignment event :
8355 changes.getRequestReassignments()) {
8356 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008357 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008358 } else {
James Mattisa076c532020-12-02 14:12:41 -08008359 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008360 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008361 }
8362 }
8363
junyulai0ac374f2020-12-14 18:41:52 +08008364 // Update the inactivity state before processing listen callbacks, because the background
8365 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008366 // just yet though, because they have to be sent after the listens are processed to keep
8367 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08008368 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09008369 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08008370 // Rematching may have altered the inactivity state of some networks, so update all
8371 // inactivity timers. updateInactivityState reads the state from the network agent
8372 // and does nothing if the state has not changed : the source of truth is controlled
8373 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8374 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08008375 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08008376 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008377 }
8378 }
8379
Chalard Jeanb10ab412019-12-11 14:12:30 +09008380 for (final NetworkAgentInfo nai : nais) {
8381 if (!nai.everConnected) continue;
8382 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008383 // Process listen requests and update capabilities if the background state has
8384 // changed for this network. For consistency with previous behavior, send onLost
8385 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09008386 processNewlyLostListenRequests(nai);
8387 if (oldBackground != nai.isBackgroundNetwork()) {
8388 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008389 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09008390 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008391 }
8392
junyulai0ac374f2020-12-14 18:41:52 +08008393 for (final NetworkAgentInfo nai : inactiveNetworks) {
8394 // For nascent networks, if connecting with no foreground request, skip broadcasting
8395 // LOSING for backward compatibility. This is typical when mobile data connected while
8396 // wifi connected with mobile data always-on enabled.
8397 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008398 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008399 }
8400
James Mattise3ef1912020-12-20 11:09:58 -08008401 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09008402
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008403 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008404 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008405 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08008406 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008407 // This network has active linger timers and no requests, but is not
8408 // lingering. Linger it.
8409 //
8410 // One way (the only way?) this can happen if this network is unvalidated
8411 // and became unneeded due to another network improving its score to the
8412 // point where this network will no longer be able to satisfy any requests
8413 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08008414 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008415 notifyNetworkLosing(nai, now);
8416 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09008417 } else {
Chalard Jean49707572019-12-10 21:07:02 +09008418 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09008419 teardownUnneededNetwork(nai);
8420 }
8421 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04008422 }
8423 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008424
Chalard Jean62edfd82019-12-02 18:39:29 +09008425 /**
8426 * Apply a change in background state resulting from rematching networks with requests.
8427 *
8428 * During rematch, a network may change background states by starting to satisfy or stopping
8429 * to satisfy a foreground request. Listens don't count for this. When a network changes
8430 * background states, its capabilities need to be updated and callbacks fired for the
8431 * capability change.
8432 *
8433 * @param nai The network that changed background states
8434 */
8435 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8436 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8437 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8438 updateNetworkPermissions(nai, newNc);
8439 nai.getAndSetNetworkCapabilities(newNc);
8440 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8441 }
8442
Chalard Jeanf0344532019-11-19 19:23:38 +09008443 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08008444 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008445 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09008446 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8447 changes.getReassignment(mDefaultRequest);
8448 final NetworkAgentInfo oldDefaultNetwork =
8449 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8450 final NetworkAgentInfo newDefaultNetwork =
8451 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08008452
Chalard Jean5b409c72021-02-04 13:12:59 +09008453 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008454 // Maintain the illusion : since the legacy API only understands one network at a time,
8455 // if the default network changed, apps should see a disconnected broadcast for the
8456 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09008457 if (oldDefaultNetwork != null) {
8458 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8459 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008460 }
Chalard Jean5b409c72021-02-04 13:12:59 +09008461 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008462 // The new default network can be newly null if and only if the old default
8463 // network doesn't satisfy the default request any more because it lost a
8464 // capability.
Chalard Jean5b409c72021-02-04 13:12:59 +09008465 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08008466 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09008467 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008468 }
8469 }
8470
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008471 // Now that all the callbacks have been sent, send the legacy network broadcasts
8472 // as needed. This is necessary so that legacy requests correctly bind dns
8473 // requests to this network. The legacy users are listening for this broadcast
8474 // and will generally do a dns request so they can ensureRouteToHost and if
8475 // they do that before the callbacks happen they'll use the default network.
8476 //
8477 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8478 // callbacks, but if apps can receive the broadcast before the callback, they still might
8479 // have an inconsistent view of networking.
8480 //
8481 // This *does* introduce a race where if the user uses the new api
8482 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8483 // they may get old info. Reverse this after the old startUsing api is removed.
8484 // This is on top of the multiple intent sequencing referenced in the todo above.
8485 for (NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008486 if (nai.everConnected) {
8487 addNetworkToLegacyTypeTracker(nai);
8488 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08008489 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008490 }
8491
Chalard Jean0354d8c2021-01-12 10:58:56 +09008492 private void issueNetworkNeeds() {
8493 ensureRunningOnConnectivityServiceThread();
8494 for (final NetworkOfferInfo noi : mNetworkOffers) {
8495 issueNetworkNeeds(noi);
8496 }
8497 }
8498
8499 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8500 ensureRunningOnConnectivityServiceThread();
8501 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8502 informOffer(nri, noi.offer, mNetworkRanker);
8503 }
8504 }
8505
8506 /**
8507 * Inform a NetworkOffer about any new situation of a request.
8508 *
8509 * This function handles updates to offers. A number of events may happen that require
8510 * updating the registrant for this offer about the situation :
8511 * • The offer itself was updated. This may lead the offer to no longer being able
8512 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8513 * or conversely being strengthened enough to beat the satisfier (and therefore
8514 * start being needed)
8515 * • The network satisfying a request changed (including cases where the request
8516 * starts or stops being satisfied). The new network may be a stronger or weaker
8517 * match than the old one, possibly affecting whether the offer is needed.
8518 * • The network satisfying a request updated their score. This may lead the offer
8519 * to no longer be able to beat it if the current satisfier got better, or
8520 * conversely start being a good choice if the current satisfier got weaker.
8521 *
8522 * @param nri The request
8523 * @param offer The offer. This may be an updated offer.
8524 */
8525 private static void informOffer(@NonNull NetworkRequestInfo nri,
8526 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
8527 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
8528 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09008529
8530 // Multi-layer requests have a currently active request, the one being satisfied.
8531 // Since the system will try to bring up a better network than is currently satisfying
8532 // the request, NetworkProviders need to be told the offers matching the requests *above*
8533 // the currently satisfied one are needed, that the ones *below* the satisfied one are
8534 // not needed, and the offer is needed for the active request iff the offer can beat
8535 // the satisfier.
8536 // For non-multilayer requests, the logic above gracefully degenerates to only the
8537 // last case.
8538 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
8539 // providers that the offer is needed for this request, until the active request is found.
8540 // In a second phase, deal with the currently active request. In a third phase, inform
8541 // the providers that offer is unneeded for the remaining requests.
8542
8543 // First phase : inform providers of all requests above the active request.
8544 int i;
8545 for (i = 0; nri.mRequests.size() > i; ++i) {
8546 final NetworkRequest request = nri.mRequests.get(i);
8547 if (activeRequest == request) break; // Found the active request : go to phase 2
8548 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8549 // Since this request is higher-priority than the one currently satisfied, if the
8550 // offer can satisfy it, the provider should try and bring up the network for sure ;
8551 // no need to even ask the ranker – an offer that can satisfy is always better than
8552 // no network. Hence tell the provider so unless it already knew.
8553 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
8554 offer.onNetworkNeeded(request);
8555 }
8556 }
8557
8558 // Second phase : deal with the active request (if any)
8559 if (null != activeRequest && activeRequest.isRequest()) {
8560 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00008561 // If an offer can satisfy the request, it is considered needed if it is currently
8562 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09008563 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00008564 && satisfier.factorySerialNumber == offer.providerId
8565 && activeRequest.canBeSatisfiedBy(offer.caps);
8566 final boolean newNeeded = currentlyServing
8567 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008568 if (newNeeded != oldNeeded) {
8569 if (newNeeded) {
8570 offer.onNetworkNeeded(activeRequest);
8571 } else {
8572 // The offer used to be able to beat the satisfier. Now it can't.
8573 offer.onNetworkUnneeded(activeRequest);
8574 }
8575 }
8576 }
8577
8578 // Third phase : inform the providers that the offer isn't needed for any request
8579 // below the active one.
8580 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
8581 final NetworkRequest request = nri.mRequests.get(i);
8582 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8583 // Since this request is lower-priority than the one currently satisfied, if the
8584 // offer can satisfy it, the provider should not try and bring up the network.
8585 // Hence tell the provider so unless it already knew.
8586 if (offer.neededFor(request)) {
8587 offer.onNetworkUnneeded(request);
8588 }
8589 }
8590 }
8591
Chalard Jean61c79252019-11-07 23:07:32 +09008592 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8593 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8594 NetworkRequest nr = nai.requestAt(i);
8595 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8596 // legacy type tracker filters out repeat adds
8597 mLegacyTypeTracker.add(nr.legacyType, nai);
8598 }
8599 }
8600
8601 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09008602 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09008603 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8604 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8605 if (nai.isVPN()) {
8606 mLegacyTypeTracker.add(TYPE_VPN, nai);
8607 }
8608 }
8609
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008610 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04008611 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittia8de5ca2014-12-17 11:14:42 +09008612 if (!nai.everValidated) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09008613 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04008614 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09008615 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008616
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008617 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008618 // Don't repeat publish.
8619 if (newInetCondition == mDefaultInetConditionPublished) return;
8620
8621 mDefaultInetConditionPublished = newInetCondition;
8622 sendInetConditionBroadcast(nai.networkInfo);
8623 }
8624
Chalard Jeand61375d2020-01-14 22:46:36 +09008625 @NonNull
8626 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8627 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008628 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09008629 final boolean suspended =
8630 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8631 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8632 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8633 // state. This is because the network could have been suspended before connecting,
8634 // or it could be disconnecting while being suspended, and in both these cases
8635 // the state should not be overridden. Note that the only detailed state that
8636 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8637 // worry about multiple different substates of CONNECTED.
8638 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8639 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08008640 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8641 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8642 // network agent is created, then goes to suspended, then goes out of suspended without
8643 // ever setting connected. Check if network agent is ever connected to update the state.
8644 newInfo.setDetailedState(nai.everConnected
8645 ? NetworkInfo.DetailedState.CONNECTED
8646 : NetworkInfo.DetailedState.CONNECTING,
8647 info.getReason(),
8648 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09008649 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008650 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09008651 return newInfo;
8652 }
8653
8654 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8655 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8656
Erik Kline99f301b2017-02-15 19:59:17 +09008657 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008658 NetworkInfo oldInfo = null;
8659 synchronized (networkAgent) {
8660 oldInfo = networkAgent.networkInfo;
8661 networkAgent.networkInfo = newInfo;
8662 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008663
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008664 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008665 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8666 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008667 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07008668
Robin Leea8c0b6e2016-05-01 23:00:00 +01008669 if (!networkAgent.created
8670 && (state == NetworkInfo.State.CONNECTED
8671 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008672
8673 // A network that has just connected has zero requests and is thus a foreground network.
8674 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8675
Luke Huangfdd11f82019-04-09 18:41:49 +08008676 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09008677 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008678 // Initialize the network's capabilities to their starting values according to the
8679 // underlying networks. This ensures that the capabilities are correct before
8680 // anything happens to the network.
8681 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09008682 }
Paul Jensen74940202014-08-04 12:21:19 -04008683 networkAgent.created = true;
Chiachang Wang3f6cc072021-03-24 18:39:17 +08008684 networkAgent.onNetworkCreated();
Robin Leea8c0b6e2016-05-01 23:00:00 +01008685 }
8686
8687 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
8688 networkAgent.everConnected = true;
8689
lucaslin45e639b2019-04-03 17:09:28 +08008690 // NetworkCapabilities need to be set before sending the private DNS config to
8691 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09008692 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
8693
Erik Kline9a62f012018-03-21 07:18:33 -07008694 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08008695 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
8696 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008697
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008698 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
8699 // command must be sent after updating LinkProperties to maximize chances of
8700 // NetworkMonitor seeing the correct LinkProperties when starting.
8701 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008702 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09008703 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008704 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09008705 networkAgent.networkMonitor().notifyNetworkConnected(
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008706 new LinkProperties(networkAgent.linkProperties,
8707 true /* parcelSensitiveFields */),
8708 networkAgent.networkCapabilities);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09008709 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008710
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008711 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
8712 // be communicated to a particular NetworkAgent depends only on the network's immutable,
8713 // capabilities, so it only needs to be done once on initial connect, not every time the
8714 // network's capabilities change. Note that we do this before rematching the network,
8715 // so we could decide to tear it down immediately afterwards. That's fine though - on
8716 // disconnection NetworkAgents should stop any signal strength monitoring they have been
8717 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09008718 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008719
junyulai0ac374f2020-12-14 18:41:52 +08008720 // Before first rematching networks, put an inactivity timer without any request, this
8721 // allows {@code updateInactivityState} to update the state accordingly and prevent
8722 // tearing down for any {@code unneeded} evaluation in this period.
8723 // Note that the timer will not be rescheduled since the expiry time is
8724 // fixed after connection regardless of the network satisfying other requests or not.
8725 // But it will be removed as soon as the network satisfies a request for the first time.
8726 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
8727 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08008728 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008729
Paul Jensen05e85ee2014-09-11 11:00:39 -04008730 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008731 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008732
8733 // This has to happen after matching the requests, because callbacks are just requests.
8734 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008735 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008736 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04008737 if (networkAgent.isVPN()) {
Chalard Jeanb2a49912018-01-16 18:43:05 +09008738 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04008739 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09008740 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00008741 if (networkAgent.isVPN()) {
8742 // As the active or bound network changes for apps, broadcast the default proxy, as
8743 // apps may need to update their proxy data. This is called after disconnecting from
8744 // VPN to make sure we do not broadcast the old proxy data.
8745 // TODO(b/122649188): send the broadcast only to VPN users.
8746 mProxyTracker.sendProxyBroadcast();
8747 }
Yintang Gu5014b522019-06-18 14:24:32 +08008748 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
8749 state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008750 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008751 }
8752 }
8753
Chalard Jean28018572020-12-21 18:36:52 +09008754 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09008755 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
8756 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008757 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07008758 }
8759
Erik Kline99f301b2017-02-15 19:59:17 +09008760 // Notify only this one new request of the current state. Transfer all the
8761 // current state by calling NetworkCapabilities and LinkProperties callbacks
8762 // so that callers can be guaranteed to have as close to atomicity in state
8763 // transfer as can be supported by this current API.
8764 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07008765 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09008766 if (nri.mPendingIntent != null) {
8767 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
8768 // Attempt no subsequent state pushes where intents are involved.
8769 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008770 }
Erik Kline99f301b2017-02-15 19:59:17 +09008771
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008772 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08008773 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008774 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
8775 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
8776 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08008777 }
8778
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008779 // Notify the requests on this NAI that the network is now lingered.
8780 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08008781 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008782 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
8783 }
8784
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008785 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
8786 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
8787 return vpnBlocked
8788 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
8789 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
8790 }
8791
8792 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
8793 if (blockedReasons == BLOCKED_REASON_NONE) {
8794 mUidBlockedReasons.delete(uid);
8795 } else {
8796 mUidBlockedReasons.put(uid, blockedReasons);
8797 }
8798 }
8799
junyulaif2c67e42018-08-07 19:50:45 +08008800 /**
8801 * Notify of the blocked state apps with a registered callback matching a given NAI.
8802 *
8803 * Unlike other callbacks, blocked status is different between each individual uid. So for
8804 * any given nai, all requests need to be considered according to the uid who filed it.
8805 *
8806 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008807 * @param oldMetered True if the previous network capabilities were metered.
8808 * @param newMetered True if the current network capabilities are metered.
8809 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
8810 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08008811 */
8812 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00008813 boolean newMetered, List<UidRange> oldBlockedUidRanges,
8814 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08008815
8816 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8817 NetworkRequest nr = nai.requestAt(i);
8818 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008819
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008820 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8821 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
8822 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008823 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008824 : oldVpnBlocked;
8825
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008826 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
8827 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
8828 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08008829 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008830 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08008831 }
8832 }
8833 }
8834
8835 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00008836 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08008837 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00008838 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08008839 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008840 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008841 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08008842 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008843 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00008844
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008845 final int oldBlockedState = getBlockedState(
8846 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
8847 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
8848 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08008849 continue;
junyulaif2c67e42018-08-07 19:50:45 +08008850 }
junyulaif2c67e42018-08-07 19:50:45 +08008851 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8852 NetworkRequest nr = nai.requestAt(i);
8853 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008854 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008855 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8856 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08008857 }
8858 }
8859 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008860 }
8861
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008862 @VisibleForTesting
8863 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09008864 // The NetworkInfo we actually send out has no bearing on the real
8865 // state of affairs. For example, if the default connection is mobile,
8866 // and a request for HIPRI has just gone away, we need to pretend that
8867 // HIPRI has just disconnected. So we need to set the type to HIPRI and
8868 // the state to DISCONNECTED, even though the network is of type MOBILE
8869 // and is still connected.
8870 NetworkInfo info = new NetworkInfo(nai.networkInfo);
8871 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09008872 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008873 if (state != DetailedState.DISCONNECTED) {
8874 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09008875 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008876 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008877 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07008878 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
8879 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
8880 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
8881 if (info.isFailover()) {
8882 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
8883 nai.networkInfo.setFailover(false);
8884 }
8885 if (info.getReason() != null) {
8886 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
8887 }
8888 if (info.getExtraInfo() != null) {
8889 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
8890 }
8891 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09008892 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08008893 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07008894 if (newDefaultAgent != null) {
8895 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
8896 newDefaultAgent.networkInfo);
8897 } else {
8898 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
8899 }
8900 }
8901 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
8902 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09008903 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008904 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09008905 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008906 }
8907 }
8908 }
8909
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008910 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008911 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008912 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09008913 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09008914 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008915 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
8916 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008917 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8918 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008919 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008920 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008921 } else {
8922 sendPendingIntentForRequest(nri, networkAgent, notifyType);
8923 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008924 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008925 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07008926
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008927 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
8928 notifyNetworkCallbacks(networkAgent, notifyType, 0);
8929 }
8930
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008931 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09008932 * Returns the list of all interfaces that could be used by network traffic that does not
8933 * explicitly specify a network. This includes the default network, but also all VPNs that are
8934 * currently connected.
8935 *
8936 * Must be called on the handler thread.
8937 */
junyulaie7c7d2a2021-01-26 15:29:15 +08008938 @NonNull
8939 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08008940 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08008941 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08008942 final Set<Integer> activeNetIds = new ArraySet<>();
8943 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8944 if (nri.isBeingSatisfied()) {
8945 activeNetIds.add(nri.getSatisfier().network().netId);
8946 }
8947 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008948 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattis2516da32021-01-31 17:06:19 -08008949 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09008950 defaultNetworks.add(nai.network);
8951 }
8952 }
junyulaie7c7d2a2021-01-26 15:29:15 +08008953 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09008954 }
8955
8956 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09008957 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
8958 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008959 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08008960 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08008961 ensureRunningOnConnectivityServiceThread();
8962 String activeIface = null;
8963 LinkProperties activeLinkProperties = getActiveLinkProperties();
8964 if (activeLinkProperties != null) {
8965 activeIface = activeLinkProperties.getInterfaceName();
8966 }
Benedict Wong9308cd32019-06-12 17:46:31 +00008967
junyulai2050bed2021-01-23 09:46:34 +08008968 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008969 try {
junyulaide41fc22021-01-22 22:46:01 +08008970 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
junyulai69114da2021-03-05 14:46:25 +08008971 for (final NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaide41fc22021-01-22 22:46:01 +08008972 snapshots.add(snapshot);
8973 }
junyulaie7c7d2a2021-01-26 15:29:15 +08008974 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
8975 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008976 } catch (Exception ignored) {
8977 }
8978 }
8979
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07008980 @Override
Udam Sainicd645462016-01-04 12:16:14 -08008981 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08008982 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008983 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008984 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01008985
8986 if (!TextUtils.isEmpty(settingUrl)) {
8987 return settingUrl;
8988 }
8989
8990 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08008991 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01008992 if (!TextUtils.isEmpty(settingUrl)) {
8993 return settingUrl;
8994 }
8995
8996 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08008997 }
8998
8999 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009000 public void startNattKeepalive(Network network, int intervalSeconds,
9001 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009002 enforceKeepalivePermission();
9003 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009004 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai070f9ff2019-01-16 20:23:34 +08009005 intervalSeconds, cb,
junyulai011b1f12019-01-03 18:50:15 +08009006 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009007 }
9008
9009 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009010 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009011 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulaid05a1922019-01-15 11:32:44 +08009012 String dstAddr) {
Josh Gao461a1222020-06-16 15:58:11 -07009013 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009014 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009015 mKeepaliveTracker.startNattKeepalive(
9016 getNetworkAgentInfoForNetwork(network), fd, resourceId,
9017 intervalSeconds, cb,
9018 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
9019 } finally {
9020 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9021 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009022 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9023 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009024 }
9025 }
junyulaid05a1922019-01-15 11:32:44 +08009026 }
9027
9028 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009029 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009030 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009031 try {
9032 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08009033 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009034 mKeepaliveTracker.startTcpKeepalive(
9035 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
9036 } finally {
9037 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9038 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009039 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9040 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009041 }
9042 }
junyulai0835a1e2019-01-08 20:04:33 +08009043 }
9044
9045 @Override
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009046 public void stopKeepalive(Network network, int slot) {
9047 mHandler.sendMessage(mHandler.obtainMessage(
junyulai011b1f12019-01-03 18:50:15 +08009048 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009049 }
9050
9051 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07009052 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08009053 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07009054
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009055 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08009056 final long token = Binder.clearCallingIdentity();
9057 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009058 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
9059 UserHandle.getUserHandleForUid(uid))) {
9060 return;
9061 }
9062
Heemin Seogdb8489d2019-06-12 09:21:44 -07009063 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
9064 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009065
9066 // Turn airplane mode off
9067 setAirplaneMode(false);
9068
9069 // restore private DNS settings to default mode (opportunistic)
9070 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
9071 UserHandle.getUserHandleForUid(uid))) {
9072 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
9073 PRIVATE_DNS_MODE_OPPORTUNISTIC);
9074 }
9075
9076 Settings.Global.putString(mContext.getContentResolver(),
9077 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08009078 } finally {
9079 Binder.restoreCallingIdentity(token);
9080 }
Stuart Scottd5463642015-04-02 18:00:02 -07009081 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04009082
Ricky Wai7097cc92018-01-23 04:09:45 +00009083 @Override
9084 public byte[] getNetworkWatchlistConfigHash() {
9085 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
9086 if (nwm == null) {
9087 loge("Unable to get NetworkWatchlistManager");
9088 return null;
9089 }
9090 // Redirect it to network watchlist service to access watchlist file and calculate hash.
9091 return nwm.getWatchlistConfigHash();
9092 }
9093
Hugo Benichibe0c7652016-05-31 16:28:06 +09009094 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09009095 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08009096 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09009097 }
Hugo Benichif4210292017-04-21 15:07:12 +09009098
9099 private static boolean toBool(int encodedBoolean) {
9100 return encodedBoolean != 0; // Only 0 means false.
9101 }
9102
9103 private static int encodeBool(boolean b) {
9104 return b ? 1 : 0;
9105 }
mswest4632928412018-03-12 10:34:34 -07009106
9107 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009108 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
9109 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
9110 @NonNull String[] args) {
9111 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
9112 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07009113 }
9114
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009115 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07009116 @Override
9117 public int onCommand(String cmd) {
9118 if (cmd == null) {
9119 return handleDefaultCommands(cmd);
9120 }
9121 final PrintWriter pw = getOutPrintWriter();
9122 try {
9123 switch (cmd) {
9124 case "airplane-mode":
9125 final String action = getNextArg();
9126 if ("enable".equals(action)) {
9127 setAirplaneMode(true);
9128 return 0;
9129 } else if ("disable".equals(action)) {
9130 setAirplaneMode(false);
9131 return 0;
9132 } else if (action == null) {
9133 final ContentResolver cr = mContext.getContentResolver();
9134 final int enabled = Settings.Global.getInt(cr,
9135 Settings.Global.AIRPLANE_MODE_ON);
9136 pw.println(enabled == 0 ? "disabled" : "enabled");
9137 return 0;
9138 } else {
9139 onHelp();
9140 return -1;
9141 }
9142 default:
9143 return handleDefaultCommands(cmd);
9144 }
9145 } catch (Exception e) {
9146 pw.println(e);
9147 }
9148 return -1;
9149 }
9150
9151 @Override
9152 public void onHelp() {
9153 PrintWriter pw = getOutPrintWriter();
9154 pw.println("Connectivity service commands:");
9155 pw.println(" help");
9156 pw.println(" Print this help text.");
9157 pw.println(" airplane-mode [enable|disable]");
9158 pw.println(" Turn airplane mode on or off.");
9159 pw.println(" airplane-mode");
9160 pw.println(" Get airplane mode.");
9161 }
9162 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009163
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09009164 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009165 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
9166 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
9167 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +08009168 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009169 }
9170
9171 /**
9172 * @param connectionInfo the connection to resolve.
9173 * @return {@code uid} if the connection is found and the app has permission to observe it
9174 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
9175 * connection is not found.
9176 */
9177 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009178 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
9179 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
9180 }
9181
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09009182 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009183 connectionInfo.local, connectionInfo.remote);
9184
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009185 if (uid == INVALID_UID) return uid; // Not found.
9186
9187 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
9188 // VPN, if any, that applies to the UID that owns the connection.
9189 if (checkNetworkStackPermission()) return uid;
9190
9191 final NetworkAgentInfo vpn = getVpnForUid(uid);
9192 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09009193 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009194 return INVALID_UID;
9195 }
9196
9197 return uid;
9198 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +00009199
Benedict Wong493e04b2018-11-09 14:45:34 -08009200 /**
9201 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
9202 *
9203 * <p>The TestNetworkService must be run in the system server due to TUN creation.
9204 */
9205 @Override
9206 public IBinder startOrGetTestNetworkService() {
9207 synchronized (mTNSLock) {
9208 TestNetworkService.enforceTestNetworkPermissions(mContext);
9209
9210 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +08009211 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -08009212 }
9213
9214 return mTNS;
9215 }
9216 }
Cody Kestingd199a9d2019-12-17 12:55:28 -08009217
Cody Kesting73708bf2019-12-18 10:57:50 -08009218 /**
9219 * Handler used for managing all Connectivity Diagnostics related functions.
9220 *
9221 * @see android.net.ConnectivityDiagnosticsManager
9222 *
9223 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9224 */
9225 @VisibleForTesting
9226 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009227 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9228
Cody Kesting73708bf2019-12-18 10:57:50 -08009229 /**
9230 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9231 * android.net.ConnectivityDiagnosticsManager}.
9232 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9233 * NetworkRequestInfo to be registered
9234 */
9235 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9236
9237 /**
9238 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9239 * android.net.ConnectivityDiagnosticsManager}.
9240 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9241 * arg1 = the uid of the caller
9242 */
9243 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9244
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009245 /**
9246 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
9247 * after processing {@link #EVENT_NETWORK_TESTED} events.
9248 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9249 * NetworkMonitor.
9250 * data = PersistableBundle of extras passed from NetworkMonitor.
9251 *
9252 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
9253 */
9254 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
9255
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009256 /**
9257 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9258 * been detected on the network.
9259 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9260 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9261 * arg2 = NetID.
9262 * data = PersistableBundle of extras passed from NetworkMonitor.
9263 */
9264 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9265
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009266 /**
9267 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9268 * the platform. This event will invoke {@link
9269 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9270 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -07009271 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009272 */
9273 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9274
Cody Kesting73708bf2019-12-18 10:57:50 -08009275 private ConnectivityDiagnosticsHandler(Looper looper) {
9276 super(looper);
9277 }
9278
9279 @Override
9280 public void handleMessage(Message msg) {
9281 switch (msg.what) {
9282 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9283 handleRegisterConnectivityDiagnosticsCallback(
9284 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9285 break;
9286 }
9287 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9288 handleUnregisterConnectivityDiagnosticsCallback(
9289 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9290 break;
9291 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009292 case EVENT_NETWORK_TESTED: {
9293 final ConnectivityReportEvent reportEvent =
9294 (ConnectivityReportEvent) msg.obj;
9295
Aaron Huang959d3642021-01-21 15:47:41 +08009296 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009297 break;
9298 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009299 case EVENT_DATA_STALL_SUSPECTED: {
9300 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +08009301 final Pair<Long, PersistableBundle> arg =
9302 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009303 if (nai == null) break;
9304
Aaron Huang959d3642021-01-21 15:47:41 +08009305 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009306 break;
9307 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009308 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -07009309 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009310 break;
9311 }
9312 default: {
9313 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9314 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009315 }
9316 }
9317 }
9318
9319 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9320 @VisibleForTesting
9321 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9322 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9323 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009324 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009325
9326 @VisibleForTesting
9327 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009328 @NonNull IConnectivityDiagnosticsCallback cb,
9329 @NonNull NetworkRequestInfo nri,
9330 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009331 mCb = cb;
9332 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009333 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009334 }
9335
9336 @Override
9337 public void binderDied() {
9338 log("ConnectivityDiagnosticsCallback IBinder died.");
9339 unregisterConnectivityDiagnosticsCallback(mCb);
9340 }
9341 }
9342
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009343 /**
9344 * Class used for sending information from {@link
9345 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9346 */
9347 private static class NetworkTestedResults {
9348 private final int mNetId;
9349 private final int mTestResult;
9350 private final long mTimestampMillis;
9351 @Nullable private final String mRedirectUrl;
9352
9353 private NetworkTestedResults(
9354 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9355 mNetId = netId;
9356 mTestResult = testResult;
9357 mTimestampMillis = timestampMillis;
9358 mRedirectUrl = redirectUrl;
9359 }
9360 }
9361
9362 /**
9363 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9364 * ConnectivityDiagnosticsHandler}.
9365 */
9366 private static class ConnectivityReportEvent {
9367 private final long mTimestampMillis;
9368 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +08009369 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009370
Aaron Huang959d3642021-01-21 15:47:41 +08009371 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9372 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009373 mTimestampMillis = timestampMillis;
9374 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +08009375 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009376 }
9377 }
9378
Cody Kestingf1120be2020-08-03 18:01:40 -07009379 /**
9380 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
9381 * ConnectivityDiagnosticsHandler}.
9382 */
9383 private static class ReportedNetworkConnectivityInfo {
9384 public final boolean hasConnectivity;
9385 public final boolean isNetworkRevalidating;
9386 public final int reporterUid;
9387 @NonNull public final NetworkAgentInfo nai;
9388
9389 private ReportedNetworkConnectivityInfo(
9390 boolean hasConnectivity,
9391 boolean isNetworkRevalidating,
9392 int reporterUid,
9393 @NonNull NetworkAgentInfo nai) {
9394 this.hasConnectivity = hasConnectivity;
9395 this.isNetworkRevalidating = isNetworkRevalidating;
9396 this.reporterUid = reporterUid;
9397 this.nai = nai;
9398 }
9399 }
9400
Cody Kesting73708bf2019-12-18 10:57:50 -08009401 private void handleRegisterConnectivityDiagnosticsCallback(
9402 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9403 ensureRunningOnConnectivityServiceThread();
9404
9405 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -08009406 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009407 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9408
James Mattis64b8b0f2020-11-24 17:40:49 -08009409 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9410 // confusing for these networks to change when an NRI is satisfied in another layer.
9411 if (nri.isMultilayerRequest()) {
9412 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9413 + "network requests.");
9414 }
9415
Cody Kesting73708bf2019-12-18 10:57:50 -08009416 // This means that the client registered the same callback multiple times. Do
9417 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -08009418 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009419 if (VDBG) log("Diagnostics callback is already registered");
9420
9421 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9422 // incremented when the NetworkRequestInfo is created as part of
9423 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009424 nri.decrementRequestCount();
Cody Kesting73708bf2019-12-18 10:57:50 -08009425 return;
9426 }
9427
Cody Kesting31f1ff62020-03-05 10:46:02 -08009428 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -08009429
9430 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -08009431 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009432 } catch (RemoteException e) {
9433 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -08009434 return;
9435 }
9436
9437 // Once registered, provide ConnectivityReports for matching Networks
9438 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9439 synchronized (mNetworkForNetId) {
9440 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9441 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -08009442 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9443 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -08009444 matchingNetworks.add(nai);
9445 }
9446 }
9447 }
9448 for (final NetworkAgentInfo nai : matchingNetworks) {
9449 final ConnectivityReport report = nai.getConnectivityReport();
9450 if (report == null) {
9451 continue;
9452 }
9453 if (!checkConnectivityDiagnosticsPermissions(
9454 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9455 continue;
9456 }
9457
9458 try {
9459 cb.onConnectivityReportAvailable(report);
9460 } catch (RemoteException e) {
9461 // Exception while sending the ConnectivityReport. Move on to the next network.
9462 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009463 }
9464 }
9465
9466 private void handleUnregisterConnectivityDiagnosticsCallback(
9467 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9468 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009469 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009470
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009471 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9472 mConnectivityDiagnosticsCallbacks.remove(iCb);
9473 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009474 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9475 return;
9476 }
9477
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009478 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -08009479
Cody Kesting70fa2b22020-12-02 12:16:56 -08009480 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9481 // (if the Binder died)
9482 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9483 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -08009484 return;
9485 }
9486
Cody Kesting46cb1672020-03-04 13:35:20 -08009487 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9488 // incremented when the NetworkRequestInfo is created as part of
9489 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009490 nri.decrementRequestCount();
Cody Kesting46cb1672020-03-04 13:35:20 -08009491
Cody Kesting31f1ff62020-03-05 10:46:02 -08009492 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009493 }
9494
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009495 private void handleNetworkTestedWithExtras(
9496 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9497 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -08009498 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009499 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009500 final ConnectivityReport report =
9501 new ConnectivityReport(
9502 reportEvent.mNai.network,
9503 reportEvent.mTimestampMillis,
9504 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009505 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009506 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -08009507 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -07009508
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009509 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009510 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009511 for (final IConnectivityDiagnosticsCallback cb : results) {
9512 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -08009513 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009514 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -07009515 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009516 }
9517 }
9518 }
9519
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009520 private void handleDataStallSuspected(
9521 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9522 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -08009523 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009524 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009525 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -08009526 new DataStallReport(
9527 nai.network,
9528 timestampMillis,
9529 detectionMethod,
9530 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009531 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -08009532 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009533 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009534 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009535 for (final IConnectivityDiagnosticsCallback cb : results) {
9536 try {
9537 cb.onDataStallSuspected(report);
9538 } catch (RemoteException ex) {
9539 loge("Error invoking onDataStallSuspected", ex);
9540 }
9541 }
9542 }
9543
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009544 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -07009545 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
9546 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
9547 final ConnectivityReport cachedReport = nai.getConnectivityReport();
9548
9549 // If the Network is being re-validated as a result of this call to
9550 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
9551 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009552 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009553 getMatchingPermissionedCallbacks(
9554 nai,
9555 reportedNetworkConnectivityInfo.isNetworkRevalidating
9556 ? Process.INVALID_UID
9557 : reportedNetworkConnectivityInfo.reporterUid);
9558
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009559 for (final IConnectivityDiagnosticsCallback cb : results) {
9560 try {
Cody Kestingf1120be2020-08-03 18:01:40 -07009561 cb.onNetworkConnectivityReported(
9562 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009563 } catch (RemoteException ex) {
9564 loge("Error invoking onNetworkConnectivityReported", ex);
9565 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009566
9567 // If the Network isn't re-validating, also provide the cached report. If there is no
9568 // cached report, the Network is still being validated and a report will be sent once
9569 // validation is complete. Note that networks which never undergo validation will still
9570 // have a cached ConnectivityReport with RESULT_SKIPPED.
9571 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
9572 try {
9573 cb.onConnectivityReportAvailable(cachedReport);
9574 } catch (RemoteException ex) {
9575 loge("Error invoking onConnectivityReportAvailable", ex);
9576 }
9577 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009578 }
9579 }
9580
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009581 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +09009582 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9583 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009584 sanitized.setUids(null);
9585 sanitized.setAdministratorUids(new int[0]);
9586 sanitized.setOwnerUid(Process.INVALID_UID);
9587 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -08009588 }
9589
Cody Kestingf1120be2020-08-03 18:01:40 -07009590 /**
9591 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
9592 *
9593 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
9594 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009595 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -07009596 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009597 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009598 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009599 mConnectivityDiagnosticsCallbacks.entrySet()) {
9600 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9601 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -07009602
James Mattis64b8b0f2020-11-24 17:40:49 -08009603 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -07009604 if (!nai.satisfies(nri.mRequests.get(0))) {
9605 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009606 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009607
9608 // UID for this callback must either be:
9609 // - INVALID_UID (which sends callbacks to all UIDs), or
9610 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
9611 // notified as a result)
9612 if (uid != Process.INVALID_UID && uid != nri.mUid) {
9613 continue;
9614 }
9615
9616 if (!checkConnectivityDiagnosticsPermissions(
9617 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9618 continue;
9619 }
9620
9621 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009622 }
9623 return results;
9624 }
9625
Cody Kesting7474f672021-05-11 14:22:40 -07009626 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
9627 @NonNull NetworkAgentInfo nai) {
9628 // TODO(b/188483916): replace with a transport-agnostic location-aware check
9629 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
9630 }
9631
Cody Kesting160ef392021-05-05 13:17:22 -07009632 private boolean hasLocationPermission(String packageName, int uid) {
9633 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9634 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9635 // call in a try-catch.
9636 try {
9637 if (!mLocationPermissionChecker.checkLocationPermission(
9638 packageName, null /* featureId */, uid, null /* message */)) {
9639 return false;
9640 }
9641 } catch (SecurityException e) {
9642 return false;
9643 }
9644
9645 return true;
9646 }
9647
9648 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
9649 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +09009650 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -07009651 && virtual.networkCapabilities.getOwnerUid() == uid
9652 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
9653 return true;
9654 }
9655 }
9656
9657 return false;
9658 }
9659
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009660 @VisibleForTesting
9661 boolean checkConnectivityDiagnosticsPermissions(
9662 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9663 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9664 return true;
9665 }
9666
Cody Kesting160ef392021-05-05 13:17:22 -07009667 // Administrator UIDs also contains the Owner UID
9668 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
9669 if (!CollectionUtils.contains(administratorUids, callbackUid)
9670 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009671 return false;
9672 }
9673
Cody Kesting7474f672021-05-11 14:22:40 -07009674 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
9675 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009676 }
9677
Cody Kestingd199a9d2019-12-17 12:55:28 -08009678 @Override
9679 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009680 @NonNull IConnectivityDiagnosticsCallback callback,
9681 @NonNull NetworkRequest request,
9682 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -07009683 Objects.requireNonNull(callback, "callback must not be null");
9684 Objects.requireNonNull(request, "request must not be null");
9685 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
9686
Cody Kesting73708bf2019-12-18 10:57:50 -08009687 if (request.legacyType != TYPE_NONE) {
9688 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
9689 + " Please use NetworkCapabilities instead.");
9690 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009691 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -08009692 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009693
9694 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
9695 // and administrator uids to be safe.
9696 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08009697 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009698
9699 final NetworkRequest requestWithId =
9700 new NetworkRequest(
9701 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
9702
9703 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
9704 //
9705 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
9706 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
9707 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009708 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -08009709 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009710 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009711
9712 mConnectivityDiagnosticsHandler.sendMessage(
9713 mConnectivityDiagnosticsHandler.obtainMessage(
9714 ConnectivityDiagnosticsHandler
9715 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9716 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -08009717 }
9718
9719 @Override
9720 public void unregisterConnectivityDiagnosticsCallback(
9721 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +08009722 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -08009723 mConnectivityDiagnosticsHandler.sendMessage(
9724 mConnectivityDiagnosticsHandler.obtainMessage(
9725 ConnectivityDiagnosticsHandler
9726 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009727 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -08009728 0,
9729 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -08009730 }
Cody Kestingf53a0752020-04-15 12:33:28 -07009731
9732 @Override
9733 public void simulateDataStall(int detectionMethod, long timestampMillis,
9734 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -07009735 Objects.requireNonNull(network, "network must not be null");
9736 Objects.requireNonNull(extras, "extras must not be null");
9737
Cody Kestingf53a0752020-04-15 12:33:28 -07009738 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
9739 android.Manifest.permission.NETWORK_STACK);
9740 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
9741 if (!nc.hasTransport(TRANSPORT_TEST)) {
9742 throw new SecurityException("Data Stall simluation is only possible for test networks");
9743 }
9744
9745 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009746 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -07009747 throw new SecurityException("Data Stall simulation is only possible for network "
9748 + "creators");
9749 }
9750
Cody Kesting652e3ec2020-05-21 12:08:21 -07009751 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
9752 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
9753 // Data Stall information as a DataStallReportParcelable and passing to
9754 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
9755 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -07009756 final DataStallReportParcelable p = new DataStallReportParcelable();
9757 p.timestampMillis = timestampMillis;
9758 p.detectionMethod = detectionMethod;
9759
9760 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
9761 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
9762 }
9763 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
9764 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
9765 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
9766 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
9767 }
9768
Serik Beketayevec8ad212020-12-07 22:43:07 -08009769 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -07009770 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009771
lucaslin66f44212021-02-23 01:12:55 +08009772 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
9773 @Override
lucaslin87b58aa2021-02-25 15:10:29 +08009774 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +08009775 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +08009776 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +08009777 }
lucaslin37a16d92021-01-21 19:48:09 +08009778
9779 @Override
9780 public void onInterfaceLinkStateChanged(String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +08009781 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +08009782 nai.clatd.interfaceLinkStateChanged(iface, up);
9783 }
9784 }
9785
9786 @Override
9787 public void onInterfaceRemoved(String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +08009788 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +08009789 nai.clatd.interfaceRemoved(iface);
9790 }
lucaslin66f44212021-02-23 01:12:55 +08009791 }
9792 }
9793
lucaslin1a8b4c62021-01-21 02:02:55 +08009794 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
9795
9796 /**
9797 * Class used for updating network activity tracking with netd and notify network activity
9798 * changes.
9799 */
9800 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +08009801 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +08009802 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +08009803 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +08009804 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
9805 new RemoteCallbackList<>();
9806 // Indicate the current system default network activity is active or not.
9807 @GuardedBy("mActiveIdleTimers")
9808 private boolean mNetworkActive;
9809 @GuardedBy("mActiveIdleTimers")
9810 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
9811 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +08009812
lucaslin1193a5d2021-01-21 02:04:15 +08009813 private class IdleTimerParams {
9814 public final int timeout;
9815 public final int transportType;
9816
9817 IdleTimerParams(int timeout, int transport) {
9818 this.timeout = timeout;
9819 this.transportType = transport;
9820 }
9821 }
9822
9823 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +08009824 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +08009825 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +08009826 mNetd = netd;
9827 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +08009828 }
9829
lucaslin66f44212021-02-23 01:12:55 +08009830 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
9831 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
9832 synchronized (mActiveIdleTimers) {
9833 mNetworkActive = active;
9834 // If there are no idle timers, it means that system is not monitoring
9835 // activity, so the system default network for those default network
9836 // unspecified apps is always considered active.
9837 //
9838 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
9839 // any network activity change event. Whenever this event is received,
9840 // the mActiveIdleTimers should be always not empty. The legacy behavior
9841 // is no-op. Remove to refer to mNetworkActive only.
9842 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
9843 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
9844 }
9845 }
9846 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009847
lucaslin1193a5d2021-01-21 02:04:15 +08009848 // The network activity should only be updated from ConnectivityService handler thread
9849 // when mActiveIdleTimers lock is held.
9850 @GuardedBy("mActiveIdleTimers")
9851 private void reportNetworkActive() {
9852 final int length = mNetworkActivityListeners.beginBroadcast();
9853 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
9854 try {
9855 for (int i = 0; i < length; i++) {
9856 try {
9857 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
9858 } catch (RemoteException | RuntimeException e) {
9859 loge("Fail to send network activie to listener " + e);
9860 }
9861 }
9862 } finally {
9863 mNetworkActivityListeners.finishBroadcast();
9864 }
9865 }
9866
9867 @GuardedBy("mActiveIdleTimers")
9868 public void handleReportNetworkActivity() {
9869 synchronized (mActiveIdleTimers) {
9870 reportNetworkActive();
9871 }
9872 }
9873
lucaslin1a8b4c62021-01-21 02:02:55 +08009874 // This is deprecated and only to support legacy use cases.
9875 private int transportTypeToLegacyType(int type) {
9876 switch (type) {
9877 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009878 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +08009879 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009880 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +08009881 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009882 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +08009883 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009884 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +08009885 default:
9886 loge("Unexpected transport in transportTypeToLegacyType: " + type);
9887 }
9888 return ConnectivityManager.TYPE_NONE;
9889 }
9890
9891 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
9892 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
9893 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
9894 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
9895 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
9896 final long ident = Binder.clearCallingIdentity();
9897 try {
9898 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
9899 RECEIVE_DATA_ACTIVITY_CHANGE,
9900 null /* resultReceiver */,
9901 null /* scheduler */,
9902 0 /* initialCode */,
9903 null /* initialData */,
9904 null /* initialExtra */);
9905 } finally {
9906 Binder.restoreCallingIdentity(ident);
9907 }
9908 }
9909
9910 /**
9911 * Setup data activity tracking for the given network.
9912 *
9913 * Every {@code setupDataActivityTracking} should be paired with a
9914 * {@link #removeDataActivityTracking} for cleanup.
9915 */
9916 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
9917 final String iface = networkAgent.linkProperties.getInterfaceName();
9918
9919 final int timeout;
9920 final int type;
9921
9922 if (networkAgent.networkCapabilities.hasTransport(
9923 NetworkCapabilities.TRANSPORT_CELLULAR)) {
9924 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009925 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +08009926 10);
9927 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9928 } else if (networkAgent.networkCapabilities.hasTransport(
9929 NetworkCapabilities.TRANSPORT_WIFI)) {
9930 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009931 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +08009932 15);
9933 type = NetworkCapabilities.TRANSPORT_WIFI;
9934 } else {
9935 return; // do not track any other networks
9936 }
9937
lucaslinb961efc2021-01-21 02:03:17 +08009938 updateRadioPowerState(true /* isActive */, type);
9939
lucaslin1a8b4c62021-01-21 02:02:55 +08009940 if (timeout > 0 && iface != null) {
9941 try {
lucaslin1193a5d2021-01-21 02:04:15 +08009942 synchronized (mActiveIdleTimers) {
9943 // Networks start up.
9944 mNetworkActive = true;
9945 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
9946 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
9947 reportNetworkActive();
9948 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009949 } catch (Exception e) {
9950 // You shall not crash!
9951 loge("Exception in setupDataActivityTracking " + e);
9952 }
9953 }
9954 }
9955
9956 /**
9957 * Remove data activity tracking when network disconnects.
9958 */
9959 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
9960 final String iface = networkAgent.linkProperties.getInterfaceName();
9961 final NetworkCapabilities caps = networkAgent.networkCapabilities;
9962
lucaslinb961efc2021-01-21 02:03:17 +08009963 if (iface == null) return;
9964
9965 final int type;
9966 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
9967 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9968 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
9969 type = NetworkCapabilities.TRANSPORT_WIFI;
9970 } else {
9971 return; // do not track any other networks
9972 }
9973
9974 try {
9975 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +08009976 synchronized (mActiveIdleTimers) {
9977 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
9978 // The call fails silently if no idle timer setup for this interface
9979 mNetd.idletimerRemoveInterface(iface, params.timeout,
9980 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +08009981 }
lucaslinb961efc2021-01-21 02:03:17 +08009982 } catch (Exception e) {
9983 // You shall not crash!
9984 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +08009985 }
9986 }
9987
9988 /**
9989 * Update data activity tracking when network state is updated.
9990 */
9991 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
9992 NetworkAgentInfo oldNetwork) {
9993 if (newNetwork != null) {
9994 setupDataActivityTracking(newNetwork);
9995 }
9996 if (oldNetwork != null) {
9997 removeDataActivityTracking(oldNetwork);
9998 }
9999 }
lucaslinb961efc2021-01-21 02:03:17 +080010000
10001 private void updateRadioPowerState(boolean isActive, int transportType) {
10002 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
10003 switch (transportType) {
10004 case NetworkCapabilities.TRANSPORT_CELLULAR:
10005 bs.reportMobileRadioPowerState(isActive, NO_UID);
10006 break;
10007 case NetworkCapabilities.TRANSPORT_WIFI:
10008 bs.reportWifiRadioPowerState(isActive, NO_UID);
10009 break;
10010 default:
10011 logw("Untracked transport type:" + transportType);
10012 }
10013 }
lucaslin1193a5d2021-01-21 02:04:15 +080010014
10015 public boolean isDefaultNetworkActive() {
10016 synchronized (mActiveIdleTimers) {
10017 // If there are no idle timers, it means that system is not monitoring activity,
10018 // so the default network is always considered active.
10019 //
10020 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
10021 // tracking is disabled (negative idle timer value configured), or no active default
10022 // network. In the latter case, this reports active but it should report inactive.
10023 return mNetworkActive || mActiveIdleTimers.isEmpty();
10024 }
10025 }
10026
10027 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
10028 mNetworkActivityListeners.register(l);
10029 }
10030
10031 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
10032 mNetworkActivityListeners.unregister(l);
10033 }
lucaslin012f7a12021-01-21 02:04:35 +080010034
10035 public void dump(IndentingPrintWriter pw) {
10036 synchronized (mActiveIdleTimers) {
10037 pw.print("mNetworkActive="); pw.println(mNetworkActive);
10038 pw.println("Idle timers:");
10039 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
10040 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
10041 final IdleTimerParams params = ent.getValue();
10042 pw.print(" timeout="); pw.print(params.timeout);
10043 pw.print(" type="); pw.println(params.transportType);
10044 }
10045 }
10046 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010047 }
James Mattis47db0582021-01-01 14:13:35 -080010048
Daniel Brightf9e945b2020-06-15 16:10:01 -070010049 /**
10050 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
10051 *
10052 * @param socketInfo the socket information
10053 * @param callback the callback to register
10054 */
10055 @Override
10056 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
10057 @NonNull final IQosCallback callback) {
10058 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
10059 if (nai == null || nai.networkCapabilities == null) {
10060 try {
10061 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
10062 } catch (final RemoteException ex) {
10063 loge("registerQosCallbackInternal: RemoteException", ex);
10064 }
10065 return;
10066 }
10067 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
10068 }
10069
10070 /**
10071 * Register a {@link IQosCallback} with base {@link QosFilter}.
10072 *
10073 * @param filter the filter to register
10074 * @param callback the callback to register
10075 * @param nai the agent information related to the filter's network
10076 */
10077 @VisibleForTesting
10078 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
10079 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
10080 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
10081 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
10082
10083 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
10084 enforceConnectivityRestrictedNetworksPermission();
10085 }
10086 mQosCallbackTracker.registerCallback(callback, filter, nai);
10087 }
10088
10089 /**
10090 * Unregisters the given callback.
10091 *
10092 * @param callback the callback to unregister
10093 */
10094 @Override
10095 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010096 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010097 mQosCallbackTracker.unregisterCallback(callback);
10098 }
James Mattis47db0582021-01-01 14:13:35 -080010099
James Mattis45d81842021-01-10 14:24:24 -080010100 /**
Chalard Jeanfa45a682021-02-25 17:23:40 +090010101 * Request that a user profile is put by default on a network matching a given preference.
10102 *
10103 * See the documentation for the individual preferences for a description of the supported
10104 * behaviors.
10105 *
10106 * @param profile the profile concerned.
10107 * @param preference the preference for this profile, as one of the PROFILE_NETWORK_PREFERENCE_*
10108 * constants.
10109 * @param listener an optional listener to listen for completion of the operation.
10110 */
10111 @Override
10112 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
10113 @ConnectivityManager.ProfileNetworkPreference final int preference,
10114 @Nullable final IOnCompleteListener listener) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010115 Objects.requireNonNull(profile);
10116 PermissionUtils.enforceNetworkStackPermission(mContext);
10117 if (DBG) {
10118 log("setProfileNetworkPreference " + profile + " to " + preference);
10119 }
10120 if (profile.getIdentifier() < 0) {
10121 throw new IllegalArgumentException("Must explicitly specify a user handle ("
10122 + "UserHandle.CURRENT not supported)");
10123 }
Chalard Jeana21ef9b2021-04-02 19:24:44 +090010124 final UserManager um = mContext.getSystemService(UserManager.class);
10125 if (!um.isManagedProfile(profile.getIdentifier())) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010126 throw new IllegalArgumentException("Profile must be a managed profile");
10127 }
paulhuaa0743d2021-05-26 21:56:03 +080010128
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010129 final NetworkCapabilities nc;
10130 switch (preference) {
10131 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
10132 nc = null;
10133 break;
10134 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
10135 final UidRange uids = UidRange.createForUser(profile);
10136 nc = createDefaultNetworkCapabilitiesForUidRange(uids);
10137 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
10138 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10139 break;
10140 default:
10141 throw new IllegalArgumentException(
10142 "Invalid preference in setProfileNetworkPreference");
10143 }
10144 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
10145 new Pair<>(new ProfileNetworkPreferences.Preference(profile, nc), listener)));
10146 }
10147
10148 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
10149 @Nullable final NetworkCapabilities nc) {
10150 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
10151 ensureRequestableCapabilities(nc);
10152 }
10153
10154 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
10155 @NonNull final ProfileNetworkPreferences prefs) {
10156 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
10157 for (final ProfileNetworkPreferences.Preference pref : prefs.preferences) {
10158 // The NRI for a user should be comprised of two layers:
10159 // - The request for the capabilities
10160 // - The request for the default network, for fallback. Create an image of it to
10161 // have the correct UIDs in it (also a request can only be part of one NRI, because
10162 // of lookups in 1:1 associations like mNetworkRequests).
10163 // Note that denying a fallback can be implemented simply by not adding the second
10164 // request.
10165 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
10166 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
James Mattisa117e282021-04-20 17:26:30 -070010167 nrs.add(createDefaultInternetRequestForTransport(
10168 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010169 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080010170 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080010171 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010172 result.add(nri);
10173 }
10174 return result;
10175 }
10176
10177 private void handleSetProfileNetworkPreference(
10178 @NonNull final ProfileNetworkPreferences.Preference preference,
10179 @Nullable final IOnCompleteListener listener) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010180 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
10181
10182 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
paulhu74128522021-09-28 02:29:03 +000010183 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
10184 addPerAppDefaultNetworkRequests(
10185 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010186 // Finally, rematch.
10187 rematchAllNetworksAndRequests();
10188
10189 if (null != listener) {
10190 try {
10191 listener.onComplete();
10192 } catch (RemoteException e) {
10193 loge("Listener for setProfileNetworkPreference has died");
10194 }
10195 }
10196 }
10197
paulhu51f77dc2021-06-07 02:34:20 +000010198 @VisibleForTesting
10199 @NonNull
10200 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
10201 @NonNull final Set<Integer> uids) {
10202 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10203 if (uids.size() == 0) {
10204 // Should not create NetworkRequestInfo if no preferences. Without uid range in
10205 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
10206 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
10207 return nris;
10208 }
10209
10210 final List<NetworkRequest> requests = new ArrayList<>();
10211 // The NRI should be comprised of two layers:
10212 // - The request for the mobile network preferred.
10213 // - The request for the default network, for fallback.
10214 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090010215 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000010216 requests.add(createDefaultInternetRequestForTransport(
10217 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10218 final Set<UidRange> ranges = new ArraySet<>();
10219 for (final int uid : uids) {
10220 ranges.add(new UidRange(uid, uid));
10221 }
10222 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080010223 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080010224 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000010225 return nris;
10226 }
10227
10228 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000010229 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000010230 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
10231 addPerAppDefaultNetworkRequests(
10232 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000010233 // Finally, rematch.
10234 rematchAllNetworksAndRequests();
10235 }
10236
James Mattis45d81842021-01-10 14:24:24 -080010237 private void enforceAutomotiveDevice() {
10238 final boolean isAutomotiveDevice =
10239 mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
10240 if (!isAutomotiveDevice) {
10241 throw new UnsupportedOperationException(
10242 "setOemNetworkPreference() is only available on automotive devices.");
10243 }
10244 }
10245
10246 /**
10247 * Used by automotive devices to set the network preferences used to direct traffic at an
10248 * application level as per the given OemNetworkPreferences. An example use-case would be an
10249 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
10250 * vehicle via a particular network.
10251 *
10252 * Calling this will overwrite the existing preference.
10253 *
James Mattisda32cfe2021-01-26 16:23:52 -080010254 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090010255 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080010256 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080010257 */
James Mattis47db0582021-01-01 14:13:35 -080010258 @Override
James Mattis45d81842021-01-10 14:24:24 -080010259 public void setOemNetworkPreference(
10260 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010261 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080010262
James Mattisfa270db2021-05-31 17:11:10 -070010263 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10264 // Only bypass the permission/device checks if this is a valid test request.
10265 if (isValidTestOemNetworkPreference(preference)) {
10266 enforceManageTestNetworksPermission();
10267 } else {
10268 enforceAutomotiveDevice();
10269 enforceOemNetworkPreferencesPermission();
10270 validateOemNetworkPreferences(preference);
10271 }
James Mattis45d81842021-01-10 14:24:24 -080010272
James Mattis45d81842021-01-10 14:24:24 -080010273 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
10274 new Pair<>(preference, listener)));
10275 }
10276
James Mattisfa270db2021-05-31 17:11:10 -070010277 /**
10278 * Check the validity of an OEM network preference to be used for testing purposes.
10279 * @param preference the preference to validate
10280 * @return true if this is a valid OEM network preference test request.
10281 */
10282 private boolean isValidTestOemNetworkPreference(
10283 @NonNull final OemNetworkPreferences preference) {
10284 // Allow for clearing of an existing OemNetworkPreference used for testing.
10285 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
10286 // changes after this check is complete. This is an unlikely scenario as calling of this API
10287 // is controlled by the OEM therefore the added complexity is not worth adding given those
10288 // circumstances. That said, it is an edge case to be aware of hence this comment.
10289 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
10290 && isTestOemNetworkPreference(mOemNetworkPreferences);
10291 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
10292 }
10293
10294 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
10295 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
10296 return prefMap.size() == 1
10297 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
10298 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
10299 }
10300
James Mattis45d81842021-01-10 14:24:24 -080010301 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
10302 for (@OemNetworkPreferences.OemNetworkPreference final int pref
10303 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070010304 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
10305 throw new IllegalArgumentException(
10306 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
10307 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080010308 }
10309 }
10310 }
10311
10312 private void handleSetOemNetworkPreference(
10313 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010314 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080010315 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10316 if (DBG) {
10317 log("set OEM network preferences :" + preference.toString());
10318 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010319
James Mattiscb1e0362021-04-06 17:07:42 -070010320 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000010321 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
10322 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
10323 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080010324 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080010325
10326 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010327 try {
10328 listener.onComplete();
10329 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080010330 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010331 }
James Mattis45d81842021-01-10 14:24:24 -080010332 }
10333 }
10334
paulhu74128522021-09-28 02:29:03 +000010335 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080010336 // Skip the requests which are set by other network preference. Because the uid range rules
10337 // should stay in netd.
10338 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080010339 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080010340 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080010341 }
10342
James Mattis3ce3d3c2021-02-09 18:18:28 -080010343 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
10344 ensureRunningOnConnectivityServiceThread();
10345 mDefaultNetworkRequests.addAll(nris);
10346 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
10347 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080010348 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000010349 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
10350 nrisToRegister.addAll(
10351 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
10352 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010353 }
10354
10355 /**
10356 * All current requests that are tracking the default network need to be assessed as to whether
10357 * or not the current set of per-application default requests will be changing their default
10358 * network. If so, those requests will need to be updated so that they will send callbacks for
10359 * default network changes at the appropriate time. Additionally, those requests tracking the
10360 * default that were previously updated by this flow will need to be reassessed.
10361 * @return the nris which will need to be updated.
10362 */
10363 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
10364 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
10365 // Get the distinct nris to check since for multilayer requests, it is possible to have the
10366 // same nri in the map's values for each of its NetworkRequest objects.
10367 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080010368 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010369 // Include this nri if it is currently being tracked.
10370 if (isPerAppTrackedNri(nri)) {
10371 defaultCallbackRequests.add(nri);
10372 continue;
10373 }
10374 // We only track callbacks for requests tracking the default.
10375 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
10376 continue;
10377 }
10378 // Include this nri if it will be tracked by the new per-app default requests.
10379 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010380 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080010381 if (isNriGoingToBeTracked) {
10382 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080010383 }
10384 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080010385 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080010386 }
10387
James Mattis3ce3d3c2021-02-09 18:18:28 -080010388 /**
10389 * Create nris for those network requests that are currently tracking the default network that
10390 * are being controlled by a per-application default.
10391 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
10392 * foundation when creating the nri. Important items include the calling uid's original
10393 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
10394 * requests are assumed to have already been validated as needing to be updated.
10395 * @return the Set of nris to use when registering network requests.
10396 */
10397 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
10398 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
10399 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
10400 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
10401 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010402 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010403
Chalard Jean9473c982021-07-29 20:03:04 +090010404 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080010405 if (trackingNri == mDefaultRequest) {
10406 callbackRequestsToRegister.add(new NetworkRequestInfo(
10407 callbackRequest,
10408 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
10409 continue;
10410 }
10411
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010412 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010413 callbackRequestsToRegister.add(new NetworkRequestInfo(
10414 callbackRequest,
10415 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010416 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090010417 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080010418 }
10419 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080010420 }
10421
Chalard Jean17215832021-03-01 14:06:28 +090010422 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
10423 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090010424 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010425 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090010426 }
10427 }
10428
James Mattis45d81842021-01-10 14:24:24 -080010429 /**
10430 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
10431 */
10432 @VisibleForTesting
10433 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010434 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080010435 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010436 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080010437 final SparseArray<Set<Integer>> uids =
10438 createUidsFromOemNetworkPreferences(preference);
10439 for (int i = 0; i < uids.size(); i++) {
10440 final int key = uids.keyAt(i);
10441 final Set<Integer> value = uids.valueAt(i);
10442 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
10443 // No need to add an nri without any requests.
10444 if (0 == nri.mRequests.size()) {
10445 continue;
10446 }
10447 nris.add(nri);
10448 }
10449
10450 return nris;
10451 }
10452
10453 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
10454 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070010455 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080010456 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080010457 final List<UserHandle> users =
10458 mContext.getSystemService(UserManager.class).getUserHandles(true);
10459 if (null == users || users.size() == 0) {
10460 if (VDBG || DDBG) {
10461 log("No users currently available for setting the OEM network preference.");
10462 }
James Mattisb6b6a432021-06-01 22:30:36 -070010463 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080010464 }
James Mattis45d81842021-01-10 14:24:24 -080010465 for (final Map.Entry<String, Integer> entry :
10466 preference.getNetworkPreferences().entrySet()) {
10467 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070010468 // Add the rules for all users as this policy is device wide.
10469 for (final UserHandle user : users) {
10470 try {
10471 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
10472 if (!prefToUids.contains(pref)) {
10473 prefToUids.put(pref, new ArraySet<>());
10474 }
10475 prefToUids.get(pref).add(uid);
10476 } catch (PackageManager.NameNotFoundException e) {
10477 // Although this may seem like an error scenario, it is ok that uninstalled
10478 // packages are sent on a network preference as the system will watch for
10479 // package installations associated with this network preference and update
10480 // accordingly. This is done to minimize race conditions on app install.
10481 continue;
James Mattis45d81842021-01-10 14:24:24 -080010482 }
James Mattis45d81842021-01-10 14:24:24 -080010483 }
10484 }
James Mattisb6b6a432021-06-01 22:30:36 -070010485 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080010486 }
10487
10488 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10489 @OemNetworkPreferences.OemNetworkPreference final int preference,
10490 @NonNull final Set<Integer> uids) {
10491 final List<NetworkRequest> requests = new ArrayList<>();
10492 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10493 switch (preference) {
10494 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10495 requests.add(createUnmeteredNetworkRequest());
10496 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070010497 requests.add(createDefaultInternetRequestForTransport(
10498 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080010499 break;
10500 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10501 requests.add(createUnmeteredNetworkRequest());
10502 requests.add(createOemPaidNetworkRequest());
10503 break;
10504 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10505 requests.add(createOemPaidNetworkRequest());
10506 break;
10507 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10508 requests.add(createOemPrivateNetworkRequest());
10509 break;
James Mattisfa270db2021-05-31 17:11:10 -070010510 case OEM_NETWORK_PREFERENCE_TEST:
10511 requests.add(createUnmeteredNetworkRequest());
10512 requests.add(createTestNetworkRequest());
10513 requests.add(createDefaultRequest());
10514 break;
10515 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
10516 requests.add(createTestNetworkRequest());
10517 break;
James Mattis45d81842021-01-10 14:24:24 -080010518 default:
10519 // This should never happen.
10520 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10521 + " called with invalid preference of " + preference);
10522 }
10523
James Mattisfa270db2021-05-31 17:11:10 -070010524 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090010525 for (final int uid : uids) {
10526 ranges.add(new UidRange(uid, uid));
10527 }
10528 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080010529 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080010530 }
10531
10532 private NetworkRequest createUnmeteredNetworkRequest() {
10533 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10534 .addCapability(NET_CAPABILITY_NOT_METERED)
10535 .addCapability(NET_CAPABILITY_VALIDATED);
10536 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10537 }
10538
10539 private NetworkRequest createOemPaidNetworkRequest() {
10540 // NET_CAPABILITY_OEM_PAID is a restricted capability.
10541 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10542 .addCapability(NET_CAPABILITY_OEM_PAID)
10543 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10544 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10545 }
10546
10547 private NetworkRequest createOemPrivateNetworkRequest() {
10548 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
10549 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10550 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
10551 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10552 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10553 }
10554
10555 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070010556 final NetworkCapabilities netcap = new NetworkCapabilities();
10557 netcap.addCapability(NET_CAPABILITY_INTERNET);
10558 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
10559 return netcap;
10560 }
10561
10562 private NetworkRequest createTestNetworkRequest() {
10563 final NetworkCapabilities netcap = new NetworkCapabilities();
10564 netcap.clearAll();
10565 netcap.addTransportType(TRANSPORT_TEST);
10566 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080010567 }
James Mattis47db0582021-01-01 14:13:35 -080010568 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070010569}