blob: 6944ca9883f9e84f99345973e5976bec1a050cf1 [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;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080076import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
77import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080078import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
79import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
80import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090081import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090082import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060083import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070084import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080085import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090086import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070087import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
88import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +090089import static android.net.shared.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070090import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080091import static android.os.Process.VPN_UID;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +090092import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070093import static android.system.OsConstants.IPPROTO_TCP;
94import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey07e19362017-10-27 17:22:59 -060095
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +090096import static com.android.net.module.util.DeviceConfigUtils.TETHERING_MODULE_NAME;
97
Cody Kesting83bb5fa2020-01-05 14:06:39 -080098import static java.util.Map.Entry;
99
Chalard Jean5b639762020-03-09 21:25:37 +0900100import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000101import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800102import android.annotation.Nullable;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800103import android.annotation.TargetApi;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800104import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800105import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700106import android.app.PendingIntent;
junyulaie7c7d2a2021-01-26 15:29:15 +0800107import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700108import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800109import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800110import android.content.ContentResolver;
111import android.content.Context;
112import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700113import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800114import android.content.pm.PackageManager;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700115import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900116import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900117import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700118import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800119import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800120import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800121import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900122import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800123import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900124import android.net.ConnectivityManager.RestrictBackgroundStatus;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900125import android.net.ConnectivityResources;
paulhu90a7a512021-03-17 17:19:09 +0800126import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900127import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800128import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700129import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900130import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800131import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800132import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800133import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800134import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800135import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900136import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900137import android.net.INetworkMonitor;
138import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900139import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900140import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700141import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800142import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900143import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900144import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900145import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800146import android.net.LinkProperties;
Charles He9369e612017-05-15 17:07:18 +0100147import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800148import android.net.NativeNetworkConfig;
149import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800150import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700151import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700152import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900153import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700154import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800155import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700156import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900157import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900158import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000159import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900160import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700161import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900162import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700163import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900164import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700165import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800166import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900167import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700168import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000169import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800170import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900171import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800172import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400173import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700174import android.net.QosCallbackException;
175import android.net.QosFilter;
176import android.net.QosSocketFilter;
177import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700178import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800179import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800180import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800181import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900182import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400183import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800184import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800185import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400186import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800187import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900188import android.net.VpnTransportInfo;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900189import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900190import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800191import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900192import android.net.networkstack.ModuleNetworkStackClient;
193import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900194import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800195import android.net.resolv.aidl.DnsHealthEventParcel;
196import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
197import android.net.resolv.aidl.Nat64PrefixEventParcel;
198import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900199import android.net.shared.PrivateDnsConfig;
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900200import android.net.util.MultinetworkPolicyTracker;
lucaslinb961efc2021-01-21 02:03:17 +0800201import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800202import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800203import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700204import android.os.Bundle;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800205import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700206import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700207import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800208import android.os.Looper;
209import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700210import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700211import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900212import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800213import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700214import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700215import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800216import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700217import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900218import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900219import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700220import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700221import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400222import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800223import android.provider.Settings;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900224import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700225import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700226import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700227import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800228import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900229import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000230import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600231import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900232import android.util.Pair;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700233import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700234import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800235
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900236import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400237import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400238import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700239import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900240import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800241import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900242import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800243import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900244import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900245import com.android.net.module.util.DeviceConfigUtils;
Chalard Jean79162542020-08-19 16:07:22 +0900246import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
247import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900248import com.android.net.module.util.LocationPermissionChecker;
lifrade6c2a2021-03-04 14:08:08 +0800249import com.android.net.module.util.NetworkCapabilitiesUtils;
paulhudf23d662021-01-25 18:53:17 +0800250import com.android.net.module.util.PermissionUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000251import com.android.net.module.util.netlink.InetDiagMessage;
Chalard Jean7284daa2019-05-30 14:58:29 +0900252import com.android.server.connectivity.AutodestructReference;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800253import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900254import com.android.server.connectivity.ConnectivityFlags;
Erik Kline32120082017-12-13 19:40:49 +0900255import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500256import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700257import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900258import com.android.server.connectivity.FullScore;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900259import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100260import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700261import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700262import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600263import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900264import com.android.server.connectivity.NetworkNotificationManager;
265import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900266import com.android.server.connectivity.NetworkOffer;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900267import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700268import com.android.server.connectivity.PermissionMonitor;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800269import com.android.server.connectivity.ProfileNetworkPreferenceList;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900270import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700271import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800272import com.android.server.connectivity.UidRangeUtils;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600273
Josh Gao461a1222020-06-16 15:58:11 -0700274import libcore.io.IoUtils;
275
The Android Open Source Project28527d22009-03-03 19:31:44 -0800276import java.io.FileDescriptor;
277import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900278import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700279import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700280import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900281import java.net.InetSocketAddress;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700282import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700283import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700284import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700285import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800286import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900287import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800288import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700289import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700290import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700291import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700292import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900293import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700294import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900295import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600296import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900297import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600298import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900299import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800300
301/**
302 * @hide
303 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800304public class ConnectivityService extends IConnectivityManager.Stub
305 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900306 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800307
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900308 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900309 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900310 private static final String NETWORK_ARG = "networks";
311 private static final String REQUEST_ARG = "requests";
Erik Klined364a242017-05-12 16:52:48 +0900312
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900313 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900314 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
315 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800316
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900317 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700318
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100319 /**
320 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
321 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800322 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100323 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
324 * (preferably via runtime resource overlays).
325 */
326 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
327 "http://connectivitycheck.gstatic.com/generate_204";
328
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700329 // TODO: create better separation between radio types and network types
330
Robert Greenwalt2034b912009-08-12 16:08:25 -0700331 // how long to wait before switching back to a radio's default network
332 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
333 // system property that can override the above value
334 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
335 "android.telephony.apn-restore";
336
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900337 // How long to wait before putting up a "This network doesn't have an Internet connection,
338 // connect anyway?" dialog after the user selects a network that doesn't validate.
339 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
340
junyulai0ac374f2020-12-14 18:41:52 +0800341 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900342 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
343 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800344 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700345
346 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900347 @VisibleForTesting
348 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700349
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900350 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700351 @VisibleForTesting
352 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900353
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900354 @VisibleForTesting
355 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800356 @VisibleForTesting
357 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900358 // True if the cell radio of the device is capable of time-sharing.
359 @VisibleForTesting
360 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900361
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800362 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800363 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800364 private final int mReleasePendingIntentDelayMs;
365
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900366 private MockableSystemProperties mSystemProperties;
367
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000368 @VisibleForTesting
369 protected final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700370
Chalard Jean9473c982021-07-29 20:03:04 +0900371 @VisibleForTesting
372 final PerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700373 @VisibleForTesting
374 final PerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700375
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900376 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700377
junyulaif2c67e42018-08-07 19:50:45 +0800378 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000379 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
380 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800381 */
Sudheer Shanka9967d462021-03-18 19:09:25 +0000382 private SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800383
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900384 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900385 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000386 // The Context is created for UserHandle.ALL.
387 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900388 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900389 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700390 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700391 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800392
Chenbo Feng15416292018-11-08 17:36:21 -0800393 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800394 protected IDnsResolver mDnsResolver;
395 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800396 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700397 private DscpPolicyTracker mDscpPolicyTracker = null;
junyulaie7c7d2a2021-01-26 15:29:15 +0800398 private NetworkStatsManager mStatsManager;
paulhu9a9f71b2020-12-29 18:15:13 +0800399 private NetworkPolicyManager mPolicyManager;
lucaslin66f44212021-02-23 01:12:55 +0800400 private final NetdCallback mNetdCallback;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800401 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700402
Benedict Wong493e04b2018-11-09 14:45:34 -0800403 /**
404 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
405 * instances.
406 */
407 @GuardedBy("mTNSLock")
408 private TestNetworkService mTNS;
409
410 private final Object mTNSLock = new Object();
411
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700412 private String mCurrentTcpBufferSizes;
413
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900414 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
lifraf3a3492021-03-10 13:58:14 +0800415 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900416
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500417 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400418 // Tear down networks that have no chance (e.g. even if validated) of becoming
419 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500420 // all networks have been rematched against all NetworkRequests.
421 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400422 // Don't reap networks. This should be passed when some networks have not yet been
423 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500424 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900425 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500426
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900427 private enum UnneededFor {
428 LINGER, // Determine whether this network is unneeded and should be lingered.
429 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
430 }
431
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700432 /**
paulhuaa0743d2021-05-26 21:56:03 +0800433 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800434 * should have priority. The order is passed to netd which will use it together
435 * with UID ranges to generate the corresponding IP rule. This serves to
436 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800437 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800438 * Order ints passed to netd must be in the 0~999 range. Larger values code for
paulhuaa0743d2021-05-26 21:56:03 +0800439 * a lower priority, {@see NativeUidRangeConfig}
paulhue9913722021-05-26 15:19:20 +0800440 *
paulhu48291862021-07-14 14:53:57 +0800441 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
442 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800443 */
paulhu48291862021-07-14 14:53:57 +0800444 // Used when sending to netd to code for "no order".
445 static final int PREFERENCE_ORDER_NONE = 0;
446 // Order for requests that don't code for a per-app preference. As it is
447 // out of the valid range, the corresponding order should be
448 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800449 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800450 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800451 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800452 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
453 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800454 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800455 static final int PREFERENCE_ORDER_OEM = 10;
456 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800457 // See {@link #setProfileNetworkPreference}.
458 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800459 static final int PREFERENCE_ORDER_PROFILE = 20;
460 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800461 // better scores are connected.
462 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800463 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800464 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900465 // Preference order that signifies the network shouldn't be set as a default network for
466 // the UIDs, only give them access to it. TODO : replace this with a boolean
467 // in NativeUidRangeConfig
468 @VisibleForTesting
469 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
470 // Bound for the lowest valid preference order.
471 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800472
473 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700474 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700475 * from one net to another. Clear happens when we get a new
476 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
477 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700478 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700479 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700480
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700481 /**
482 * used internally to reload global proxy settings
483 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700484 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700485
Robert Greenwalt34848c02011-03-25 13:09:25 -0700486 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400487 * PAC manager has received new port.
488 */
489 private static final int EVENT_PROXY_HAS_CHANGED = 16;
490
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700491 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900492 * used internally when registering NetworkProviders
493 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700494 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900495 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700496
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700497 /**
498 * used internally when registering NetworkAgents
499 * obj = Messenger
500 */
501 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
502
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700503 /**
504 * used to add a network request
505 * includes a NetworkRequestInfo
506 */
507 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
508
509 /**
510 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900511 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700512 * cancel it.
513 * includes a NetworkRequestInfo
514 */
515 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
516
517 /**
518 * used to add a network listener - no request
519 * includes a NetworkRequestInfo
520 */
521 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
522
523 /**
524 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400525 * arg1 = UID of caller
526 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700527 */
528 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
529
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700530 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900531 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700532 * obj = Messenger
533 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900534 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700535
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700536 /**
537 * used internally to expire a wakelock when transitioning
538 * from one net to another. Expire happens when we fail to find
539 * a new network (typically after 1 minute) -
540 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
541 * a replacement network.
542 */
543 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
544
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700545 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800546 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400547 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800548 */
549 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
550
551 /**
552 * used to remove a pending intent and its associated network request.
553 * arg1 = UID of caller
554 * obj = PendingIntent
555 */
556 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
557
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900558 /**
559 * used to specify whether a network should be used even if unvalidated.
560 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
561 * arg2 = whether to remember this choice in the future (1 or 0)
562 * obj = network
563 */
564 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
565
566 /**
567 * used to ask the user to confirm a connection to an unvalidated network.
568 * obj = network
569 */
570 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700571
Erik Kline05f2b402015-04-30 12:58:40 +0900572 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700573 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900574 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700575 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900576
Paul Jensenc8873fc2015-06-17 14:15:39 -0400577 /**
578 * used to add a network listener with a pending intent
579 * obj = NetworkRequestInfo
580 */
581 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
582
Hugo Benichid6b510a2017-04-06 17:22:18 +0900583 /**
584 * used to specify whether a network should not be penalized when it becomes unvalidated.
585 */
586 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
587
588 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700589 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900590 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700591 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900592
Erik Kline31b4a9e2018-01-11 21:07:29 +0900593 // Handle changes in Private DNS settings.
594 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
595
dalyk1720e542018-03-05 12:42:22 -0500596 // Handle private DNS validation status updates.
597 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
598
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800599 /**
600 * used to remove a network request, either a listener or a real request and call unavailable
601 * arg1 = UID of caller
602 * obj = NetworkRequest
603 */
604 private static final int EVENT_RELEASE_NETWORK_REQUEST_AND_CALL_UNAVAILABLE = 39;
605
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900606 /**
607 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
608 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800609 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
610 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
611 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900612 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900613 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900614
615 /**
616 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
617 * config was resolved.
618 * obj = PrivateDnsConfig
619 * arg2 = netid
620 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900621 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900622
623 /**
624 * Request ConnectivityService display provisioning notification.
625 * arg1 = Whether to make the notification visible.
626 * arg2 = NetID.
627 * obj = Intent to be launched when notification selected by user, null if !arg1.
628 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900629 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900630
631 /**
lucaslin2240ef62019-03-12 13:08:03 +0800632 * Used to specify whether a network should be used even if connectivity is partial.
633 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
634 * false)
635 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
636 * obj = network
637 */
lucaslin444d43a2020-02-20 16:56:59 +0800638 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800639
640 /**
lucasline117e2e2019-10-22 18:27:33 +0800641 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
642 * Both of the arguments are bitmasks, and the value of bits come from
643 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
644 * arg1 = A bitmask to describe which probes are completed.
645 * arg2 = A bitmask to describe which probes are successful.
646 */
lucaslin444d43a2020-02-20 16:56:59 +0800647 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800648
649 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900650 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
651 * arg1 = unused
652 * arg2 = netId
653 * obj = captive portal data
654 */
lucaslin444d43a2020-02-20 16:56:59 +0800655 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900656
657 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900658 * Used by setRequireVpnForUids.
659 * arg1 = whether the specified UID ranges are required to use a VPN.
660 * obj = Array of UidRange objects.
661 */
662 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
663
664 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900665 * Used internally when setting the default networks for OemNetworkPreferences.
666 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800667 */
668 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
669
670 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800671 * Used to indicate the system default network becomes active.
672 */
673 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
674
675 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900676 * Used internally when setting a network preference for a user profile.
677 * obj = Pair<ProfileNetworkPreference, Listener>
678 */
679 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
680
681 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000682 * Event to specify that reasons for why an uid is blocked changed.
683 * arg1 = uid
684 * arg2 = blockedReasons
685 */
686 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
687
688 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900689 * Event to register a new network offer
690 * obj = NetworkOffer
691 */
692 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
693
694 /**
695 * Event to unregister an existing network offer
696 * obj = INetworkOfferCallback
697 */
698 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
699
700 /**
paulhu51f77dc2021-06-07 02:34:20 +0000701 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
702 */
703 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
704
705 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800706 * Event to set temporary allow bad wifi within a limited time to override
707 * {@code config_networkAvoidBadWifi}.
708 */
709 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
710
711 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900712 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
713 * should be shown.
714 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900715 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900716
717 /**
718 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
719 * should be hidden.
720 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900721 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900722
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800723 /**
724 * The maximum alive time to allow bad wifi configuration for testing.
725 */
726 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
727
Hugo Benichi47011212017-03-30 10:46:05 +0900728 private static String eventName(int what) {
729 return sMagicDecoderRing.get(what, Integer.toString(what));
730 }
731
paulhua10d8212020-11-10 15:32:56 +0800732 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900733 final DnsResolverServiceManager dsm = context.getSystemService(
734 DnsResolverServiceManager.class);
735 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800736 }
737
Cody Kesting73708bf2019-12-18 10:57:50 -0800738 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900739 @VisibleForTesting
740 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700741 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700742 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700743 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700744 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800745 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
746 @VisibleForTesting
747 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
748
Erik Kline32120082017-12-13 19:40:49 +0900749 private final DnsManager mDnsManager;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900750 private final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700751
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400752 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800753 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400754
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700755 private PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800756 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700757
Chalard Jean5d70ba42018-06-07 16:44:04 +0900758 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
759 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000760 @VisibleForTesting
761 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400762
Erik Kline05f2b402015-04-30 12:58:40 +0900763 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700764
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400765 private UserManager mUserManager;
766
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700767 // the set of network types that can only be enabled by system/sig apps
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900768 private List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700769
Valentin Iftime9fa35092019-09-24 13:32:13 +0200770 private Set<String> mWolSupportedInterfaces;
771
Roshan Pius08c94fb2020-01-16 12:17:17 -0800772 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800773 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800774 private final AppOpsManager mAppOpsManager;
775
776 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400777
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900778 private KeepaliveTracker mKeepaliveTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700779 private QosCallbackTracker mQosCallbackTracker;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900780 private NetworkNotificationManager mNotifier;
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +0900781 private LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900782
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700783 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800784 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700785
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900786 // Sequence number for NetworkProvider IDs.
787 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
788 NetworkProvider.FIRST_PROVIDER_ID);
789
Erik Klineedf878b2015-07-09 18:24:03 +0900790 // NetworkRequest activity String log entries.
791 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
792 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
793
Hugo Benichid159fdd2016-07-11 11:05:12 +0900794 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900795 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900796 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
797
Hugo Benichi47011212017-03-30 10:46:05 +0900798 private static final int MAX_WAKELOCK_LOGS = 20;
799 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900800 private int mTotalWakelockAcquisitions = 0;
801 private int mTotalWakelockReleases = 0;
802 private long mTotalWakelockDurationMs = 0;
803 private long mMaxWakelockDurationMs = 0;
804 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900805
Hugo Benichi208c0102016-07-28 17:53:06 +0900806 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900807
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700808 @GuardedBy("mBandwidthRequests")
809 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
810
Erik Kline95ecfee2016-10-02 18:02:14 +0900811 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900812 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900813
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900814 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800815 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
816 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800817
Robert Greenwalt802c1102014-06-02 15:32:02 -0700818 /**
819 * Implements support for the legacy "one network per network type" model.
820 *
821 * We used to have a static array of NetworkStateTrackers, one for each
822 * network type, but that doesn't work any more now that we can have,
823 * for example, more that one wifi network. This class stores all the
824 * NetworkAgentInfo objects that support a given type, but the legacy
825 * API will only see the first one.
826 *
827 * It serves two main purposes:
828 *
829 * 1. Provide information about "the network for a given type" (since this
830 * API only supports one).
831 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
832 * the first network for a given type changes, or if the default network
833 * changes.
834 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900835 @VisibleForTesting
836 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900837
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900838 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900839 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900840
Robert Greenwalt802c1102014-06-02 15:32:02 -0700841 /**
842 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
843 * Each list holds references to all NetworkAgentInfos that are used to
844 * satisfy requests for that network type.
845 *
846 * This array is built out at startup such that an unsupported network
847 * doesn't get an ArrayList instance, making this a tristate:
848 * unsupported, supported but not active and active.
849 *
850 * The actual lists are populated when we scan the network types that
851 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900852 *
853 * Threading model:
854 * - addSupportedType() is only called in the constructor
855 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
856 * They are therefore not thread-safe with respect to each other.
857 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
858 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900859 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900860 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700861 */
Hugo Benichi389633f2016-06-21 09:48:07 +0900862 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900863 @NonNull
864 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700865
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900866 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
867 // an entry have no timer (equivalent to -1). Lazily loaded.
868 @NonNull
869 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
870
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900871 LegacyTypeTracker(@NonNull ConnectivityService service) {
872 mService = service;
873 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700874 }
875
Chiachang Wang3bc52762021-11-25 14:17:57 +0800876 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
877 // addressed.
878 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900879 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
880 final PackageManager pm = ctx.getPackageManager();
881 if (pm.hasSystemFeature(FEATURE_WIFI)) {
882 addSupportedType(TYPE_WIFI);
883 }
884 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
885 addSupportedType(TYPE_WIFI_P2P);
886 }
887 if (tm.isDataCapable()) {
888 // Telephony does not have granular support for these types: they are either all
889 // supported, or none is supported
890 addSupportedType(TYPE_MOBILE);
891 addSupportedType(TYPE_MOBILE_MMS);
892 addSupportedType(TYPE_MOBILE_SUPL);
893 addSupportedType(TYPE_MOBILE_DUN);
894 addSupportedType(TYPE_MOBILE_HIPRI);
895 addSupportedType(TYPE_MOBILE_FOTA);
896 addSupportedType(TYPE_MOBILE_IMS);
897 addSupportedType(TYPE_MOBILE_CBS);
898 addSupportedType(TYPE_MOBILE_IA);
899 addSupportedType(TYPE_MOBILE_EMERGENCY);
900 }
901 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
902 addSupportedType(TYPE_BLUETOOTH);
903 }
904 if (pm.hasSystemFeature(FEATURE_WATCH)) {
905 // TYPE_PROXY is only used on Wear
906 addSupportedType(TYPE_PROXY);
907 }
908 // Ethernet is often not specified in the configs, although many devices can use it via
909 // USB host adapters. Add it as long as the ethernet service is here.
910 if (ctx.getSystemService(Context.ETHERNET_SERVICE) != null) {
911 addSupportedType(TYPE_ETHERNET);
912 }
913
914 // Always add TYPE_VPN as a supported type
915 addSupportedType(TYPE_VPN);
916 }
917
918 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700919 if (mTypeLists[type] != null) {
920 throw new IllegalStateException(
921 "legacy list for type " + type + "already initialized");
922 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900923 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -0700924 }
925
Robert Greenwalt802c1102014-06-02 15:32:02 -0700926 public boolean isTypeSupported(int type) {
927 return isNetworkTypeValid(type) && mTypeLists[type] != null;
928 }
929
930 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +0900931 synchronized (mTypeLists) {
932 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
933 return mTypeLists[type].get(0);
934 }
Robert Greenwalt802c1102014-06-02 15:32:02 -0700935 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900936 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700937 }
938
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900939 public int getRestoreTimerForType(int type) {
940 synchronized (mTypeLists) {
941 if (mRestoreTimers == null) {
942 mRestoreTimers = loadRestoreTimers();
943 }
944 return mRestoreTimers.getOrDefault(type, -1);
945 }
946 }
947
948 private ArrayMap<Integer, Integer> loadRestoreTimers() {
949 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900950 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900951 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
952 for (final String config : configs) {
953 final String[] splits = TextUtils.split(config, ",");
954 if (splits.length != 2) {
955 logwtf("Invalid restore timer token count: " + config);
956 continue;
957 }
958 try {
959 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
960 } catch (NumberFormatException e) {
961 logwtf("Invalid restore timer number format: " + config, e);
962 }
963 }
964 return ret;
965 }
966
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -0700967 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +0900968 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900969 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +0900970 log("Sending " + state
971 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +0900972 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900973 }
974 }
975
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900976 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
977 // network type, to preserve previous behaviour.
978 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
979 if (vpnNai != mService.getLegacyLockdownNai()) return;
980
981 if (vpnNai.declaredUnderlyingNetworks == null
982 || vpnNai.declaredUnderlyingNetworks.length != 1) {
983 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
984 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
985 return;
986 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +0900987 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900988 vpnNai.declaredUnderlyingNetworks[0]);
989 if (underlyingNai == null) return;
990
991 final int type = underlyingNai.networkInfo.getType();
992 final DetailedState state = DetailedState.CONNECTED;
993 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
994 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
995 }
996
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900997 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -0700998 public void add(int type, NetworkAgentInfo nai) {
999 if (!isTypeSupported(type)) {
1000 return; // Invalid network type.
1001 }
1002 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1003
1004 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1005 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001006 return;
1007 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001008 synchronized (mTypeLists) {
1009 list.add(nai);
1010 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001011
Chalard Jean5b409c72021-02-04 13:12:59 +09001012 // Send a broadcast if this is the first network of its type or if it's the default.
1013 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001014
1015 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1016 // to preserve previous behaviour.
1017 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001018 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001019 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1020 mService.sendLegacyNetworkBroadcast(nai, state, type);
1021 }
1022
1023 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1024 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001025 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001026 }
1027
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001028 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001029 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001030 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1031 if (list == null || list.isEmpty()) {
1032 return;
1033 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001034 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001035
Hugo Benichi389633f2016-06-21 09:48:07 +09001036 synchronized (mTypeLists) {
1037 if (!list.remove(nai)) {
1038 return;
1039 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001040 }
1041
Lorenzo Colitti49767722015-05-01 00:30:10 +09001042 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001043 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1044 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001045 }
1046
1047 if (!list.isEmpty() && wasFirstNetwork) {
1048 if (DBG) log("Other network available for type " + type +
1049 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001050 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001051 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001052 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001053 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001054 }
1055 }
1056
1057 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001058 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1059 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001060 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001061 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001062 }
1063 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001064
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001065 // send out another legacy broadcast - currently only used for suspend/unsuspend
1066 // toggle
1067 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001068 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001069 final DetailedState state = nai.networkInfo.getDetailedState();
1070 for (int type = 0; type < mTypeLists.length; type++) {
1071 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001072 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001073 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001074 if (isFirst || contains && isDefault) {
1075 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001076 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001077 }
1078 }
1079 }
1080
Robert Greenwalt94e22142014-07-30 16:31:24 -07001081 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001082 pw.println("mLegacyTypeTracker:");
1083 pw.increaseIndent();
1084 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001085 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001086 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001087 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001088 pw.println();
1089 pw.println("Current state:");
1090 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001091 synchronized (mTypeLists) {
1092 for (int type = 0; type < mTypeLists.length; type++) {
1093 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1094 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001095 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001096 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001097 }
1098 }
1099 pw.decreaseIndent();
1100 pw.decreaseIndent();
1101 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001102 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001103 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001104 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001105
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001106 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001107 /**
1108 * Helper class which parses out priority arguments and dumps sections according to their
1109 * priority. If priority arguments are omitted, function calls the legacy dump command.
1110 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001111 private class LocalPriorityDump {
1112 private static final String PRIORITY_ARG = "--dump-priority";
1113 private static final String PRIORITY_ARG_HIGH = "HIGH";
1114 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1115
1116 LocalPriorityDump() {}
1117
1118 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1119 doDump(fd, pw, new String[] {DIAG_ARG});
1120 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001121 }
1122
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001123 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1124 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001125 }
1126
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001127 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1128 if (args == null) {
1129 dumpNormal(fd, pw, args);
1130 return;
1131 }
1132
1133 String priority = null;
1134 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1135 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1136 argIndex++;
1137 priority = args[argIndex];
1138 }
1139 }
1140
1141 if (PRIORITY_ARG_HIGH.equals(priority)) {
1142 dumpHigh(fd, pw);
1143 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1144 dumpNormal(fd, pw, args);
1145 } else {
1146 // ConnectivityService publishes binder service using publishBinderService() with
1147 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001148 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1149 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001150 // TODO: Integrate into signal dump.
1151 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001152 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001153 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001154 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001155
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001156 /**
Daniel Brightf9e945b2020-06-15 16:10:01 -07001157 * Keeps track of the number of requests made under different uids.
1158 */
1159 public static class PerUidCounter {
1160 private final int mMaxCountPerUid;
1161
1162 // Map from UID to number of NetworkRequests that UID has filed.
James Mattis20a4a8b2021-03-28 17:41:09 -07001163 @VisibleForTesting
Daniel Brightf9e945b2020-06-15 16:10:01 -07001164 @GuardedBy("mUidToNetworkRequestCount")
James Mattis20a4a8b2021-03-28 17:41:09 -07001165 final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
Daniel Brightf9e945b2020-06-15 16:10:01 -07001166
1167 /**
1168 * Constructor
1169 *
1170 * @param maxCountPerUid the maximum count per uid allowed
1171 */
1172 public PerUidCounter(final int maxCountPerUid) {
1173 mMaxCountPerUid = maxCountPerUid;
1174 }
1175
1176 /**
1177 * Increments the request count of the given uid. Throws an exception if the number
1178 * of open requests for the uid exceeds the value of maxCounterPerUid which is the value
1179 * passed into the constructor. see: {@link #PerUidCounter(int)}.
1180 *
1181 * @throws ServiceSpecificException with
1182 * {@link ConnectivityManager.Errors.TOO_MANY_REQUESTS} if the number of requests for
1183 * the uid exceed the allowed number.
1184 *
1185 * @param uid the uid that the request was made under
1186 */
1187 public void incrementCountOrThrow(final int uid) {
1188 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001189 incrementCountOrThrow(uid, 1 /* numToIncrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001190 }
1191 }
1192
James Mattis20a4a8b2021-03-28 17:41:09 -07001193 private void incrementCountOrThrow(final int uid, final int numToIncrement) {
1194 final int newRequestCount =
1195 mUidToNetworkRequestCount.get(uid, 0) + numToIncrement;
Chalard Jean9473c982021-07-29 20:03:04 +09001196 if (newRequestCount >= mMaxCountPerUid
1197 // HACK : the system server is allowed to go over the request count limit
1198 // when it is creating requests on behalf of another app (but not itself,
1199 // so it can still detect its own request leaks). This only happens in the
1200 // per-app API flows in which case the old requests for that particular
1201 // UID will be removed soon.
1202 // TODO : instead of this hack, addPerAppDefaultNetworkRequests and other
1203 // users of transact() should unregister the requests to decrease the count
1204 // before they increase it again by creating a new NRI. Then remove the
1205 // transact() method.
1206 && (Process.myUid() == uid || Process.myUid() != Binder.getCallingUid())) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001207 throw new ServiceSpecificException(
Chalard Jean9473c982021-07-29 20:03:04 +09001208 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
1209 "Uid " + uid + " exceeded its allotted requests limit");
James Mattis20a4a8b2021-03-28 17:41:09 -07001210 }
1211 mUidToNetworkRequestCount.put(uid, newRequestCount);
1212 }
1213
Daniel Brightf9e945b2020-06-15 16:10:01 -07001214 /**
1215 * Decrements the request count of the given uid.
1216 *
1217 * @param uid the uid that the request was made under
1218 */
1219 public void decrementCount(final int uid) {
1220 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001221 decrementCount(uid, 1 /* numToDecrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001222 }
1223 }
James Mattis20a4a8b2021-03-28 17:41:09 -07001224
1225 private void decrementCount(final int uid, final int numToDecrement) {
1226 final int newRequestCount =
1227 mUidToNetworkRequestCount.get(uid, 0) - numToDecrement;
1228 if (newRequestCount < 0) {
1229 logwtf("BUG: too small request count " + newRequestCount + " for UID " + uid);
1230 } else if (newRequestCount == 0) {
1231 mUidToNetworkRequestCount.delete(uid);
1232 } else {
1233 mUidToNetworkRequestCount.put(uid, newRequestCount);
1234 }
1235 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07001236 }
1237
1238 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001239 * Dependencies of ConnectivityService, for injection in tests.
1240 */
1241 @VisibleForTesting
1242 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001243 public int getCallingUid() {
1244 return Binder.getCallingUid();
1245 }
1246
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001247 /**
1248 * Get system properties to use in ConnectivityService.
1249 */
1250 public MockableSystemProperties getSystemProperties() {
1251 return new MockableSystemProperties();
1252 }
1253
1254 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001255 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1256 */
1257 public ConnectivityResources getResources(@NonNull Context ctx) {
1258 return new ConnectivityResources(ctx);
1259 }
1260
1261 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001262 * Create a HandlerThread to use in ConnectivityService.
1263 */
1264 public HandlerThread makeHandlerThread() {
1265 return new HandlerThread("ConnectivityServiceThread");
1266 }
1267
1268 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001269 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001270 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001271 public NetworkStackClientBase getNetworkStack() {
1272 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001273 }
1274
1275 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001276 * @see ProxyTracker
1277 */
1278 public ProxyTracker makeProxyTracker(@NonNull Context context,
1279 @NonNull Handler connServiceHandler) {
1280 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1281 }
1282
1283 /**
1284 * @see NetIdManager
1285 */
1286 public NetIdManager makeNetIdManager() {
1287 return new NetIdManager();
1288 }
1289
1290 /**
1291 * @see NetworkUtils#queryUserAccess(int, int)
1292 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001293 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1294 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001295 }
1296
1297 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001298 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1299 * requires CAP_NET_ADMIN, which the unit tests do not have.
1300 */
1301 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1302 InetSocketAddress remote) {
1303 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1304 }
1305
1306 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001307 * @see MultinetworkPolicyTracker
1308 */
1309 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1310 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1311 return new MultinetworkPolicyTracker(c, h, r);
1312 }
1313
Aaron Huang330a4c02020-10-27 03:36:19 +08001314 /**
1315 * @see BatteryStatsManager
1316 */
1317 public void reportNetworkInterfaceForTransports(Context context, String iface,
1318 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001319 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001320 context.getSystemService(BatteryStatsManager.class);
1321 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1322 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001323
1324 public boolean getCellular464XlatEnabled() {
1325 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1326 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001327
1328 /**
1329 * @see PendingIntent#intentFilterEquals
1330 */
1331 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1332 return a.intentFilterEquals(b);
1333 }
1334
1335 /**
1336 * @see LocationPermissionChecker
1337 */
1338 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1339 return new LocationPermissionChecker(context);
1340 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001341
1342 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001343 * @see CarrierPrivilegeAuthenticator
1344 */
1345 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1346 @NonNull final Context context, @NonNull final TelephonyManager tm) {
1347 if (SdkLevel.isAtLeastT()) {
1348 return new CarrierPrivilegeAuthenticator(context, tm);
1349 } else {
1350 return null;
1351 }
1352 }
1353
1354 /**
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001355 * @see DeviceConfigUtils#isFeatureEnabled
1356 */
1357 public boolean isFeatureEnabled(Context context, String name, boolean defaultEnabled) {
1358 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, name,
1359 TETHERING_MODULE_NAME, defaultEnabled);
1360 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001361
1362 /**
1363 * Get the BpfNetMaps implementation to use in ConnectivityService.
1364 * @param netd
1365 * @return BpfNetMaps implementation.
1366 */
1367 public BpfNetMaps getBpfNetMaps(INetd netd) {
1368 return new BpfNetMaps(netd);
1369 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001370 }
1371
junyulaie7c7d2a2021-01-26 15:29:15 +08001372 public ConnectivityService(Context context) {
1373 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001374 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1375 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001376 }
1377
1378 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001379 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1380 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001381 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001382
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001383 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001384 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001385 mSystemProperties = mDeps.getSystemProperties();
1386 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001387 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001388 mResources = deps.getResources(mContext);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001389 mNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_UID);
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09001390 mSystemNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001391
Hugo Benichi208c0102016-07-28 17:53:06 +09001392 mMetricsLog = logger;
Chalard Jean96a4f4b2019-12-10 22:16:53 +09001393 mNetworkRanker = new NetworkRanker();
James Mattis45d81842021-01-10 14:24:24 -08001394 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1395 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001396 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001397 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001398 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001399 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1400 mDefaultNetworkRequests.add(mDefaultRequest);
1401 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001402
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001403 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001404 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001405
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001406 // The default WiFi request is a background request so that apps using WiFi are
1407 // migrated to a better network (typically ethernet) when one comes up, instead
1408 // of staying on WiFi forever.
1409 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1410 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1411
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001412 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1413 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1414 NetworkRequest.Type.BACKGROUND_REQUEST);
1415
Chalard Jean0702f982021-09-16 21:50:07 +09001416 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1417 // TODO: Consider making the timer customizable.
1418 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1419 mCellularRadioTimesharingCapable =
1420 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1421
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001422 mHandlerThread = mDeps.makeHandlerThread();
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001423 mHandlerThread.start();
1424 mHandler = new InternalHandler(mHandlerThread.getLooper());
1425 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001426 mConnectivityDiagnosticsHandler =
1427 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001428
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001429 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001430 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001431
junyulaie7c7d2a2021-01-26 15:29:15 +08001432 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001433 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001434 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001435 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001436
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001437 mNetd = netd;
Wayne Ma2fde98c2022-01-17 18:04:05 +08001438 mBpfNetMaps = mDeps.getBpfNetMaps(netd);
Wink Saville32506bc2013-06-29 21:10:57 -07001439 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001440 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001441 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001442 mCarrierPrivilegeAuthenticator =
1443 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001444
Sudheer Shanka9967d462021-03-18 19:09:25 +00001445 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001446 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1447 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001448 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001449
1450 final PowerManager powerManager = (PowerManager) context.getSystemService(
1451 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001452 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001453 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001454
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001455 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1456 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001457 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001458 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001459 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001460 mProtectedNetworks.add(p);
1461 } else {
1462 if (DBG) loge("Ignoring protectedNetwork " + p);
1463 }
1464 }
1465
soma, kawata29444ae2019-05-23 09:30:40 +09001466 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1467
Wayne Ma2fde98c2022-01-17 18:04:05 +08001468 mPermissionMonitor = new PermissionMonitor(mContext, mNetd, mBpfNetMaps);
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -07001469
James Mattis02220e22021-03-13 19:27:21 -08001470 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001471 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001472 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001473 final IntentFilter userIntentFilter = new IntentFilter();
1474 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1475 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1476 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1477 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001478
James Mattis02220e22021-03-13 19:27:21 -08001479 // Listen to package add/removes for netd
1480 final IntentFilter packageIntentFilter = new IntentFilter();
1481 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1482 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1483 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1484 packageIntentFilter.addDataScheme("package");
1485 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001486 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001487
lucaslind5c2d072021-02-20 18:59:47 +08001488 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001489
lucaslin66f44212021-02-23 01:12:55 +08001490 mNetdCallback = new NetdCallback();
1491 try {
1492 mNetd.registerUnsolicitedEventListener(mNetdCallback);
1493 } catch (RemoteException | ServiceSpecificException e) {
1494 loge("Error registering event listener :" + e);
1495 }
1496
Erik Kline05f2b402015-04-30 12:58:40 +09001497 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1498 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001499
junyulai7e06ad42019-03-04 22:45:36 +08001500 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001501 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001502 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001503
1504 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001505 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001506 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1507 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001508 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001509 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1510 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001511
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001512 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001513 mContext, mHandler, () -> updateAvoidBadWifi());
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001514 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001515
Chiachang Wangc1215d32020-10-20 15:38:58 +08001516 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001517 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001518
Chalard Jean28018572020-12-21 18:36:52 +09001519 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1520 // request that doesn't allow fallback to the default network. It should never be visible
1521 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1522 // arguments like the handler or the DnsResolver.
1523 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001524 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001525 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001526 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001527 new LinkProperties(), new NetworkCapabilities(),
1528 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001529 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1530 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001531
1532 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001533 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1534 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1535 // Even if it could, running on S would at least require mocking out the BPF map,
1536 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1537 // the bpf syscall. http://aosp/1907693
1538 if (SdkLevel.isAtLeastT()) {
1539 mDscpPolicyTracker = new DscpPolicyTracker();
1540 }
Tyler Wear72388212021-09-09 14:49:02 -07001541 } catch (ErrnoException e) {
1542 loge("Unable to create DscpPolicyTracker");
1543 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001544 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001545
Chalard Jean46adcf32018-04-18 20:18:38 +09001546 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001547 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1548 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001549 }
1550
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001551 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1552 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001553 final NetworkCapabilities netCap = new NetworkCapabilities();
1554 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001555 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001556 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001557 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001558 return netCap;
1559 }
1560
James Mattis45d81842021-01-10 14:24:24 -08001561 private NetworkRequest createDefaultRequest() {
1562 return createDefaultInternetRequestForTransport(
1563 TYPE_NONE, NetworkRequest.Type.REQUEST);
1564 }
1565
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001566 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001567 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001568 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001569 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001570 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001571 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001572 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001573 netCap.addTransportType(transportType);
1574 }
James Mattis45d81842021-01-10 14:24:24 -08001575 return createNetworkRequest(type, netCap);
1576 }
1577
1578 private NetworkRequest createNetworkRequest(
1579 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001580 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001581 }
1582
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001583 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1584 NetworkRequest.Type type) {
1585 final NetworkCapabilities netCap = new NetworkCapabilities();
1586 netCap.clearAll();
1587 netCap.addCapability(capability);
1588 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1589 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1590 }
1591
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001592 // Used only for testing.
1593 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001594 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001595 // changing ContentResolver to make registerContentObserver non-final).
1596 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1597 // by subclassing SettingsObserver.
1598 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001599 void updateAlwaysOnNetworks() {
1600 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001601 }
1602
Erik Kline9a62f012018-03-21 07:18:33 -07001603 // See FakeSettingsProvider comment above.
1604 @VisibleForTesting
1605 void updatePrivateDnsSettings() {
1606 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1607 }
1608
paulhu51f77dc2021-06-07 02:34:20 +00001609 @VisibleForTesting
1610 void updateMobileDataPreferredUids() {
1611 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1612 }
1613
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09001614 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, int id) {
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001615 final boolean enable = mContext.getResources().getBoolean(id);
1616 handleAlwaysOnNetworkRequest(networkRequest, enable);
1617 }
1618
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001619 private void handleAlwaysOnNetworkRequest(
1620 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001621 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001622 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001623 handleAlwaysOnNetworkRequest(networkRequest, enable);
1624 }
1625
1626 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001627 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001628 if (enable == isEnabled) {
1629 return; // Nothing to do.
1630 }
1631
1632 if (enable) {
1633 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001634 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001635 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001636 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001637 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001638 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1639 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001640 }
1641 }
1642
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001643 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001644 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1645 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1646 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1647 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001648 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1649 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001650 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001651 }
1652
paulhu51f77dc2021-06-07 02:34:20 +00001653 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001654 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001655 private void registerSettingsCallbacks() {
1656 // Watch for global HTTP proxy changes.
1657 mSettingsObserver.observe(
1658 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1659 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1660
1661 // Watch for whether or not to keep mobile data always on.
1662 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001663 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001664 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1665
1666 // Watch for whether or not to keep wifi always on.
1667 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001668 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001669 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001670
1671 // Watch for mobile data preferred uids changes.
1672 mSettingsObserver.observe(
1673 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1674 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001675 }
1676
Erik Kline31b4a9e2018-01-11 21:07:29 +09001677 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001678 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1679 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001680 }
1681 }
1682
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001683 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001684 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1685 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001686 return mNextNetworkRequestId++;
1687 }
1688
junyulai74f9a8b2018-06-13 15:00:37 +08001689 @VisibleForTesting
1690 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001691 if (network == null) {
1692 return null;
1693 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001694 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001695 }
1696
1697 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001698 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001699 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001700 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001701 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001702
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001703 // TODO: determine what to do when more than one VPN applies to |uid|.
1704 private NetworkAgentInfo getVpnForUid(int uid) {
1705 synchronized (mNetworkForNetId) {
1706 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1707 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
1708 if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) {
1709 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001710 }
1711 }
1712 }
1713 return null;
1714 }
1715
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001716 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001717 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001718 final NetworkAgentInfo nai = getVpnForUid(uid);
1719 if (nai != null) return nai.declaredUnderlyingNetworks;
1720 return null;
1721 }
1722
Lorenzo Colittia7574052021-01-19 01:33:05 +09001723 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001724 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001725
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001726 final Network[] networks = getVpnUnderlyingNetworks(uid);
1727 if (networks != null) {
1728 // getUnderlyingNetworks() returns:
1729 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1730 // empty array => the VPN explicitly said "no default network".
1731 // non-empty array => the VPN specified one or more default networks; we use the
1732 // first one.
1733 if (networks.length > 0) {
1734 nai = getNetworkAgentInfoForNetwork(networks[0]);
1735 } else {
1736 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001737 }
1738 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001739 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001740 }
1741
1742 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001743 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001744 */
paulhu7aeba372020-12-30 00:42:19 +08001745 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1746 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001747 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001748 if (ignoreBlocked) {
1749 return false;
1750 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001751 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001752 final long ident = Binder.clearCallingIdentity();
1753 try {
1754 final boolean metered = nc == null ? true : nc.isMetered();
1755 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1756 } finally {
1757 Binder.restoreCallingIdentity(ident);
1758 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001759 }
1760
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001761 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001762 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1763 return;
1764 }
Hugo Benichi47011212017-03-30 10:46:05 +09001765 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001766 synchronized (mBlockedAppUids) {
1767 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001768 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001769 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001770 blocked = false;
1771 } else {
1772 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001773 }
1774 }
Hugo Benichi47011212017-03-30 10:46:05 +09001775 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1776 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1777 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001778 }
1779
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001780 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001781 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1782 return;
1783 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001784 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001785 final int requestId = nri.getActiveRequest() != null
1786 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001787 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001788 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001789 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001790 }
1791
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001792 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001793 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001794 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001795 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001796 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001797 @NonNull
1798 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1799 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001800 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1801 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1802 // but only exists if an app asks about them or requests them. Ensure the requesting app
1803 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001804 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001805 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1806 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1807 null /* extraInfo */);
1808 }
1809 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001810 return filtered;
1811 }
1812
1813 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1814 boolean ignoreBlocked) {
1815 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1816 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001817 }
1818
1819 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001820 * Return NetworkInfo for the active (i.e., connected) network interface.
1821 * It is assumed that at most one network is active at a time. If more
1822 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001823 * @return the info for the active network, or {@code null} if none is
1824 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001825 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001826 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001827 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001828 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001829 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001830 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1831 if (nai == null) return null;
1832 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1833 maybeLogBlockedNetworkInfo(networkInfo, uid);
1834 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001835 }
1836
Paul Jensen1f567382015-02-13 14:18:39 -05001837 @Override
1838 public Network getActiveNetwork() {
1839 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001840 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00001841 }
1842
1843 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001844 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001845 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001846 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001847 }
1848
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001849 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001850 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1851 if (vpnNai != null) {
1852 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1853 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1854 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09001855 }
Paul Jensen1f567382015-02-13 14:18:39 -05001856 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001857
James Mattis2516da32021-01-31 17:06:19 -08001858 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001859 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1860 ignoreBlocked)) {
1861 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001862 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001863 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05001864 }
1865
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001866 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001867 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001868 PermissionUtils.enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001869 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1870 if (nai == null) return null;
1871 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001872 }
1873
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001874 /** Returns a NetworkInfo object for a network that doesn't exist. */
1875 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1876 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1877 getNetworkTypeName(networkType), "" /* subtypeName */);
1878 info.setIsAvailable(true);
1879 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1880 // background data is restricted.
1881 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1882 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1883 ? DetailedState.BLOCKED
1884 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001885 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1886 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001887 return info;
1888 }
1889
Lorenzo Colittia7574052021-01-19 01:33:05 +09001890 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001891 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1892 return null;
1893 }
1894 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001895 if (nai == null) {
1896 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001897 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001898 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1899 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001900 }
1901
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001902 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001903 public NetworkInfo getNetworkInfo(int networkType) {
1904 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001905 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001906 if (getVpnUnderlyingNetworks(uid) != null) {
1907 // A VPN is active, so we may need to return one of its underlying networks. This
1908 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09001909 // getNetworkAgentInfoForUid.
1910 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1911 if (nai == null) return null;
1912 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1913 if (networkInfo.getType() == networkType) {
1914 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001915 }
1916 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001917 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001918 }
1919
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001920 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001921 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001922 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001923 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001924 if (nai == null) return null;
1925 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001926 }
1927
1928 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001929 public NetworkInfo[] getAllNetworkInfo() {
1930 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08001931 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04001932 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1933 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001934 NetworkInfo info = getNetworkInfo(networkType);
1935 if (info != null) {
1936 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001937 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001938 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001939 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001940 }
1941
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001942 @Override
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001943 public Network getNetworkForType(int networkType) {
1944 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001945 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1946 return null;
1947 }
1948 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1949 if (nai == null) {
1950 return null;
1951 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001952 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001953 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
1954 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001955 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001956 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001957 }
1958
1959 @Override
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001960 public Network[] getAllNetworks() {
1961 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001962 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04001963 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001964 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04001965 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001966 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04001967 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001968 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001969 }
1970
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001971 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08001972 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001973 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001974 // The basic principle is: if an app's traffic could possibly go over a
1975 // network, without the app doing anything multinetwork-specific,
1976 // (hence, by "default"), then include that network's capabilities in
1977 // the array.
1978 //
1979 // In the normal case, app traffic only goes over the system's default
1980 // network connection, so that's the only network returned.
1981 //
1982 // With a VPN in force, some app traffic may go into the VPN, and thus
1983 // over whatever underlying networks the VPN specifies, while other app
1984 // traffic may go over the system default network (e.g.: a split-tunnel
1985 // VPN, or an app disallowed by the VPN), so the set of networks
1986 // returned includes the VPN's underlying networks and the system
1987 // default.
1988 enforceAccessPermission();
1989
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001990 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001991
James Mattis2516da32021-01-31 17:06:19 -08001992 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
1993 if (!nri.isBeingSatisfied()) {
1994 continue;
1995 }
1996 final NetworkAgentInfo nai = nri.getSatisfier();
1997 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
1998 if (null != nc
1999 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2000 && !result.containsKey(nai.network)) {
2001 result.put(
2002 nai.network,
2003 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002004 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002005 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2006 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002007 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002008 }
2009
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002010 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002011 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002012 if (null != networks) {
2013 for (final Network network : networks) {
2014 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2015 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002016 result.put(
2017 network,
2018 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002019 nc,
2020 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002021 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002022 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002023 }
2024 }
2025 }
2026
2027 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2028 out = result.values().toArray(out);
2029 return out;
2030 }
2031
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002032 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002033 public boolean isNetworkSupported(int networkType) {
2034 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002035 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002036 }
2037
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002038 /**
2039 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002040 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002041 * @return the ip properties for the active network, or {@code null} if
2042 * none is active
2043 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002044 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002045 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002046 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002047 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002048 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2049 if (nai == null) return null;
2050 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002051 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002052 }
2053
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002054 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002055 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002056 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002057 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002058 final LinkProperties lp = getLinkProperties(nai);
2059 if (lp == null) return null;
2060 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002061 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002062 }
2063
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002064 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002065 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002066 public LinkProperties getLinkProperties(Network network) {
2067 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002068 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2069 if (lp == null) return null;
2070 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002071 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002072 }
2073
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002074 @Nullable
2075 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002076 if (nai == null) {
2077 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002078 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002079 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002080 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002081 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002082 }
2083
lucaslinc582d502022-01-27 09:07:00 +08002084 @Override
2085 @Nullable
2086 public LinkProperties redactLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
2087 @NonNull String packageName, @Nullable String callingAttributionTag) {
2088 Objects.requireNonNull(packageName);
2089 Objects.requireNonNull(lp);
2090 enforceNetworkStackOrSettingsPermission();
2091 if (!checkAccessPermission(-1 /* pid */, uid)) {
2092 return null;
2093 }
2094 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2095 }
2096
Qingxi Lib2748102020-01-08 12:51:49 -08002097 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2098 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2099 }
2100
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002101 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002102 if (nai == null) return null;
2103 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002104 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002105 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002106 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002107 }
2108
2109 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002110 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2111 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002112 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002113 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002114 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002115 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002116 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002117 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002118 }
2119
lucaslinc582d502022-01-27 09:07:00 +08002120 @Override
2121 public NetworkCapabilities redactNetworkCapabilitiesForPackage(@NonNull NetworkCapabilities nc,
2122 int uid, @NonNull String packageName, @Nullable String callingAttributionTag) {
2123 Objects.requireNonNull(nc);
2124 Objects.requireNonNull(packageName);
2125 enforceNetworkStackOrSettingsPermission();
2126 if (!checkAccessPermission(-1 /* pid */, uid)) {
2127 return null;
2128 }
2129 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2130 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2131 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2132 callingAttributionTag);
2133 }
2134
Qingxi Libb8da982020-01-17 17:54:27 -08002135 @VisibleForTesting
2136 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002137 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002138 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2139 // this would be expensive (one more permission check every time any NC callback is
2140 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2141 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2142 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002143 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002144 if (!checkSettingsPermission(callerPid, callerUid)) {
2145 newNc.setUids(null);
2146 newNc.setSSID(null);
lucaslinc582d502022-01-27 09:07:00 +08002147 // TODO: Processes holding NETWORK_FACTORY should be able to see the underlying networks
lucaslin6adf5ac2021-10-19 15:04:56 +08002148 newNc.setUnderlyingNetworks(null);
Chalard Jean46adcf32018-04-18 20:18:38 +09002149 }
Etan Cohen107ae952018-12-30 17:59:59 -08002150 if (newNc.getNetworkSpecifier() != null) {
2151 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2152 }
Cody Kesting5ab1f552020-03-16 18:15:28 -07002153 newNc.setAdministratorUids(new int[0]);
Benedict Wong53de25f2021-03-24 14:01:51 -07002154 if (!checkAnyPermissionOf(
2155 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09002156 newNc.setAccessUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002157 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002158 }
Qingxi Libb8da982020-01-17 17:54:27 -08002159
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002160 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002161 }
2162
Roshan Pius98f59ec2021-02-23 08:47:39 -08002163 /**
2164 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002165 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002166 * NetworkCapabilities.
2167 * Note: This wrapper does not support any sort of invalidation and thus must not be
2168 * persistent or long-lived. It may only be used for the time necessary to
2169 * compute the redactions required by one particular NetworkCallback or
2170 * synchronous call.
2171 */
2172 private class RedactionPermissionChecker {
2173 private final int mCallingPid;
2174 private final int mCallingUid;
2175 @NonNull private final String mCallingPackageName;
2176 @Nullable private final String mCallingAttributionTag;
2177
2178 private Boolean mHasLocationPermission = null;
2179 private Boolean mHasLocalMacAddressPermission = null;
2180 private Boolean mHasSettingsPermission = null;
2181
2182 RedactionPermissionChecker(int callingPid, int callingUid,
2183 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2184 mCallingPid = callingPid;
2185 mCallingUid = callingUid;
2186 mCallingPackageName = callingPackageName;
2187 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002188 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002189
2190 private boolean hasLocationPermissionInternal() {
2191 final long token = Binder.clearCallingIdentity();
2192 try {
2193 return mLocationPermissionChecker.checkLocationPermission(
2194 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2195 null /* message */);
2196 } finally {
2197 Binder.restoreCallingIdentity(token);
2198 }
2199 }
2200
2201 /**
2202 * Returns whether the app holds location permission or not (might return cached result
2203 * if the permission was already checked before).
2204 */
2205 public boolean hasLocationPermission() {
2206 if (mHasLocationPermission == null) {
2207 // If there is no cached result, perform the check now.
2208 mHasLocationPermission = hasLocationPermissionInternal();
2209 }
2210 return mHasLocationPermission;
2211 }
2212
2213 /**
2214 * Returns whether the app holds local mac address permission or not (might return cached
2215 * result if the permission was already checked before).
2216 */
2217 public boolean hasLocalMacAddressPermission() {
2218 if (mHasLocalMacAddressPermission == null) {
2219 // If there is no cached result, perform the check now.
2220 mHasLocalMacAddressPermission =
2221 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2222 }
2223 return mHasLocalMacAddressPermission;
2224 }
2225
2226 /**
2227 * Returns whether the app holds settings permission or not (might return cached
2228 * result if the permission was already checked before).
2229 */
2230 public boolean hasSettingsPermission() {
2231 if (mHasSettingsPermission == null) {
2232 // If there is no cached result, perform the check now.
2233 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2234 }
2235 return mHasSettingsPermission;
2236 }
2237 }
2238
2239 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2240 @NetworkCapabilities.NetCapability long redaction) {
2241 return (redactions & redaction) != 0;
2242 }
2243
2244 /**
2245 * Use the provided |applicableRedactions| to check the receiving app's
2246 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2247 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2248 * before being sent to the corresponding app.
2249 */
2250 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2251 @NetworkCapabilities.RedactionType long applicableRedactions,
2252 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2253 boolean includeLocationSensitiveInfo) {
2254 long redactions = applicableRedactions;
2255 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2256 if (includeLocationSensitiveInfo
2257 && redactionPermissionChecker.hasLocationPermission()) {
2258 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2259 }
2260 }
2261 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2262 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2263 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2264 }
2265 }
2266 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2267 if (redactionPermissionChecker.hasSettingsPermission()) {
2268 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2269 }
2270 }
2271 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002272 }
2273
Qingxi Lib2748102020-01-08 12:51:49 -08002274 @VisibleForTesting
2275 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002276 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002277 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002278 int callingPid, int callingUid, @NonNull String callingPkgName,
2279 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002280 if (nc == null) {
2281 return null;
2282 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002283 // Avoid doing location permission check if the transport info has no location sensitive
2284 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002285 final RedactionPermissionChecker redactionPermissionChecker =
2286 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2287 callingAttributionTag);
2288 final long redactions = retrieveRequiredRedactions(
2289 nc.getApplicableRedactions(), redactionPermissionChecker,
2290 includeLocationSensitiveInfo);
2291 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002292 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002293 // TODO : calling UID is redacted because apps should generally not know what UID is
2294 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002295 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002296 newNc.setOwnerUid(INVALID_UID);
2297 return newNc;
2298 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002299 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2300 if (nc.hasTransport(TRANSPORT_VPN)) {
2301 // Owner UIDs already checked above. No need to re-check.
2302 return newNc;
2303 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002304 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2305 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002306 // compatibility for older apps.
2307 if (!includeLocationSensitiveInfo
2308 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002309 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002310 newNc.setOwnerUid(INVALID_UID);
2311 return newNc;
2312 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002313 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002314 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002315 newNc.setOwnerUid(INVALID_UID);
2316 }
Qingxi Lib2748102020-01-08 12:51:49 -08002317 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002318 }
2319
lucaslinc582d502022-01-27 09:07:00 +08002320 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002321 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2322 LinkProperties lp, int callerPid, int callerUid) {
2323 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002324 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2325 // this would be expensive (one more permission check every time any LP callback is
2326 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2327 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2328 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002329
2330 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2331 final boolean needsSanitization =
2332 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2333 if (!needsSanitization) {
2334 return new LinkProperties(lp);
2335 }
2336
2337 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002338 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002339 }
2340
2341 final LinkProperties newLp = new LinkProperties(lp);
2342 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2343 // object gets parceled.
2344 newLp.setCaptivePortalApiUrl(null);
2345 newLp.setCaptivePortalData(null);
2346 return newLp;
2347 }
2348
Roshan Pius08c94fb2020-01-16 12:17:17 -08002349 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2350 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002351 // There is no need to track the effective UID of the request here. If the caller
2352 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002353 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002354 // Unprivileged apps can only pass in null or their own UID.
2355 if (nc.getUids() == null) {
2356 // If the caller passes in null, the callback will also match networks that do not
2357 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2358 // In this case, redact everything in the request immediately. This ensures that the
2359 // app is not able to get any redacted information by filing an unredacted request
2360 // and observing whether the request matches something.
2361 if (nc.getNetworkSpecifier() != null) {
2362 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2363 }
2364 } else {
2365 nc.setSingleUid(callerUid);
2366 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002367 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002368 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002369 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002370
2371 // Clear owner UID; this can never come from an app.
2372 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002373 }
2374
Chalard Jean38354d12018-03-20 19:13:57 +09002375 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002376 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002377 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2378 }
2379 }
2380
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002381 @Override
2382 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2383 enforceAccessPermission();
2384 final int callerUid = Binder.getCallingUid();
2385 final long token = Binder.clearCallingIdentity();
2386 try {
2387 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2388 } finally {
2389 Binder.restoreCallingIdentity(token);
2390 }
2391 }
2392
junyulaiebd15162021-03-03 12:09:05 +08002393 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002394 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002395 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002396 // This contains IMSI details, so make sure the caller is privileged.
paulhudf23d662021-01-25 18:53:17 +08002397 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002398
Serik Beketayev05130302021-01-15 16:47:25 -08002399 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002400 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002401 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2402 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002403 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002404 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002405 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002406 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2407 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002408 }
2409 }
2410 return result.toArray(new NetworkState[result.size()]);
2411 }
2412
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002413 @Override
junyulaiebd15162021-03-03 12:09:05 +08002414 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002415 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002416 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002417 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002418
2419 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2420 for (Network network : getAllNetworks()) {
2421 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Junyu Laiddecb662021-08-17 08:44:36 +00002422 if (nai != null && nai.everConnected) {
junyulaiebd15162021-03-03 12:09:05 +08002423 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2424 // NetworkCapabilities, which may contain UIDs of apps to which the
2425 // network applies. Should the UIDs be cleared so as not to leak or
2426 // interfere ?
2427 result.add(nai.getNetworkStateSnapshot());
2428 }
2429 }
2430 return result;
2431 }
2432
2433 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002434 public boolean isActiveNetworkMetered() {
2435 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002436
Qingxi Lib2748102020-01-08 12:51:49 -08002437 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002438 if (caps != null) {
2439 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2440 } else {
2441 // Always return the most conservative value
2442 return true;
2443 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002444 }
2445
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002446 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002447 * Ensures that the system cannot call a particular method.
2448 */
2449 private boolean disallowedBecauseSystemCaller() {
2450 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002451 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2452 // for devices launched with Q and above. However, existing devices upgrading to Q and
2453 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002454 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002455 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002456 log("This method exists only for app backwards compatibility"
2457 + " and must not be called by system services.");
2458 return true;
2459 }
2460 return false;
2461 }
2462
paulhub2c28682021-08-18 18:35:54 +08002463 private int getAppUid(final String app, final UserHandle user) {
2464 final PackageManager pm =
2465 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2466 final long token = Binder.clearCallingIdentity();
2467 try {
2468 return pm.getPackageUid(app, 0 /* flags */);
2469 } catch (PackageManager.NameNotFoundException e) {
2470 return -1;
2471 } finally {
2472 Binder.restoreCallingIdentity(token);
2473 }
2474 }
2475
2476 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2477 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2478 if (getAppUid(packageName, user) != callingUid) {
2479 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2480 }
2481 }
2482
Lorenzo Colitti23862912018-09-28 11:31:55 +09002483 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002484 * Ensure that a network route exists to deliver traffic to the specified
2485 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002486 * @param networkType the type of the network over which traffic to the
2487 * specified host is to be routed
2488 * @param hostAddress the IP address of the host to which the route is
2489 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002490 * @return {@code true} on success, {@code false} on failure
2491 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002492 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002493 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2494 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002495 if (disallowedBecauseSystemCaller()) {
2496 return false;
2497 }
paulhub2c28682021-08-18 18:35:54 +08002498 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002499 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002500 if (mProtectedNetworks.contains(networkType)) {
paulhu8e96a752019-08-12 16:25:11 +08002501 enforceConnectivityRestrictedNetworksPermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002502 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002503
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002504 InetAddress addr;
2505 try {
2506 addr = InetAddress.getByAddress(hostAddress);
2507 } catch (UnknownHostException e) {
2508 if (DBG) log("requestRouteToHostAddress got " + e.toString());
2509 return false;
2510 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002511
The Android Open Source Project28527d22009-03-03 19:31:44 -08002512 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002513 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002514 return false;
2515 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002516
2517 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2518 if (nai == null) {
2519 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
2520 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2521 } else {
2522 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2523 }
2524 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002525 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002526
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002527 DetailedState netState;
2528 synchronized (nai) {
2529 netState = nai.networkInfo.getDetailedState();
2530 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002531
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002532 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002533 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002534 log("requestRouteToHostAddress on down network "
2535 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002536 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002537 }
2538 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002539 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002540
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002541 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002542 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002543 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002544 LinkProperties lp;
2545 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002546 synchronized (nai) {
2547 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002548 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002549 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002550 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002551 if (DBG) {
2552 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2553 }
Wink Saville32506bc2013-06-29 21:10:57 -07002554 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002555 } finally {
2556 Binder.restoreCallingIdentity(token);
2557 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002558 }
2559
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002560 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002561 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002562 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002563 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002564 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002565 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002566 if (bestRoute.getGateway().equals(addr)) {
2567 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002568 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002569 } else {
2570 // if we will connect to this through another route, add a direct route
2571 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002572 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002573 }
2574 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002575 if (DBG) log("Adding legacy route " + bestRoute +
2576 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002577
2578 final String dst = bestRoute.getDestinationLinkAddress().toString();
2579 final String nextHop = bestRoute.hasGateway()
2580 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002581 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002582 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2583 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002584 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002585 return false;
2586 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002587 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002588 }
2589
paulhu7c0a2e62021-01-08 00:51:49 +08002590 class DnsResolverUnsolicitedEventCallback extends
2591 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002592 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002593 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002594 try {
2595 mHandler.sendMessage(mHandler.obtainMessage(
2596 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002597 new PrivateDnsValidationUpdate(event.netId,
2598 InetAddresses.parseNumericAddress(event.ipAddress),
2599 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002600 } catch (IllegalArgumentException e) {
2601 loge("Error parsing ip address in validation event");
2602 }
2603 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002604
2605 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002606 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2607 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002608 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2609 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2610 // event callback for certain nai. e.g. cellular. Register here to pass to
2611 // NetworkMonitor instead.
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002612 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allow one
2613 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2614 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002615 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002616 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002617 }
2618 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002619
2620 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002621 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2622 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2623 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002624 }
dalyk1720e542018-03-05 12:42:22 -05002625
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002626 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002627 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002628 return this.VERSION;
2629 }
2630
2631 @Override
2632 public String getInterfaceHash() {
2633 return this.HASH;
2634 }
paulhu7c0a2e62021-01-08 00:51:49 +08002635 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002636
2637 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002638 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2639 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002640
paulhu7c0a2e62021-01-08 00:51:49 +08002641 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002642 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002643 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002644 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002645 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002646 }
2647 }
2648
Sudheer Shanka9967d462021-03-18 19:09:25 +00002649 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002650 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002651 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002652 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2653 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002654 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002655 };
2656
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002657 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002658 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002659 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002660 }
2661
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002662 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002663 for (String permission : permissions) {
2664 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002665 return true;
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002666 }
2667 }
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002668 return false;
2669 }
2670
paulhu1a407652019-03-22 16:35:06 +08002671 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2672 for (String permission : permissions) {
2673 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2674 return true;
2675 }
2676 }
2677 return false;
2678 }
2679
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002680 private void enforceAnyPermissionOf(String... permissions) {
2681 if (!checkAnyPermissionOf(permissions)) {
2682 throw new SecurityException("Requires one of the following permissions: "
2683 + String.join(", ", permissions) + ".");
2684 }
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002685 }
2686
Paul Jensen83f5d572014-08-29 09:54:01 -04002687 private void enforceInternetPermission() {
2688 mContext.enforceCallingOrSelfPermission(
2689 android.Manifest.permission.INTERNET,
2690 "ConnectivityService");
2691 }
2692
The Android Open Source Project28527d22009-03-03 19:31:44 -08002693 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002694 mContext.enforceCallingOrSelfPermission(
2695 android.Manifest.permission.ACCESS_NETWORK_STATE,
2696 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002697 }
2698
lucaslinc582d502022-01-27 09:07:00 +08002699 private boolean checkAccessPermission(int pid, int uid) {
2700 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
2701 == PERMISSION_GRANTED;
2702 }
2703
paulhua6ee2122021-02-22 15:40:43 +08002704 /**
2705 * Performs a strict and comprehensive check of whether a calling package is allowed to
2706 * change the state of network, as the condition differs for pre-M, M+, and
2707 * privileged/preinstalled apps. The caller is expected to have either the
2708 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2709 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2710 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2711 * permission and cannot be revoked. See http://b/23597341
2712 *
2713 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2714 * of this app will be updated to the current time.
2715 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002716 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002717 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2718 == PackageManager.PERMISSION_GRANTED) {
2719 return;
2720 }
2721
2722 if (callingPkg == null) {
2723 throw new SecurityException("Calling package name is null.");
2724 }
2725
2726 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2727 final int uid = mDeps.getCallingUid();
2728 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2729 callingPkg, callingAttributionTag, null /* message */);
2730
2731 if (mode == AppOpsManager.MODE_ALLOWED) {
2732 return;
2733 }
2734
2735 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2736 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2737 return;
2738 }
2739
2740 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2741 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2742 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002743 }
2744
Charles He9369e612017-05-15 17:07:18 +01002745 private void enforceSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002746 enforceAnyPermissionOf(
Charles He9369e612017-05-15 17:07:18 +01002747 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002748 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002749 }
2750
paulhu8e96a752019-08-12 16:25:11 +08002751 private void enforceNetworkFactoryPermission() {
paulhub6ba8e82020-03-04 09:43:41 +08002752 enforceAnyPermissionOf(
paulhu8e96a752019-08-12 16:25:11 +08002753 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002754 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002755 }
2756
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002757 private void enforceNetworkFactoryOrSettingsPermission() {
2758 enforceAnyPermissionOf(
2759 android.Manifest.permission.NETWORK_SETTINGS,
2760 android.Manifest.permission.NETWORK_FACTORY,
2761 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2762 }
2763
2764 private void enforceNetworkFactoryOrTestNetworksPermission() {
2765 enforceAnyPermissionOf(
2766 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2767 android.Manifest.permission.NETWORK_FACTORY,
2768 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2769 }
2770
Chalard Jean9a396cc2018-02-21 18:43:54 +09002771 private boolean checkSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002772 return checkAnyPermissionOf(
2773 android.Manifest.permission.NETWORK_SETTINGS,
2774 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002775 }
2776
2777 private boolean checkSettingsPermission(int pid, int uid) {
2778 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002779 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2780 || PERMISSION_GRANTED == mContext.checkPermission(
2781 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002782 }
2783
paulhu8e96a752019-08-12 16:25:11 +08002784 private void enforceNetworkStackOrSettingsPermission() {
2785 enforceAnyPermissionOf(
2786 android.Manifest.permission.NETWORK_SETTINGS,
2787 android.Manifest.permission.NETWORK_STACK,
2788 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2789 }
2790
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002791 private void enforceNetworkStackSettingsOrSetup() {
2792 enforceAnyPermissionOf(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002793 android.Manifest.permission.NETWORK_SETTINGS,
2794 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002795 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002796 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002797 }
2798
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002799 private void enforceAirplaneModePermission() {
2800 enforceAnyPermissionOf(
2801 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2802 android.Manifest.permission.NETWORK_SETTINGS,
2803 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2804 android.Manifest.permission.NETWORK_STACK,
2805 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2806 }
2807
James Mattis8378aec2021-01-26 14:05:36 -08002808 private void enforceOemNetworkPreferencesPermission() {
2809 mContext.enforceCallingOrSelfPermission(
2810 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2811 "ConnectivityService");
2812 }
2813
James Mattisfa270db2021-05-31 17:11:10 -07002814 private void enforceManageTestNetworksPermission() {
2815 mContext.enforceCallingOrSelfPermission(
2816 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2817 "ConnectivityService");
2818 }
2819
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002820 private boolean checkNetworkStackPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002821 return checkAnyPermissionOf(
2822 android.Manifest.permission.NETWORK_STACK,
2823 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002824 }
2825
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002826 private boolean checkNetworkStackPermission(int pid, int uid) {
2827 return checkAnyPermissionOf(pid, uid,
2828 android.Manifest.permission.NETWORK_STACK,
2829 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2830 }
2831
paulhu1a407652019-03-22 16:35:06 +08002832 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2833 return checkAnyPermissionOf(pid, uid,
2834 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002835 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2836 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002837 }
2838
Hugo Benichibd0cc762016-07-19 15:59:27 +09002839 private void enforceConnectivityRestrictedNetworksPermission() {
2840 try {
2841 mContext.enforceCallingOrSelfPermission(
2842 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2843 "ConnectivityService");
2844 return;
2845 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
paulhu8e96a752019-08-12 16:25:11 +08002846 // TODO: Remove this fallback check after all apps have declared
2847 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2848 mContext.enforceCallingOrSelfPermission(
2849 android.Manifest.permission.CONNECTIVITY_INTERNAL,
2850 "ConnectivityService");
Hugo Benichibd0cc762016-07-19 15:59:27 +09002851 }
2852
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002853 private void enforceKeepalivePermission() {
Lorenzo Colittif25beee2015-09-08 13:21:48 +09002854 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002855 }
2856
Roshan Pius98f59ec2021-02-23 08:47:39 -08002857 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2858 return PERMISSION_GRANTED == mContext.checkPermission(
2859 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2860 }
2861
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002862 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002863 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002864 }
2865
2866 private void sendInetConditionBroadcast(NetworkInfo info) {
2867 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2868 }
2869
Wink Saville4f0de1e2011-08-04 15:01:58 -07002870 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002871 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002872 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002873 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002874 if (info.isFailover()) {
2875 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2876 info.setFailover(false);
2877 }
2878 if (info.getReason() != null) {
2879 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2880 }
2881 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002882 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2883 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002884 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002885 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002886 return intent;
2887 }
2888
2889 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2890 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2891 }
2892
Chiachang Wang3bc52762021-11-25 14:17:57 +08002893 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
2894 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002895 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09002896 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09002897 if (!mSystemReady
2898 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002899 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002900 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002901 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002902 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002903 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002904 }
2905
Dianne Hackborn66dd0332015-12-09 17:22:26 -08002906 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07002907 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002908 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07002909 final NetworkInfo ni = intent.getParcelableExtra(
2910 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08002911 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2912 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2913 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08002914 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002915 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07002916 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00002917 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002918 } finally {
2919 Binder.restoreCallingIdentity(ident);
2920 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002921 }
2922 }
2923
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002924 /**
Aaron Huang96011892020-06-27 07:18:23 +08002925 * Called by SystemServer through ConnectivityManager when the system is ready.
2926 */
2927 @Override
2928 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002929 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08002930 throw new SecurityException("Calling Uid is not system uid.");
2931 }
2932 systemReadyInternal();
2933 }
2934
2935 /**
2936 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002937 */
2938 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08002939 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09002940 // Load flags after PackageManager is ready to query module version
2941 mFlags.loadFlags(mDeps, mContext);
2942
Aaron Huang9a57acf2020-12-08 10:03:29 +08002943 // Since mApps in PermissionMonitor needs to be populated first to ensure that
2944 // listening network request which is sent by MultipathPolicyTracker won't be added
2945 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
2946 // be called after PermissionMonitor#startMonitoring().
2947 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
2948 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
2949 // to ensure the tracking will be initialized correctly.
paulhuc62d3c22019-11-19 17:55:31 +08002950 mPermissionMonitor.startMonitoring();
Chalard Jeane4f9bd92018-06-08 12:47:42 +09002951 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08002952 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002953
Hugo Benichie5220992017-04-26 14:53:28 +09002954 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002955 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002956 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07002957 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002958 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002959 }
2960 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002961
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002962 // Create network requests for always-on networks.
2963 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00002964
2965 // Update mobile data preference if necessary.
2966 // Note that empty uid list can be skip here only because no uid rules applied before system
2967 // ready. Normally, the empty uid list means to clear the uids rules on netd.
2968 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
2969 updateMobileDataPreferredUids();
2970 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002971 }
2972
The Android Open Source Project28527d22009-03-03 19:31:44 -08002973 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002974 * Start listening for default data network activity state changes.
2975 */
2976 @Override
2977 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08002978 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002979 }
2980
2981 /**
2982 * Stop listening for default data network activity state changes.
2983 */
2984 @Override
2985 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08002986 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002987 }
2988
2989 /**
2990 * Check whether the default network radio is currently active.
2991 */
2992 @Override
2993 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08002994 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002995 }
2996
2997 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09002998 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09002999 * and set it on it's iface.
3000 */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003001 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
3002 final String iface = newLp.getInterfaceName();
3003 final int mtu = newLp.getMtu();
Pierre Imai07c53a32016-02-08 16:01:40 +09003004 if (oldLp == null && mtu == 0) {
3005 // Silently ignore unset MTU value.
3006 return;
3007 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003008 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
3009 if (VDBG) log("identical MTU - not setting");
3010 return;
3011 }
paulhucbbc3db2019-03-08 16:35:20 +08003012 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003013 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003014 return;
3015 }
sy.yun4aa73922013-09-02 05:24:09 +09003016
w19976e714f1d2014-08-05 15:18:11 -07003017 // Cannot set MTU without interface name
3018 if (TextUtils.isEmpty(iface)) {
3019 loge("Setting MTU size with null iface.");
3020 return;
3021 }
3022
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003023 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003024 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003025 mNetd.interfaceSetMtu(iface, mtu);
3026 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003027 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003028 }
3029 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003030
Chenbo Feng15416292018-11-08 17:36:21 -08003031 @VisibleForTesting
3032 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003033
lucaslin821c9782018-11-28 19:27:52 +08003034 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003035 String[] values = null;
3036 if (tcpBufferSizes != null) {
3037 values = tcpBufferSizes.split(",");
3038 }
3039
3040 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003041 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003042 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3043 values = tcpBufferSizes.split(",");
3044 }
3045
3046 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3047
3048 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003049 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003050
Chenbo Feng15416292018-11-08 17:36:21 -08003051 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3052 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3053 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003054 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003055 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003056 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003057 }
3058 }
3059
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003060 @Override
3061 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003062 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003063 NETWORK_RESTORE_DELAY_PROP_NAME);
3064 if(restoreDefaultNetworkDelayStr != null &&
3065 restoreDefaultNetworkDelayStr.length() != 0) {
3066 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003067 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003068 } catch (NumberFormatException e) {
3069 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003070 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003071 // if the system property isn't set, use the value for the apn type
3072 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3073
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003074 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3075 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003076 }
3077 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003078 }
3079
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003080 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
3081 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
3082 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003083 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003084 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003085 // Start gathering diagnostic information.
3086 netDiags.add(new NetworkDiagnostics(
3087 nai.network,
3088 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003089 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003090 DIAG_TIME_MS));
3091 }
3092
3093 for (NetworkDiagnostics netDiag : netDiags) {
3094 pw.println();
3095 netDiag.waitForMeasurements();
3096 netDiag.dump(pw);
3097 }
3098 }
3099
The Android Open Source Project28527d22009-03-03 19:31:44 -08003100 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003101 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3102 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003103 if (!checkDumpPermission(mContext, TAG, writer)) return;
3104
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003105 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003106 }
3107
lucaslin99473f62020-12-10 15:10:54 +08003108 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3109 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3110 != PackageManager.PERMISSION_GRANTED) {
3111 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003112 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003113 + " due to missing android.permission.DUMP permission");
3114 return false;
3115 } else {
3116 return true;
3117 }
3118 }
3119
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003120 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003121 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003122
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003123 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003124 dumpNetworkDiagnostics(pw);
3125 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003126 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003127 dumpNetworks(pw);
3128 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003129 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003130 dumpNetworkRequests(pw);
3131 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003132 }
Erik Kline9647f382015-06-05 17:47:34 +09003133
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003134 pw.print("NetworkProviders for:");
3135 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
3136 pw.print(" " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003137 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09003138 pw.println();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003139 pw.println();
3140
Chalard Jean5b409c72021-02-04 13:12:59 +09003141 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003142 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003143 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003144 pw.println("none");
3145 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003146 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003147 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003148 pw.println();
3149
James Mattis8b298a02021-06-01 22:34:04 -07003150 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003151 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003152 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003153 pw.decreaseIndent();
3154 pw.println();
3155
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003156 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003157 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003158 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003159 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003160 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003161
junyulaif2c67e42018-08-07 19:50:45 +08003162 pw.println("Status for known UIDs:");
3163 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003164 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003165 for (int i = 0; i < size; i++) {
3166 // Don't crash if the array is modified while dumping in bugreports.
3167 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003168 final int uid = mUidBlockedReasons.keyAt(i);
3169 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3170 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003171 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003172 } catch (ArrayIndexOutOfBoundsException e) {
3173 pw.println(" ArrayIndexOutOfBoundsException");
3174 } catch (ConcurrentModificationException e) {
3175 pw.println(" ConcurrentModificationException");
3176 }
3177 }
3178 pw.println();
3179 pw.decreaseIndent();
3180
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003181 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003182 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003183 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003184 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003185 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003186
Robert Greenwalt94e22142014-07-30 16:31:24 -07003187 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003188
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003189 pw.println();
markchien5e866652019-09-30 14:40:57 +08003190 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003191
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003192 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003193 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003194
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003195 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003196
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003197 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003198 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003199 pw.println("mNetworkRequestInfoLogs (most recent first):");
3200 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003201 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003202 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003203
3204 pw.println();
3205 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3206 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003207 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003208 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003209
3210 pw.println();
3211 pw.println("NetTransition WakeLock activity (most recent first):");
3212 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003213 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3214 pw.println("total releases: " + mTotalWakelockReleases);
3215 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3216 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3217 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3218 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3219 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3220 }
James Mattiscb1e0362021-04-06 17:07:42 -07003221 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003222
3223 pw.println();
3224 pw.println("bandwidth update requests (by uid):");
3225 pw.increaseIndent();
3226 synchronized (mBandwidthRequests) {
3227 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3228 pw.println("[" + mBandwidthRequests.keyAt(i)
3229 + "]: " + mBandwidthRequests.valueAt(i));
3230 }
3231 }
3232 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003233 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003234
James Mattiscb1e0362021-04-06 17:07:42 -07003235 pw.println();
3236 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3237 pw.increaseIndent();
3238 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003239 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003240 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003241
3242 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003243
3244 pw.println();
3245 pw.println("Permission Monitor:");
3246 pw.increaseIndent();
3247 mPermissionMonitor.dump(pw);
3248 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003249
3250 pw.println();
3251 pw.println("Legacy network activity:");
3252 pw.increaseIndent();
3253 mNetworkActivityTracker.dump(pw);
3254 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003255 }
3256
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003257 private void dumpNetworks(IndentingPrintWriter pw) {
3258 for (NetworkAgentInfo nai : networksSortedById()) {
3259 pw.println(nai.toString());
3260 pw.increaseIndent();
3261 pw.println(String.format(
3262 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3263 nai.numForegroundNetworkRequests(),
3264 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3265 nai.numBackgroundNetworkRequests(),
3266 nai.numNetworkRequests()));
3267 pw.increaseIndent();
3268 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3269 pw.println(nai.requestAt(i).toString());
3270 }
3271 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003272 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003273 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003274 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003275 pw.decreaseIndent();
3276 pw.decreaseIndent();
3277 }
3278 }
3279
James Mattis8b298a02021-06-01 22:34:04 -07003280 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3281 if (!mProfileNetworkPreferences.isEmpty()) {
3282 pw.println("Profile preferences:");
3283 pw.increaseIndent();
3284 pw.println(mProfileNetworkPreferences.preferences);
3285 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003286 }
James Mattis8b298a02021-06-01 22:34:04 -07003287 if (!mOemNetworkPreferences.isEmpty()) {
3288 pw.println("OEM preferences:");
3289 pw.increaseIndent();
3290 pw.println(mOemNetworkPreferences);
3291 pw.decreaseIndent();
3292 }
3293 if (!mMobileDataPreferredUids.isEmpty()) {
3294 pw.println("Mobile data preferred UIDs:");
3295 pw.increaseIndent();
3296 pw.println(mMobileDataPreferredUids);
3297 pw.decreaseIndent();
3298 }
James Mattis45d81842021-01-10 14:24:24 -08003299
James Mattis8b298a02021-06-01 22:34:04 -07003300 pw.println("Default requests:");
3301 pw.increaseIndent();
3302 dumpPerAppDefaultRequests(pw);
3303 pw.decreaseIndent();
3304 }
3305
3306 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003307 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3308 if (mDefaultRequest == defaultRequest) {
3309 continue;
3310 }
3311
James Mattis8b298a02021-06-01 22:34:04 -07003312 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3313 final String networkOutput;
3314 if (null == satisfier) {
3315 networkOutput = "null";
3316 } else if (mNoServiceNetwork.equals(satisfier)) {
3317 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003318 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003319 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003320 }
James Mattis8b298a02021-06-01 22:34:04 -07003321 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3322 ? "" : " asUid: " + defaultRequest.mAsUid;
3323 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3324 + defaultRequest.mPid + asUidString + "]";
3325 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3326 + " Preference order: " + defaultRequest.mPreferenceOrder
3327 + " Tracked UIDs: " + defaultRequest.getUids();
3328 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003329 }
3330 }
3331
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003332 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003333 NetworkRequestInfo[] infos = null;
3334 while (infos == null) {
3335 try {
3336 infos = requestsSortedById();
3337 } catch (ConcurrentModificationException e) {
3338 // mNetworkRequests should only be accessed from handler thread, except dump().
3339 // As dump() is never called in normal usage, it would be needlessly expensive
3340 // to lock the collection only for its benefit. Instead, retry getting the
3341 // requests if ConcurrentModificationException is thrown during dump().
3342 }
3343 }
3344 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003345 pw.println(nri.toString());
3346 }
3347 }
3348
Chalard Jean524f0b12021-10-25 21:11:56 +09003349 private void dumpAllRequestInfoLogsToLogcat() {
3350 try (PrintWriter logPw = new PrintWriter(new Writer() {
3351 @Override
3352 public void write(final char[] cbuf, final int off, final int len) {
3353 // This method is called with 0-length and 1-length arrays for empty strings
3354 // or strings containing only the DEL character.
3355 if (len <= 1) return;
3356 Log.e(TAG, new String(cbuf, off, len));
3357 }
3358 @Override public void flush() {}
3359 @Override public void close() {}
3360 })) {
3361 mNetworkRequestInfoLogs.dump(logPw);
3362 }
3363 }
3364
Hugo Benichia480ba52018-09-03 08:19:02 +09003365 /**
3366 * Return an array of all current NetworkAgentInfos sorted by network id.
3367 */
3368 private NetworkAgentInfo[] networksSortedById() {
3369 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003370 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003371 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003372 return networks;
3373 }
3374
3375 /**
3376 * Return an array of all current NetworkRequest sorted by request id.
3377 */
James Mattis258ea3c2020-11-15 15:04:40 -08003378 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003379 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003380 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003381 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003382 // Sort the array based off the NRI containing the min requestId in its requests.
3383 Arrays.sort(requests,
3384 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3385 Comparator.comparingInt(req -> req.requestId)).requestId
3386 )
3387 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003388 return requests;
3389 }
3390
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003391 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003392 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003393 if (officialNai != null && officialNai.equals(nai)) return true;
3394 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003395 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003396 " - " + nai);
3397 }
3398 return false;
3399 }
3400
Robert Greenwalt2034b912009-08-12 16:08:25 -07003401 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003402 private class NetworkStateTrackerHandler extends Handler {
3403 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003404 super(looper);
3405 }
3406
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003407 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003408 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3409 final NetworkAgentInfo nai = arg.first;
3410 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003411 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003412 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003413 }
3414 return;
3415 }
3416
3417 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003418 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean15228572022-01-28 19:29:12 +09003419 final NetworkCapabilities networkCapabilities = new NetworkCapabilities(
3420 (NetworkCapabilities) arg.second);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003421 processCapabilitiesFromAgent(nai, networkCapabilities);
Hugo Benichibbc15192016-09-15 18:18:48 +09003422 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003423 break;
3424 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003425 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003426 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003427 processLinkPropertiesFromAgent(nai, newLp);
3428 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003429 break;
3430 }
3431 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003432 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003433 updateNetworkInfo(nai, info);
3434 break;
3435 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003436 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003437 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003438 break;
3439 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003440 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003441 if (nai.everConnected) {
3442 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003443 // Note that if the NAI had been connected, this would affect the
3444 // score, and therefore would require re-mixing the score and performing
3445 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003446 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003447 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3448 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003449 // Mark the network as temporarily accepting partial connectivity so that it
3450 // will be validated (and possibly become default) even if it only provides
3451 // partial internet access. Note that if user connects to partial connectivity
3452 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3453 // out of wifi coverage) and if the same wifi is available again, the device
3454 // will auto connect to this wifi even though the wifi has "no internet".
3455 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003456 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003457 break;
3458 }
junyulai011b1f12019-01-03 18:50:15 +08003459 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003460 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003461 break;
3462 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003463 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003464 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003465 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003466
3467 if (isLegacyLockdownNai(nai)
3468 && (underlying == null || underlying.size() != 1)) {
3469 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3470 + " must have exactly one underlying network: " + underlying);
3471 }
3472
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003473 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3474 nai.declaredUnderlyingNetworks = (underlying != null)
3475 ? underlying.toArray(new Network[0]) : null;
3476
3477 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3478 if (DBG) {
3479 log(nai.toShortString() + " changed underlying networks to "
3480 + Arrays.toString(nai.declaredUnderlyingNetworks));
3481 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003482 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003483 notifyIfacesChangedForNetworkStats();
3484 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003485 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003486 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003487 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3488 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3489 nai.teardownDelayMs = msg.arg1;
3490 } else {
3491 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3492 }
Chalard Jean550b5212021-03-05 23:07:53 +09003493 break;
3494 }
3495 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3496 nai.setLingerDuration((int) arg.second);
3497 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003498 }
Tyler Wear72388212021-09-09 14:49:02 -07003499 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3500 DscpPolicy policy = (DscpPolicy) arg.second;
3501 if (mDscpPolicyTracker != null) {
3502 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3503 }
3504 break;
3505 }
3506 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3507 if (mDscpPolicyTracker != null) {
3508 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3509 }
3510 break;
3511 }
3512 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3513 if (mDscpPolicyTracker != null) {
3514 mDscpPolicyTracker.removeAllDscpPolicies(nai);
3515 }
3516 break;
3517 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003518 }
3519 }
3520
3521 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
3522 switch (msg.what) {
3523 default:
3524 return false;
lucasline117e2e2019-10-22 18:27:33 +08003525 case EVENT_PROBE_STATUS_CHANGED: {
3526 final Integer netId = (Integer) msg.obj;
3527 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3528 if (nai == null) {
3529 break;
3530 }
3531 final boolean probePrivateDnsCompleted =
3532 ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
3533 final boolean privateDnsBroken =
3534 ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
3535 if (probePrivateDnsCompleted) {
3536 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3537 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003538 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003539 }
3540 // Only show the notification when the private DNS is broken and the
3541 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003542 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003543 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3544 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003545 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003546 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3547 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3548 // private DNS is broken, it means this network is being reevaluated.
3549 // Either probing private DNS is not necessary any more or it hasn't been
3550 // done yet. In either case, the networkCapabilities should be updated to
3551 // reflect the new status.
3552 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003553 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003554 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003555 }
3556 break;
3557 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003558 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003559 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3560
3561 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(results.mNetId);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003562 if (nai == null) break;
3563
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003564 handleNetworkTested(nai, results.mTestResult,
3565 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003566 break;
3567 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003568 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09003569 final int netId = msg.arg2;
Hugo Benichif4210292017-04-21 15:07:12 +09003570 final boolean visible = toBool(msg.arg1);
Erik Kline9a62f012018-03-21 07:18:33 -07003571 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Ondada1452016-10-11 15:10:46 -07003572 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04003573 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3574 nai.lastCaptivePortalDetected = visible;
3575 nai.everCaptivePortalDetected |= visible;
Calvin Ondada1452016-10-11 15:10:46 -07003576 if (nai.lastCaptivePortalDetected &&
paulhu56e09df2021-03-17 20:30:33 +08003577 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3578 == getCaptivePortalMode()) {
Chalard Jean49707572019-12-10 21:07:02 +09003579 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003580 nai.onPreventAutomaticReconnect();
Calvin Ondada1452016-10-11 15:10:46 -07003581 teardownUnneededNetwork(nai);
3582 break;
3583 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003584 updateCapabilitiesForNetwork(nai);
Paul Jensen53f08952015-06-16 14:27:36 -04003585 }
3586 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003587 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003588 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003589 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3590 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003591 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003592 if (nai == null) {
3593 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3594 break;
3595 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003596 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003597 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003598 (PendingIntent) msg.obj,
3599 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003600 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003601 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003602 break;
3603 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003604 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline9a62f012018-03-21 07:18:33 -07003605 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003606 if (nai == null) break;
3607
Erik Kline9a62f012018-03-21 07:18:33 -07003608 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003609 break;
3610 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003611 case EVENT_CAPPORT_DATA_CHANGED: {
3612 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3613 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003614 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003615 break;
3616 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003617 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003618 return true;
3619 }
3620
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003621 private void handleNetworkTested(
3622 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
3623 final boolean wasPartial = nai.partialConnectivity;
3624 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3625 final boolean partialConnectivityChanged =
3626 (wasPartial != nai.partialConnectivity);
3627
3628 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3629 final boolean wasValidated = nai.lastValidated;
Chalard Jean5b409c72021-02-04 13:12:59 +09003630 final boolean wasDefault = isDefaultNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003631
3632 if (DBG) {
3633 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3634 ? " with redirect to " + redirectUrl
3635 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003636 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003637 }
3638 if (valid != nai.lastValidated) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003639 final int oldScore = nai.getCurrentScore();
3640 nai.lastValidated = valid;
3641 nai.everValidated |= valid;
3642 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003643 if (valid) {
3644 handleFreshlyValidatedNetwork(nai);
3645 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3646 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003647 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003648 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003649 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003650 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003651 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003652 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003653 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003654 NotificationType.PRIVATE_DNS_BROKEN);
3655 // If network becomes valid, the hasShownBroken should be reset for
3656 // that network so that the notification will be fired when the private
3657 // DNS is broken again.
3658 nai.networkAgentConfig.hasShownBroken = false;
3659 }
3660 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003661 updateCapabilitiesForNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003662 }
3663 updateInetCondition(nai);
3664 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003665 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003666 nai.onValidationStatusChanged(
3667 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3668 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003669
3670 // If NetworkMonitor detects partial connectivity before
3671 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3672 // immediately. Re-notify partial connectivity silently if no internet
3673 // notification already there.
3674 if (!wasPartial && nai.partialConnectivity) {
3675 // Remove delayed message if there is a pending message.
3676 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3677 handlePromptUnvalidated(nai.network);
3678 }
3679
3680 if (wasValidated && !nai.lastValidated) {
3681 handleNetworkUnvalidated(nai);
3682 }
3683 }
3684
Calvin Ondada1452016-10-11 15:10:46 -07003685 private int getCaptivePortalMode() {
3686 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08003687 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3688 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07003689 }
3690
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003691 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3692 switch (msg.what) {
3693 default:
3694 return false;
3695 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3696 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3697 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3698 handleLingerComplete(nai);
3699 }
3700 break;
3701 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003702 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3703 handleNetworkAgentRegistered(msg);
3704 break;
3705 }
3706 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3707 handleNetworkAgentDisconnected(msg);
3708 break;
3709 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003710 }
3711 return true;
3712 }
3713
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003714 @Override
3715 public void handleMessage(Message msg) {
lifraf3a3492021-03-10 13:58:14 +08003716 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09003717 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003718 maybeHandleNetworkAgentMessage(msg);
3719 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003720 }
3721 }
3722
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003723 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09003724 private final int mNetId;
3725 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003726
3727 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003728 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003729 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003730 }
3731
3732 @Override
3733 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3734 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09003735 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003736 }
3737
3738 @Override
3739 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003740 // Legacy version of notifyNetworkTestedWithExtras.
3741 // Would only be called if the system has a NetworkStack module older than the
3742 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08003743 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003744 }
3745
3746 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003747 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09003748 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3749 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003750 final Message msg = mTrackerHandler.obtainMessage(
3751 EVENT_NETWORK_TESTED,
3752 new NetworkTestedResults(
3753 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003754 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003755
3756 // Invoke ConnectivityReport generation for this Network test event.
3757 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3758 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003759
Cody Kestingf1120be2020-08-03 18:01:40 -07003760 // NetworkMonitor reports the network validation result as a bitmask while
3761 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
3762 // logical value for ConnectivityDiagnostics.
3763 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
3764 p.result);
3765
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003766 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07003767 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003768 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3769 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3770
Aaron Huang959d3642021-01-21 15:47:41 +08003771 ConnectivityReportEvent reportEvent =
3772 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3773 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
3774 ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003775 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003776 }
3777
3778 @Override
3779 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3780 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3781 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09003782 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003783 }
3784
3785 @Override
lucasline117e2e2019-10-22 18:27:33 +08003786 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3787 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3788 EVENT_PROBE_STATUS_CHANGED,
3789 probesCompleted, probesSucceeded, new Integer(mNetId)));
3790 }
3791
3792 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003793 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3794 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3795 EVENT_CAPPORT_DATA_CHANGED,
3796 0, mNetId, data));
3797 }
3798
3799 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003800 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003801 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003802 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003803
3804 final PendingIntent pendingIntent;
3805 // Only the system server can register notifications with package "android"
3806 final long token = Binder.clearCallingIdentity();
3807 try {
paulhu7746e4e2020-06-09 19:07:03 +08003808 pendingIntent = PendingIntent.getBroadcast(
3809 mContext,
3810 0 /* requestCode */,
3811 intent,
3812 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003813 } finally {
3814 Binder.restoreCallingIdentity(token);
3815 }
3816 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3817 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09003818 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003819 }
3820
3821 @Override
3822 public void hideProvisioningNotification() {
3823 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09003824 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003825 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003826
3827 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003828 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003829 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08003830 }
3831
3832 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003833 public int getInterfaceVersion() {
3834 return this.VERSION;
3835 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09003836
3837 @Override
3838 public String getInterfaceHash() {
3839 return this.HASH;
3840 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003841 }
3842
Cody Kestingf1120be2020-08-03 18:01:40 -07003843 /**
3844 * Converts the given NetworkMonitor-specific validation result bitmask to a
3845 * ConnectivityDiagnostics-specific validation result int.
3846 */
3847 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
3848 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
3849 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
3850 }
3851 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
3852 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
3853 }
3854 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
3855 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
3856 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
3857 }
3858
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003859 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07003860 log("Data stall detected with methods: " + p.detectionMethod);
3861
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003862 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07003863 int detectionMethod = 0;
3864 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
3865 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
3866 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
3867 }
3868 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
3869 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
3870 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
3871 p.tcpMetricsCollectionPeriodMillis);
3872 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003873 }
3874
Cody Kestingf53a0752020-04-15 12:33:28 -07003875 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003876 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08003877 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07003878
3879 // NetworkStateTrackerHandler currently doesn't take any actions based on data
3880 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
3881 // the cost of going through two handlers.
3882 mConnectivityDiagnosticsHandler.sendMessage(msg);
3883 }
3884
Cody Kestingb37958e2020-05-15 10:36:01 -07003885 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
3886 return (p.detectionMethod & detectionMethod) != 0;
3887 }
3888
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003889 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
3890 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07003891 }
3892
Erik Klinea73af002018-06-26 18:53:43 +09003893 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
3894 if (nai == null) return;
3895 // If the Private DNS mode is opportunistic, reprogram the DNS servers
3896 // in order to restart a validation pass from within netd.
3897 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3898 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003899 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09003900 }
3901 }
3902
Erik Kline31b4a9e2018-01-11 21:07:29 +09003903 private void handlePrivateDnsSettingsChanged() {
3904 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3905
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003906 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07003907 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003908 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05003909 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3910 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09003911 }
3912 }
3913
Erik Kline9a62f012018-03-21 07:18:33 -07003914 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
3915 // Private DNS only ever applies to networks that might provide
3916 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003917 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09003918
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003919 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07003920 // schedule DNS resolutions. If a DNS resolution is required the
3921 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09003922 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07003923
3924 // With Private DNS bypass support, we can proceed to update the
3925 // Private DNS config immediately, even if we're in strict mode
3926 // and have not yet resolved the provider name into a set of IPs.
3927 updatePrivateDns(nai, cfg);
3928 }
3929
3930 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
3931 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003932 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09003933 }
3934
dalyk1720e542018-03-05 12:42:22 -05003935 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
3936 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
3937 if (nai == null) {
3938 return;
3939 }
3940 mDnsManager.updatePrivateDnsValidation(update);
3941 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3942 }
3943
paulhu7c0a2e62021-01-08 00:51:49 +08003944 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003945 int prefixLength) {
3946 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
3947 if (nai == null) return;
3948
paulhu7c0a2e62021-01-08 00:51:49 +08003949 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
3950 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003951
3952 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08003953 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003954 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003955 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003956 prefixLength);
3957 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003958 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003959 return;
3960 }
3961 }
3962
Lorenzo Colittid523d142020-04-01 20:16:30 +09003963 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003964 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3965 }
3966
Hai Shalome58bdc62021-01-11 18:45:34 -08003967 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003968 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08003969 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003970 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
3971 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3972 }
3973
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003974 /**
junyulai2b6f0c22021-02-03 20:15:30 +08003975 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003976 * @param nai the agent info to update
3977 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08003978 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003979 */
junyulai2b6f0c22021-02-03 20:15:30 +08003980 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
3981 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
3982 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003983 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08003984 // one lingered request, set inactive.
3985 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08003986 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08003987 if (DBG) log("Unsetting inactive " + nai.toShortString());
3988 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003989 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08003990 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003991 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08003992 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
3993 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003994 }
junyulai2b6f0c22021-02-03 20:15:30 +08003995 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003996 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003997 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003998 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003999 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004000 }
4001
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004002 private void handleNetworkAgentRegistered(Message msg) {
4003 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4004 if (!mNetworkAgentInfos.contains(nai)) {
4005 return;
4006 }
4007
4008 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4009 if (VDBG) log("NetworkAgent registered");
4010 } else {
4011 loge("Error connecting NetworkAgent");
4012 mNetworkAgentInfos.remove(nai);
4013 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004014 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004015 synchronized (mNetworkForNetId) {
4016 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004017 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004018 mNetIdManager.releaseNetId(nai.network.getNetId());
4019 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004020 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004021 }
4022 }
4023 }
Paul Jensend5f53392014-11-25 15:26:53 -05004024
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004025 private void handleNetworkAgentDisconnected(Message msg) {
4026 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004027 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004028 }
4029
Chalard Jeand9fffc32018-05-11 20:19:20 +09004030 // Destroys a network, remove references to it from the internal state managed by
4031 // ConnectivityService, free its interfaces and clean up.
4032 // Must be called on the Handler thread.
4033 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004034 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004035
4036 if (!mNetworkAgentInfos.contains(nai)) return;
4037
Chalard Jeand9fffc32018-05-11 20:19:20 +09004038 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004039 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004040 }
lucaslinb25c9a62019-02-12 15:30:13 +08004041 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004042 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004043 // A network agent has disconnected.
4044 // TODO - if we move the logic to the network agent (have them disconnect
4045 // because they lost all their requests or because their score isn't good)
4046 // then they would disconnect organically, report their new state and then
4047 // disconnect the channel.
4048 if (nai.networkInfo.isConnected()) {
4049 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4050 null, null);
4051 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004052 final boolean wasDefault = isDefaultNetwork(nai);
4053 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004054 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004055 }
4056 notifyIfacesChangedForNetworkStats();
4057 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4058 // by other networks that are already connected. Perhaps that can be done by
4059 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4060 // of rematchAllNetworksAndRequests
4061 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004062 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004063
4064 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004065 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4066 // Disable wakeup packet monitoring for each interface.
4067 wakeupModifyInterface(iface, nai.networkCapabilities, false);
4068 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004069 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004070 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004071 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004072 synchronized (mNetworkForNetId) {
4073 // Remove the NetworkAgent, but don't mark the netId as
4074 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004075 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004076 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004077 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004078 // Remove all previously satisfied requests.
4079 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004080 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004081 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004082 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004083 if (currentNetwork != null
4084 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004085 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004086 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4087 // rematch not to keep disconnected agents instead of setting it here ; this
4088 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004089 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004090 for (final NetworkOfferInfo noi : mNetworkOffers) {
4091 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004092 }
James Mattise3ef1912020-12-20 11:09:58 -08004093
Chalard Jean5b409c72021-02-04 13:12:59 +09004094 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004095 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004096 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004097 // network, because while incorrect this is the closest to the old (also
4098 // incorrect) behavior.
4099 mNetworkActivityTracker.updateDataActivityTracking(
4100 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004101 ensureNetworkTransitionWakelock(nai.toShortString());
4102 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004103 }
4104 }
junyulai2b6f0c22021-02-03 20:15:30 +08004105 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004106 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004107 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004108 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004109 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004110 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004111 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004112
4113 // Immediate teardown.
4114 if (nai.teardownDelayMs == 0) {
4115 destroyNetwork(nai);
4116 return;
4117 }
4118
4119 // Delayed teardown.
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304120 if (nai.created) {
4121 try {
4122 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4123 } catch (RemoteException e) {
4124 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4125 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004126 }
4127 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4128 }
4129
4130 private void destroyNetwork(NetworkAgentInfo nai) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004131 if (nai.created) {
4132 // Tell netd to clean up the configuration for this network
4133 // (routing rules, DNS, etc).
4134 // This may be slow as it requires a lot of netd shelling out to ip and
4135 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004136 // after we've rematched networks with requests (which might change the default
4137 // network or service a new request from an app), so network traffic isn't interrupted
4138 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004139 destroyNativeNetwork(nai);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004140 mDnsManager.removeNetwork(nai.network);
4141 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004142 mNetIdManager.releaseNetId(nai.network.getNetId());
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004143 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004144 }
4145
Ken Chen6df7a902021-04-09 15:08:42 +08004146 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004147 try {
4148 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004149 final NativeNetworkConfig config;
4150 if (nai.isVPN()) {
4151 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004152 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004153 return false;
4154 }
4155 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4156 INetd.PERMISSION_NONE,
4157 (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass),
Chiachang Wang9164c102022-01-13 10:54:32 +08004158 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004159 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004160 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
4161 getNetworkPermission(nai.networkCapabilities), /*secure=*/ false,
Chiachang Wangbf6b8792022-01-11 10:48:07 +08004162 VpnManager.TYPE_VPN_NONE, /*excludeLocalRoutes=*/ false);
Luke Huangfdd11f82019-04-09 18:41:49 +08004163 }
Ken Chen6df7a902021-04-09 15:08:42 +08004164 mNetd.networkCreate(config);
4165 mDnsResolver.createNetworkCache(nai.network.getNetId());
4166 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4167 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004168 return true;
4169 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004170 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004171 return false;
4172 }
4173 }
4174
Ken Chen6df7a902021-04-09 15:08:42 +08004175 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004176 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004177 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004178 } catch (RemoteException | ServiceSpecificException e) {
4179 loge("Exception destroying network(networkDestroy): " + e);
4180 }
4181 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004182 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004183 } catch (RemoteException | ServiceSpecificException e) {
4184 loge("Exception destroying network: " + e);
4185 }
4186 }
4187
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004188 // If this method proves to be too slow then we can maintain a separate
4189 // pendingIntent => NetworkRequestInfo map.
4190 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4191 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004192 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4193 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4194 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004195 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004196 return entry.getValue();
4197 }
4198 }
4199 return null;
4200 }
4201
Chalard Jean524f0b12021-10-25 21:11:56 +09004202 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4203 if (SdkLevel.isAtLeastT()) {
4204 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4205 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4206 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4207 // bug is fixed.
4208 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004209 throw new IllegalStateException("This NRI is already registered. New : " + nri
4210 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004211 }
4212 }
4213 }
4214 }
4215
Chalard Jeanac9ace02022-01-26 16:54:05 +09004216 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
4217 @NonNull final NetworkCapabilities caps) {
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004218 if (SdkLevel.isAtLeastT() && mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004219 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
4220 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004221 }
4222 return false;
4223 }
4224
James Mattisf7027322020-12-13 16:28:14 -08004225 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004226 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004227 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4228 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4229 final NetworkRequestInfo existingRequest =
4230 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004231 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004232 if (DBG) {
4233 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4234 + nri.mRequests.get(0) + " because their intents matched.");
4235 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004236 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004237 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004238 }
Erik Kline05f2b402015-04-30 12:58:40 +09004239 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004240 }
4241
James Mattisf7027322020-12-13 16:28:14 -08004242 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004243 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004244 }
4245
James Mattis3ce3d3c2021-02-09 18:18:28 -08004246 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004247 ensureRunningOnConnectivityServiceThread();
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004248 NetworkRequest requestToBeReleased = null;
James Mattis45d81842021-01-10 14:24:24 -08004249 for (final NetworkRequestInfo nri : nris) {
4250 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004251 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004252 for (final NetworkRequest req : nri.mRequests) {
4253 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004254 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004255 if (req.isListen()) {
4256 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4257 if (req.networkCapabilities.hasSignalStrength()
4258 && network.satisfiesImmutableCapabilitiesOf(req)) {
4259 updateSignalStrengthThresholds(network, "REGISTER", req);
4260 }
James Mattisf7027322020-12-13 16:28:14 -08004261 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004262 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004263 if (req.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004264 if (!hasCarrierPrivilegeForNetworkCaps(nri.mUid, req.networkCapabilities)
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004265 && !checkConnectivityRestrictedNetworksPermission(
4266 nri.mPid, nri.mUid)) {
4267 requestToBeReleased = req;
4268 }
4269 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004270 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004271
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004272 // If this NRI has a satisfier already, it is replacing an older request that
4273 // has been removed. Track it.
4274 final NetworkRequest activeRequest = nri.getActiveRequest();
4275 if (null != activeRequest) {
4276 // If there is an active request, then for sure there is a satisfier.
4277 nri.getSatisfier().addRequest(activeRequest);
4278 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004279 }
James Mattisf7027322020-12-13 16:28:14 -08004280
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004281 if (requestToBeReleased != null) {
4282 releaseNetworkRequestAndCallOnUnavailable(requestToBeReleased);
4283 return;
4284 }
4285
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004286 if (mFlags.noRematchAllRequestsOnRegister()) {
4287 rematchNetworksAndRequests(nris);
4288 } else {
4289 rematchAllNetworksAndRequests();
4290 }
James Mattis45d81842021-01-10 14:24:24 -08004291
Chalard Jean0354d8c2021-01-12 10:58:56 +09004292 // Requests that have not been matched to a network will not have been sent to the
4293 // providers, because the old satisfier and the new satisfier are the same (null in this
4294 // case). Send these requests to the providers.
4295 for (final NetworkRequestInfo nri : nris) {
4296 for (final NetworkOfferInfo noi : mNetworkOffers) {
4297 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004298 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004299 }
4300 }
4301
James Mattisf7027322020-12-13 16:28:14 -08004302 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4303 final int callingUid) {
4304 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004305 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004306 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4307 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4308 handleReleaseNetworkRequest(
4309 nri.mRequests.get(0),
4310 callingUid,
4311 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004312 }
4313 }
4314
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004315 // Determines whether the network is the best (or could become the best, if it validated), for
4316 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4317 // on the value of reason:
4318 //
4319 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4320 // then it should be torn down.
4321 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4322 // then it should be lingered.
4323 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004324 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004325
4326 if (!nai.everConnected || nai.isVPN() || nai.isInactive()
4327 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4328 return false;
4329 }
4330
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004331 final int numRequests;
4332 switch (reason) {
4333 case TEARDOWN:
4334 numRequests = nai.numRequestNetworkRequests();
4335 break;
4336 case LINGER:
4337 numRequests = nai.numForegroundNetworkRequests();
4338 break;
4339 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004340 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004341 return true;
4342 }
4343
Chalard Jean947acd42021-03-08 22:29:27 +09004344 if (numRequests > 0) return false;
4345
Paul Jensende49eb12015-06-25 15:30:08 -04004346 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004347 if (reason == UnneededFor.LINGER
4348 && !nri.isMultilayerRequest()
4349 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004350 // Background requests don't affect lingering.
4351 continue;
4352 }
4353
James Mattis3d229892020-11-16 16:46:28 -08004354 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004355 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004356 }
4357 }
Paul Jensende49eb12015-06-25 15:30:08 -04004358 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004359 }
4360
James Mattis3d229892020-11-16 16:46:28 -08004361 private boolean isNetworkPotentialSatisfier(
4362 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4363 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004364 // request, return immediately. For multilayer requests, check to see if any of the
4365 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004366 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4367 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004368 return false;
4369 }
4370 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004371 // This multilayer listen request is satisfied therefore no further requests need to be
4372 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004373 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004374 return false;
4375 }
James Mattis3d229892020-11-16 16:46:28 -08004376 // As non-multilayer listen requests have already returned, the below would only happen
4377 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004378 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004379 continue;
4380 }
4381 // If this Network is already the highest scoring Network for a request, or if
4382 // there is hope for it to become one if it validated, then it is needed.
4383 if (candidate.satisfies(req)) {
4384 // As soon as a network is found that satisfies a request, return. Specifically for
4385 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4386 // is important so as to not evaluate lower priority requests further in
4387 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004388 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4389 ? nri.getSatisfier() : null;
4390 // Note that this catches two important cases:
4391 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4392 // is currently satisfying the request. This is desirable when
4393 // cellular ends up validating but WiFi does not.
4394 // 2. Unvalidated WiFi will not be reaped when validated cellular
4395 // is currently satisfying the request. This is desirable when
4396 // WiFi ends up validating and out scoring cellular.
4397 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004398 }
4399 }
4400
4401 return false;
4402 }
4403
Erik Kline0c04b742016-07-07 16:50:58 +09004404 private NetworkRequestInfo getNriForAppRequest(
4405 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004406 // Looking up the app passed param request in mRequests isn't possible since it may return
4407 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4408 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004409 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4410 // to avoid potential race conditions when validating a package->uid mapping when sending
4411 // the callback on the very low-chance that an application shuts down prior to the callback
4412 // being sent.
4413 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4414 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004415
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004416 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004417 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004418 log(String.format("UID %d attempted to %s for unowned request %s",
4419 callingUid, requestedOperation, nri));
4420 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004421 }
Erik Kline0c04b742016-07-07 16:50:58 +09004422 }
4423
4424 return nri;
4425 }
4426
James Mattisf7027322020-12-13 16:28:14 -08004427 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4428 final String callingMethod) {
4429 if (nri.isMultilayerRequest()) {
4430 throw new IllegalStateException(
4431 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004432 }
4433 }
4434
James Mattisf7027322020-12-13 16:28:14 -08004435 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004436 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004437 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4438 // single NetworkRequest and thus does not apply to multilayer requests.
4439 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4440 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004441 return;
4442 }
James Mattis2516da32021-01-31 17:06:19 -08004443 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004444 return;
4445 }
James Mattisf7027322020-12-13 16:28:14 -08004446 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4447 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004448 }
4449 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004450 callCallbackForRequest(
4451 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004452 }
4453
James Mattisf7027322020-12-13 16:28:14 -08004454 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4455 final int callingUid,
4456 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004457 final NetworkRequestInfo nri =
4458 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4459 if (nri == null) {
4460 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004461 }
James Mattisf7027322020-12-13 16:28:14 -08004462 if (VDBG || (DBG && request.isRequest())) {
4463 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004464 }
4465 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004466 if (callOnUnavailable) {
4467 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4468 }
Erik Kline155a59a2015-11-25 12:49:38 +09004469 }
Erik Kline0c04b742016-07-07 16:50:58 +09004470
James Mattisa076c532020-12-02 14:12:41 -08004471 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004472 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004473 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004474 if (null == mNetworkRequests.remove(req)) {
4475 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4476 continue;
4477 }
James Mattisa076c532020-12-02 14:12:41 -08004478 if (req.isListen()) {
4479 removeListenRequestFromNetworks(req);
4480 }
4481 }
James Mattis8f036802021-06-20 16:26:01 -07004482 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004483 if (mDefaultNetworkRequests.remove(nri)) {
4484 // If this request was one of the defaults, then the UID rules need to be updated
4485 // WARNING : if the app(s) for which this network request is the default are doing
4486 // traffic, this will kill their connected sockets, even if an equivalent request
4487 // is going to be reinstated right away ; unconnected traffic will go on the default
4488 // until the new default is set, which will happen very soon.
4489 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4490 // remove ranges for those requests that won't have a replacement
4491 final NetworkAgentInfo satisfier = nri.getSatisfier();
4492 if (null != satisfier) {
4493 try {
paulhu0e79d952021-06-09 16:11:35 +08004494 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4495 satisfier.network.getNetId(),
4496 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004497 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004498 } catch (RemoteException e) {
4499 loge("Exception setting network preference default network", e);
4500 }
4501 }
4502 }
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09004503 nri.decrementRequestCount();
Erik Kline0c04b742016-07-07 16:50:58 +09004504 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004505 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004506
4507 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004508 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004509 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004510 }
4511 }
4512
Chalard Jean0354d8c2021-01-12 10:58:56 +09004513 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4514 // needed for this offer.
4515 for (final NetworkOfferInfo noi : mNetworkOffers) {
4516 for (final NetworkRequest req : nri.mRequests) {
4517 if (req.isRequest() && noi.offer.neededFor(req)) {
4518 noi.offer.onNetworkUnneeded(req);
4519 }
4520 }
4521 }
James Mattisa076c532020-12-02 14:12:41 -08004522 }
4523
James Mattis3ce3d3c2021-02-09 18:18:28 -08004524 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4525 for (final NetworkRequestInfo nri : nris) {
4526 if (mDefaultRequest == nri) {
4527 // Make sure we never remove the default request.
4528 continue;
4529 }
4530 handleRemoveNetworkRequest(nri);
4531 }
4532 }
4533
James Mattisa076c532020-12-02 14:12:41 -08004534 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4535 // listens don't have a singular affected Network. Check all networks to see
4536 // if this listen request applies and remove it.
4537 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4538 nai.removeRequest(req.requestId);
4539 if (req.networkCapabilities.hasSignalStrength()
4540 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4541 updateSignalStrengthThresholds(nai, "RELEASE", req);
4542 }
4543 }
4544 }
4545
4546 /**
4547 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4548 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4549 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4550 */
4551 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4552 boolean wasKept = false;
4553 final NetworkAgentInfo nai = nri.getSatisfier();
4554 if (nai != null) {
4555 final int requestLegacyType = nri.getActiveRequest().legacyType;
4556 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4557 nai.removeRequest(nri.getActiveRequest().requestId);
4558 if (VDBG || DDBG) {
4559 log(" Removing from current network " + nai.toShortString()
4560 + ", leaving " + nai.numNetworkRequests() + " requests.");
4561 }
4562 // If there are still lingered requests on this network, don't tear it down,
4563 // but resume lingering instead.
4564 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004565 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004566 notifyNetworkLosing(nai, now);
4567 }
4568 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4569 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4570 teardownUnneededNetwork(nai);
4571 } else {
4572 wasKept = true;
4573 }
James Mattisa076c532020-12-02 14:12:41 -08004574 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4575 // Went from foreground to background.
4576 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004577 }
4578
Erik Kline0c04b742016-07-07 16:50:58 +09004579 // Maintain the illusion. When this request arrived, we might have pretended
4580 // that a network connected to serve it, even though the network was already
4581 // connected. Now that this request has gone away, we might have to pretend
4582 // that the network disconnected. LegacyTypeTracker will generate that
4583 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004584 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004585 boolean doRemove = true;
4586 if (wasKept) {
4587 // check if any of the remaining requests for this network are for the
4588 // same legacy type - if so, don't remove the nai
4589 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4590 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004591 if (otherRequest.legacyType == requestLegacyType
4592 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004593 if (DBG) log(" still have other legacy request - leaving");
4594 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004595 }
4596 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004597 }
4598
Erik Kline0c04b742016-07-07 16:50:58 +09004599 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004600 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004601 }
4602 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004603 }
4604 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004605
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004606 private PerUidCounter getRequestCounter(NetworkRequestInfo nri) {
4607 return checkAnyPermissionOf(
4608 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4609 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4610 }
4611
Lorenzo Colittid6459092016-07-04 12:55:44 +09004612 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004613 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004614 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004615 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004616 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004617 }
4618
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004619 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004620 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4621 enforceNetworkStackSettingsOrSetup();
4622 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4623 encodeBool(accept), encodeBool(always), network));
4624 }
4625
4626 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004627 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004628 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004629 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4630 }
4631
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004632 @Override
4633 public void setTestAllowBadWifiUntil(long timeMs) {
4634 enforceSettingsPermission();
4635 if (!Build.isDebuggable()) {
4636 throw new IllegalStateException("Does not support in non-debuggable build");
4637 }
4638
4639 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4640 throw new IllegalArgumentException("It should not exceed "
4641 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4642 }
4643
4644 mHandler.sendMessage(
4645 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
4646 }
4647
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004648 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4649 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4650 " accept=" + accept + " always=" + always);
4651
4652 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4653 if (nai == null) {
4654 // Nothing to do.
4655 return;
4656 }
4657
4658 if (nai.everValidated) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004659 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004660 return;
4661 }
4662
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004663 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08004664 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004665 }
4666
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004667 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4668 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004669 // If network becomes partial connectivity and user already accepted to use this
4670 // network, we should respect the user's option and don't need to popup the
4671 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004672 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004673 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004674 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004675 }
4676
4677 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004678 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004679 }
4680
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004681 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04004682 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004683 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09004684 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04004685 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004686 }
4687
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004688 }
4689
lucaslin2240ef62019-03-12 13:08:03 +08004690 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4691 boolean always) {
4692 if (DBG) {
4693 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4694 + " always=" + always);
4695 }
4696
4697 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4698 if (nai == null) {
4699 // Nothing to do.
4700 return;
4701 }
4702
4703 if (nai.lastValidated) {
4704 // The network validated while the dialog box was up. Take no action.
4705 return;
4706 }
4707
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004708 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4709 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004710 }
4711
4712 // TODO: Use the current design or save the user choice into IpMemoryStore.
4713 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004714 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08004715 }
4716
4717 if (!accept) {
4718 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004719 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08004720 // Tear down the network.
4721 teardownUnneededNetwork(nai);
4722 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08004723 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4724 // result in a partial connectivity result which will be processed by
4725 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08004726 //
4727 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4728 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004729 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08004730 }
4731 }
4732
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004733 private void handleSetAvoidUnvalidated(Network network) {
4734 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4735 if (nai == null || nai.lastValidated) {
4736 // Nothing to do. The network either disconnected or revalidated.
4737 return;
4738 }
4739 if (!nai.avoidUnvalidated) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004740 nai.avoidUnvalidated = true;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004741 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004742 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004743 }
4744 }
4745
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004746 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09004747 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004748 mHandler.sendMessageDelayed(
4749 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4750 PROMPT_UNVALIDATED_DELAY_MS);
4751 }
4752
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004753 @Override
4754 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08004755 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004756 mHandler.post(() -> {
4757 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4758 if (nai == null) return;
4759 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004760 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004761 });
4762 }
4763
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004764 /**
4765 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4766 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004767 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004768 * @param appExtras Bundle to use as intent extras for the captive portal application.
4769 * Must be treated as opaque to avoid preventing the captive portal app to
4770 * update its arguments.
4771 */
4772 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004773 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08004774 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4775 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004776
4777 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4778 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004779 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4780 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004781 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4782
lucaslin75ff7022020-12-17 04:14:35 +08004783 final long token = Binder.clearCallingIdentity();
4784 try {
4785 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4786 } finally {
4787 Binder.restoreCallingIdentity(token);
4788 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004789 }
4790
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004791 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4792 private final Network mNetwork;
4793
4794 private CaptivePortalImpl(Network network) {
4795 mNetwork = network;
4796 }
4797
4798 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004799 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004800 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
4801 enforceSettingsPermission();
4802 }
4803
Chiachang Wang938bfba2020-01-09 13:50:55 +08004804 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004805 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004806 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004807 }
4808
4809 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08004810 public void appRequest(final int request) {
4811 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4812 if (nm == null) return;
4813
4814 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08004815 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09004816 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08004817 }
4818 }
4819
4820 @Nullable
4821 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
4822 // getNetworkAgentInfoForNetwork is thread-safe
4823 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4824 if (nai == null) return null;
4825
4826 // nai.networkMonitor() is thread-safe
4827 return nai.networkMonitor();
4828 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004829 }
4830
Hugo Benichic9048bc2016-09-14 23:23:08 +00004831 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004832 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09004833 }
4834
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004835 /**
4836 * Return whether the device should maintain continuous, working connectivity by switching away
4837 * from WiFi networks having no connectivity.
4838 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
4839 */
4840 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004841 if (!checkNetworkStackPermission()) {
4842 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
4843 }
4844 return avoidBadWifi();
4845 }
4846
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004847 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09004848 ensureRunningOnConnectivityServiceThread();
4849 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004850 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09004851 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004852 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09004853 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
4854 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
4855 for (final NetworkOfferInfo noi : offersToUpdate) {
4856 updateOfferScore(noi.offer);
4857 }
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004858 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004859 }
4860
Erik Kline95ecfee2016-10-02 18:02:14 +09004861 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004862 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004863 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004864 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004865 if (!configRestrict) {
4866 pw.println("Bad Wi-Fi avoidance: unrestricted");
4867 return;
4868 }
4869
4870 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
4871 pw.increaseIndent();
4872 pw.println("Config restrict: " + configRestrict);
4873
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004874 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004875 String description;
4876 // Can't use a switch statement because strings are legal case labels, but null is not.
4877 if ("0".equals(value)) {
4878 description = "get stuck";
4879 } else if (value == null) {
4880 description = "prompt";
4881 } else if ("1".equals(value)) {
4882 description = "avoid";
4883 } else {
4884 description = value + " (?)";
4885 }
4886 pw.println("User setting: " + description);
4887 pw.println("Network overrides:");
4888 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09004889 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004890 if (nai.avoidUnvalidated) {
Chalard Jean49707572019-12-10 21:07:02 +09004891 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004892 }
4893 }
4894 pw.decreaseIndent();
4895 pw.decreaseIndent();
4896 }
4897
paulhu7746e4e2020-06-09 19:07:03 +08004898 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
4899 // unify the method.
4900 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
4901 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
4902 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
4903 return settingsComponent != null
4904 ? settingsComponent.getPackageName() : "com.android.settings";
4905 }
4906
lucaslinb1e8e382019-01-24 15:55:30 +08004907 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004908 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004909 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004910 switch (type) {
4911 case NO_INTERNET:
4912 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004913 // High priority because it is only displayed for explicitly selected networks.
4914 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004915 break;
lucasline117e2e2019-10-22 18:27:33 +08004916 case PRIVATE_DNS_BROKEN:
4917 action = Settings.ACTION_WIRELESS_SETTINGS;
4918 // High priority because we should let user know why there is no internet.
4919 highPriority = true;
4920 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004921 case LOST_INTERNET:
4922 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004923 // High priority because it could help the user avoid unexpected data usage.
4924 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004925 break;
lucaslin2240ef62019-03-12 13:08:03 +08004926 case PARTIAL_CONNECTIVITY:
4927 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004928 // Don't bother the user with a high-priority notification if the network was not
4929 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004930 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08004931 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004932 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004933 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004934 return;
4935 }
4936
4937 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08004938 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08004939 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08004940 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08004941 // Some OEMs have their own Settings package. Thus, need to get the current using
4942 // Settings package name instead of just use default name "com.android.settings".
4943 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
4944 intent.setClassName(settingsPkgName,
4945 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08004946 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004947
paulhu2af50222020-10-11 22:52:27 +08004948 PendingIntent pendingIntent = PendingIntent.getActivity(
4949 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08004950 0 /* requestCode */,
4951 intent,
paulhu2af50222020-10-11 22:52:27 +08004952 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004953
Serik Beketayevec8ad212020-12-07 22:43:07 -08004954 mNotifier.showNotification(
4955 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004956 }
4957
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004958 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
4959 // Don't prompt if the network is validated, and don't prompt on captive portals
4960 // because we're already prompting the user to sign in.
4961 if (nai.everValidated || nai.everCaptivePortalDetected) {
4962 return false;
4963 }
4964
4965 // If a network has partial connectivity, always prompt unless the user has already accepted
4966 // partial connectivity and selected don't ask again. This ensures that if the device
4967 // automatically connects to a network that has partial Internet access, the user will
4968 // always be able to use it, either because they've already chosen "don't ask again" or
4969 // because we have prompt them.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004970 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004971 return true;
4972 }
4973
4974 // If a network has no Internet access, only prompt if the network was explicitly selected
4975 // and if the user has not already told us to use the network regardless of whether it
4976 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004977 if (nai.networkAgentConfig.explicitlySelected
4978 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004979 return true;
4980 }
4981
4982 return false;
4983 }
4984
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004985 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09004986 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004987 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4988
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004989 if (nai == null || !shouldPromptUnvalidated(nai)) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004990 return;
4991 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09004992
4993 // Stop automatically reconnecting to this network in the future. Automatically connecting
4994 // to a network that provides no or limited connectivity is not useful, because the user
4995 // cannot use that network except through the notification shown by this method, and the
4996 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004997 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09004998
lucaslin2240ef62019-03-12 13:08:03 +08004999 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
5000 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
5001 // popup the notification immediately when the network is partial connectivity.
5002 if (nai.partialConnectivity) {
lucasline0118ab2019-03-21 11:59:22 +08005003 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005004 } else {
5005 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5006 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005007 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005008
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005009 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5010 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005011 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005012
lucaslin2240ef62019-03-12 13:08:03 +08005013 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5014 return;
5015 }
5016
5017 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005018 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005019 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005020 }
5021
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005022 @Override
5023 public int getMultipathPreference(Network network) {
5024 enforceAccessPermission();
5025
5026 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005027 if (nai != null && nai.networkCapabilities
5028 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005029 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5030 }
5031
Aaron Huang9a57acf2020-12-08 10:03:29 +08005032 final NetworkPolicyManager netPolicyManager =
5033 mContext.getSystemService(NetworkPolicyManager.class);
5034
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005035 final long token = Binder.clearCallingIdentity();
5036 final int networkPreference;
5037 try {
5038 networkPreference = netPolicyManager.getMultipathPreference(network);
5039 } finally {
5040 Binder.restoreCallingIdentity(token);
5041 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005042 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005043 return networkPreference;
5044 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005045 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5046 }
5047
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005048 @Override
5049 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005050 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005051 }
5052
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005053 private class InternalHandler extends Handler {
5054 public InternalHandler(Looper looper) {
5055 super(looper);
5056 }
5057
5058 @Override
5059 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005060 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005061 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005062 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005063 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005064 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005065 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005066 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005067 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005068 break;
5069 }
Jason Monka69f1b02013-10-10 14:02:51 -04005070 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005071 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5072 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005073 break;
5074 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005075 case EVENT_REGISTER_NETWORK_PROVIDER: {
5076 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005077 break;
5078 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005079 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5080 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005081 break;
5082 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005083 case EVENT_REGISTER_NETWORK_OFFER: {
5084 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5085 break;
5086 }
5087 case EVENT_UNREGISTER_NETWORK_OFFER: {
5088 final NetworkOfferInfo offer =
5089 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5090 if (null != offer) {
5091 handleUnregisterNetworkOffer(offer);
5092 }
5093 break;
5094 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005095 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005096 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5097 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5098 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005099 break;
5100 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005101 case EVENT_REGISTER_NETWORK_REQUEST:
5102 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005103 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005104 break;
5105 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005106 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5107 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005108 handleRegisterNetworkRequestWithIntent(msg);
5109 break;
5110 }
Erik Kline155a59a2015-11-25 12:49:38 +09005111 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5112 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5113 handleTimedOutNetworkRequest(nri);
5114 break;
5115 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005116 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5117 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5118 break;
5119 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005120 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005121 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5122 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005123 break;
5124 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005125 case EVENT_RELEASE_NETWORK_REQUEST_AND_CALL_UNAVAILABLE: {
5126 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5127 /* callOnUnavailable */ true);
5128 break;
5129 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005130 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005131 Network network = (Network) msg.obj;
5132 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005133 break;
5134 }
lucaslin2240ef62019-03-12 13:08:03 +08005135 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5136 Network network = (Network) msg.obj;
5137 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5138 toBool(msg.arg2));
5139 break;
5140 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005141 case EVENT_SET_AVOID_UNVALIDATED: {
5142 handleSetAvoidUnvalidated((Network) msg.obj);
5143 break;
5144 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005145 case EVENT_PROMPT_UNVALIDATED: {
5146 handlePromptUnvalidated((Network) msg.obj);
5147 break;
5148 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005149 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5150 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005151 break;
5152 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005153 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005154 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005155 mKeepaliveTracker.handleStartKeepalive(msg);
5156 break;
5157 }
5158 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005159 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005160 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5161 int slot = msg.arg1;
5162 int reason = msg.arg2;
5163 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
5164 break;
5165 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005166 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5167 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5168 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005169 break;
5170 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005171 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5172 handlePrivateDnsSettingsChanged();
5173 break;
dalyk1720e542018-03-05 12:42:22 -05005174 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5175 handlePrivateDnsValidationUpdate(
5176 (PrivateDnsValidationUpdate) msg.obj);
5177 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005178 case EVENT_UID_BLOCKED_REASON_CHANGED:
5179 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005180 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005181 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5182 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5183 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005184 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005185 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5186 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005187 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005188 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005189 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005190 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005191 final Pair<List<ProfileNetworkPreferenceList.Preference>,
5192 IOnCompleteListener> arg =
5193 (Pair<List<ProfileNetworkPreferenceList.Preference>,
5194 IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005195 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005196 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005197 }
lucaslin1193a5d2021-01-21 02:04:15 +08005198 case EVENT_REPORT_NETWORK_ACTIVITY:
5199 mNetworkActivityTracker.handleReportNetworkActivity();
5200 break;
paulhu51f77dc2021-06-07 02:34:20 +00005201 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5202 handleMobileDataPreferredUidsChanged();
5203 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005204 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5205 final long timeMs = ((Long) msg.obj).longValue();
5206 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5207 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005208 }
5209 }
5210 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005211
Lorenzo Colittid6459092016-07-04 12:55:44 +09005212 @Override
markchien5776f962019-12-16 20:15:20 +08005213 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005214 public int getLastTetherError(String iface) {
markchien5776f962019-12-16 20:15:20 +08005215 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5216 Context.TETHERING_SERVICE);
5217 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005218 }
5219
Lorenzo Colittid6459092016-07-04 12:55:44 +09005220 @Override
markchien5776f962019-12-16 20:15:20 +08005221 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005222 public String[] getTetherableIfaces() {
markchien5776f962019-12-16 20:15:20 +08005223 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5224 Context.TETHERING_SERVICE);
5225 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005226 }
5227
Lorenzo Colittid6459092016-07-04 12:55:44 +09005228 @Override
markchien5776f962019-12-16 20:15:20 +08005229 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005230 public String[] getTetheredIfaces() {
markchien5776f962019-12-16 20:15:20 +08005231 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5232 Context.TETHERING_SERVICE);
5233 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005234 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005235
markchien5776f962019-12-16 20:15:20 +08005236
Lorenzo Colittid6459092016-07-04 12:55:44 +09005237 @Override
markchien5776f962019-12-16 20:15:20 +08005238 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005239 public String[] getTetheringErroredIfaces() {
markchien5776f962019-12-16 20:15:20 +08005240 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5241 Context.TETHERING_SERVICE);
5242
5243 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005244 }
5245
Lorenzo Colittid6459092016-07-04 12:55:44 +09005246 @Override
markchien5776f962019-12-16 20:15:20 +08005247 @Deprecated
5248 public String[] getTetherableUsbRegexs() {
5249 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5250 Context.TETHERING_SERVICE);
5251
5252 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005253 }
5254
Udam Saini8f7d6a72017-06-07 12:06:28 -07005255 @Override
markchien5776f962019-12-16 20:15:20 +08005256 @Deprecated
5257 public String[] getTetherableWifiRegexs() {
5258 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5259 Context.TETHERING_SERVICE);
5260 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005261 }
5262
Robert Greenwalte0b00512014-07-02 09:59:16 -07005263 // Called when we lose the default network and have no replacement yet.
5264 // This will automatically be cleared after X seconds or a new default network
5265 // becomes CONNECTED, whichever happens first. The timer is started by the
5266 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005267 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005268 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005269 if (mNetTransitionWakeLock.isHeld()) {
5270 return;
5271 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005272 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005273 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5274 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005275 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005276 mWakelockLogs.log("ACQUIRE for " + forWhom);
5277 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005278 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005279 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005280 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005281 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005282
Hugo Benichi471b62a2017-03-30 23:18:10 +09005283 // Called when we gain a new default network to release the network transition wakelock in a
5284 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5285 // message is cancelled.
5286 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005287 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005288 if (!mNetTransitionWakeLock.isHeld()) {
5289 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005290 }
5291 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005292 // Cancel self timeout on wakelock hold.
5293 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5294 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5295 mHandler.sendMessageDelayed(msg, 1000);
5296 }
5297
5298 // Called when either message of ensureNetworkTransitionWakelock or
5299 // scheduleReleaseNetworkTransitionWakelock is processed.
5300 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5301 String event = eventName(eventId);
5302 synchronized (this) {
5303 if (!mNetTransitionWakeLock.isHeld()) {
5304 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005305 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005306 return;
5307 }
5308 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005309 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5310 mTotalWakelockDurationMs += lockDuration;
5311 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5312 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005313 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005314 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005315 }
5316
Robert Greenwalt986c7412010-09-08 15:24:47 -07005317 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005318 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005319 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005320 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005321 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005322 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005323 }
5324
Lorenzo Colittid6459092016-07-04 12:55:44 +09005325 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005326 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005327 enforceAccessPermission();
5328 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005329 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005330 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005331
5332 final NetworkAgentInfo nai;
5333 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005334 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005335 } else {
5336 nai = getNetworkAgentInfoForNetwork(network);
5337 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005338
5339 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005340 mHandler.obtainMessage(
5341 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005342 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005343
Hugo Benichid6b510a2017-04-06 17:22:18 +09005344 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005345 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005346 if (nai == null
5347 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005348 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005349 return;
5350 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005351 // Revalidate if the app report does not match our current validated state.
Hugo Benichie9d321b2017-04-06 16:01:44 +09005352 if (hasConnectivity == nai.lastValidated) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005353 mConnectivityDiagnosticsHandler.sendMessage(
5354 mConnectivityDiagnosticsHandler.obtainMessage(
5355 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5356 new ReportedNetworkConnectivityInfo(
5357 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005358 return;
5359 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005360 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005361 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005362 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005363 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005364 // Validating a network that has not yet connected could result in a call to
5365 // rematchNetworkAndRequests() which is not meant to work on such networks.
5366 if (!nai.everConnected) {
5367 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005368 }
paulhu7aeba372020-12-30 00:42:19 +08005369 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5370 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005371 return;
5372 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005373
5374 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5375 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5376 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5377 // completed.
5378 mConnectivityDiagnosticsHandler.sendMessage(
5379 mConnectivityDiagnosticsHandler.obtainMessage(
5380 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5381 new ReportedNetworkConnectivityInfo(
5382 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005383 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005384 }
5385
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005386 // TODO: call into netd.
5387 private boolean queryUserAccess(int uid, Network network) {
5388 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5389 if (nai == null) return false;
5390
5391 // Any UID can use its default network.
5392 if (nai == getDefaultNetworkForUid(uid)) return true;
5393
5394 // Privileged apps can use any network.
5395 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5396 return true;
5397 }
5398
5399 // An unprivileged UID can use a VPN iff the VPN applies to it.
5400 if (nai.isVPN()) {
5401 return nai.networkCapabilities.appliesToUid(uid);
5402 }
5403
5404 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5405 // sockets, i.e., if it is the owner.
5406 final NetworkAgentInfo vpn = getVpnForUid(uid);
5407 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5408 && uid != vpn.networkCapabilities.getOwnerUid()) {
5409 return false;
5410 }
5411
5412 // The UID's permission must be at least sufficient for the network. Since the restricted
5413 // permission was already checked above, that just leaves background networks.
5414 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5415 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5416 }
5417
5418 // Unrestricted network. Anyone gets to use it.
5419 return true;
5420 }
5421
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005422 /**
5423 * Returns information about the proxy a certain network is using. If given a null network, it
5424 * it will return the proxy for the bound network for the caller app or the default proxy if
5425 * none.
5426 *
5427 * @param network the network we want to get the proxy information for.
5428 * @return Proxy information if a network has a proxy configured, or otherwise null.
5429 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005430 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005431 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005432 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005433 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005434 if (network == null) {
5435 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005436 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005437 true);
5438 if (activeNetwork == null) {
5439 return null;
5440 }
5441 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005442 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005443 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5444 // caller may not have.
5445 return getLinkPropertiesProxyInfo(network);
5446 }
5447 // No proxy info available if the calling UID does not have network access.
5448 return null;
5449 }
5450
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005451
5452 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005453 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5454 if (nai == null) return null;
5455 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005456 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5457 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005458 }
5459 }
5460
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005461 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005462 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhudf23d662021-01-25 18:53:17 +08005463 PermissionUtils.enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005464 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005465 }
5466
Chalard Jean777e2e52018-06-07 18:02:37 +09005467 @Override
5468 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005469 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005470 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005471 }
5472
Jason Monk4d5e20f2014-04-25 15:00:09 -04005473 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005474 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005475 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005476 proxy = null;
5477 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005478 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005479 }
5480
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005481 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5482 // when any network changes proxy.
5483 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5484 // multi-network world where an app might be bound to a non-default network.
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005485 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensenc0618a62014-12-10 15:12:18 -05005486 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5487 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5488
Chalard Jean7d97afc2018-06-07 17:41:29 +09005489 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005490 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005491 }
5492 }
5493
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005494 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005495 final private HashMap<Uri, Integer> mUriEventMap;
5496 final private Context mContext;
5497 final private Handler mHandler;
5498
5499 SettingsObserver(Context context, Handler handler) {
5500 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005501 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005502 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005503 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005504 }
5505
Erik Kline05f2b402015-04-30 12:58:40 +09005506 void observe(Uri uri, int what) {
5507 mUriEventMap.put(uri, what);
5508 final ContentResolver resolver = mContext.getContentResolver();
5509 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005510 }
5511
5512 @Override
5513 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005514 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005515 }
5516
5517 @Override
5518 public void onChange(boolean selfChange, Uri uri) {
5519 final Integer what = mUriEventMap.get(uri);
5520 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005521 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005522 } else {
5523 loge("No matching event to send for URI=" + uri);
5524 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005525 }
5526 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005527
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005528 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005529 Log.d(TAG, s);
5530 }
5531
5532 private static void logw(String s) {
5533 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005534 }
5535
Daniel Brightf9e945b2020-06-15 16:10:01 -07005536 private static void logwtf(String s) {
5537 Log.wtf(TAG, s);
5538 }
5539
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005540 private static void logwtf(String s, Throwable t) {
5541 Log.wtf(TAG, s, t);
5542 }
5543
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005544 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005545 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005546 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005547
Hugo Benichi39621362017-02-11 17:04:43 +09005548 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005549 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005550 }
5551
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005552 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005553 * Return the information of all ongoing VPNs.
5554 *
5555 * <p>This method is used to update NetworkStatsService.
5556 *
5557 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08005558 */
junyulai2050bed2021-01-23 09:46:34 +08005559 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005560 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09005561 if (mLockdownEnabled) {
5562 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08005563 }
junyulai2050bed2021-01-23 09:46:34 +08005564 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005565 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08005566 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005567 if (info != null) {
5568 infoList.add(info);
5569 }
5570 }
junyulai2050bed2021-01-23 09:46:34 +08005571 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08005572 }
5573
5574 /**
5575 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00005576 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08005577 */
junyulai2050bed2021-01-23 09:46:34 +08005578 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005579 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08005580 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5581 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09005582 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5583 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5584 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08005585 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5586 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00005587 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00005588 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08005589 }
5590 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005591
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005592 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005593
5594 List<String> interfaces = new ArrayList<>();
5595 for (Network network : underlyingNetworks) {
5596 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5597 if (underlyingNai == null) continue;
5598 LinkProperties lp = underlyingNai.linkProperties;
5599 for (String iface : lp.getAllInterfaceNames()) {
5600 if (!TextUtils.isEmpty(iface)) {
5601 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00005602 }
5603 }
Benedict Wong34857f82019-06-12 17:46:15 +00005604 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005605
5606 if (interfaces.isEmpty()) return null;
5607
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005608 // Must be non-null or NetworkStatsService will crash.
5609 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5610 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08005611 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08005612 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005613
junyulai2050bed2021-01-23 09:46:34 +08005614 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5615 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08005616 }
5617
James Mattisd31bdfa2020-12-23 16:37:26 -08005618 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08005619 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5620 Network[] underlyingNetworks) {
5621 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005622 if (underlyingNetworks == null && defaultNetwork != null) {
5623 // null underlying networks means to track the default.
5624 underlyingNetworks = new Network[] { defaultNetwork };
5625 }
5626 return underlyingNetworks;
5627 }
5628
5629 // Returns true iff |network| is an underlying network of |nai|.
5630 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5631 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5632 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09005633 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08005634 final Network[] underlying = underlyingNetworksOrDefault(
5635 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005636 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005637 }
5638
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005639 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005640 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005641 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005642 * When underlying networks change, such networks may have to update capabilities to reflect
5643 * things like the metered bit, their transports, and so on. The capabilities are calculated
5644 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005645 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005646 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005647 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005648 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005649 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005650 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005651 }
5652 }
5653 }
5654
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005655 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5656 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5657 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5658 // a VPN is not up.
5659 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5660 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5661 for (UidRange range : blockedUidRanges) {
5662 if (range.contains(uid)) return true;
5663 }
5664 return false;
5665 }
5666
5667 @Override
5668 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08005669 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005670 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5671 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5672 }
5673
5674 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5675 if (DBG) {
5676 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5677 + Arrays.toString(ranges));
5678 }
5679 // Cannot use a Set since the list of UID ranges might contain duplicates.
5680 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5681 for (int i = 0; i < ranges.length; i++) {
5682 if (requireVpn) {
5683 newVpnBlockedUidRanges.add(ranges[i]);
5684 } else {
5685 newVpnBlockedUidRanges.remove(ranges[i]);
5686 }
5687 }
5688
5689 try {
5690 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5691 } catch (RemoteException | ServiceSpecificException e) {
5692 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5693 + Arrays.toString(ranges) + "): netd command failed: " + e);
5694 }
5695
5696 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5697 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00005698 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5699 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005700 }
5701
5702 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5703 }
5704
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07005705 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005706 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08005707 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005708 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01005709 }
5710
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005711 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5712 return mLockdownEnabled
5713 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5714 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00005715 }
5716
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005717 private NetworkAgentInfo getLegacyLockdownNai() {
5718 if (!mLockdownEnabled) {
5719 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005720 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005721 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005722 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5723 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005724
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005725 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005726 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5727 // a local variable. There is no need to make a copy because its contents cannot change.
5728 final Network[] underlying = nai.declaredUnderlyingNetworks;
5729 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005730 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005731 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005732
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005733 // The legacy lockdown VPN always uses the default network.
5734 // If the VPN's underlying network is no longer the current default network, it means that
5735 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005736 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5737 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005738 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005739 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005740 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005741 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005742
5743 return nai;
5744 };
5745
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005746 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5747 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5748 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005749 private DetailedState getLegacyLockdownState(DetailedState origState) {
5750 if (origState != DetailedState.CONNECTED) {
5751 return origState;
5752 }
5753 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5754 ? DetailedState.CONNECTING
5755 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005756 }
5757
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005758 private void filterForLegacyLockdown(NetworkInfo ni) {
5759 if (!mLockdownEnabled || !ni.isConnected()) return;
5760 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5761 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5762 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5763 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5764 // network, this time with a state of CONNECTED.
5765 //
5766 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5767 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5768 // is not too far off the truth, since an always-on VPN, when not connected, is always
5769 // trying to reconnect.
5770 if (getLegacyLockdownNai() == null) {
5771 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5772 }
5773 }
5774
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005775 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005776 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04005777 String action) {
paulhu8e96a752019-08-12 16:25:11 +08005778 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09005779 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5780 return;
5781 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04005782 final long ident = Binder.clearCallingIdentity();
5783 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09005784 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09005785 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09005786 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04005787 } finally {
5788 Binder.restoreCallingIdentity(ident);
5789 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005790 }
Wink Savillecb117d32013-08-29 14:57:08 -07005791
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005792 @Override
5793 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01005794 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005795 final long ident = Binder.clearCallingIdentity();
5796 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005797 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09005798 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005799 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5800 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08005801 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005802 } finally {
5803 Binder.restoreCallingIdentity(ident);
5804 }
5805 }
5806
James Mattis02220e22021-03-13 19:27:21 -08005807 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005808 mPermissionMonitor.onUserAdded(user);
James Mattisae9aeb02021-03-01 17:09:11 -08005809 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5810 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5811 }
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005812 }
5813
James Mattis02220e22021-03-13 19:27:21 -08005814 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005815 mPermissionMonitor.onUserRemoved(user);
Chalard Jean0f57a492021-03-09 21:09:20 +09005816 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005817 handleSetProfileNetworkPreference(
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08005818 List.of(new ProfileNetworkPreferenceList.Preference(user, null, true)),
Chalard Jean0f57a492021-03-09 21:09:20 +09005819 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08005820 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5821 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5822 }
junyulaid91e7052020-08-28 13:44:33 +08005823 }
5824
James Mattis02220e22021-03-13 19:27:21 -08005825 private void onPackageChanged(@NonNull final String packageName) {
5826 // This is necessary in case a package is added or removed, but also when it's replaced to
5827 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5828 // as one in the preferences, then it should follow the same routing as that other package,
5829 // which means updating the rules is never to be needed in this case (whether it joins or
5830 // leaves a UID with a preference).
5831 if (isMappedInOemNetworkPreference(packageName)) {
5832 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5833 }
5834 }
5835
5836 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005837 @Override
5838 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09005839 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005840 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005841 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08005842
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005843 // User should be filled for below intents, check the existence.
5844 if (user == null) {
5845 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5846 return;
5847 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005848
Lorenzo Colitticd675292021-02-04 17:32:07 +09005849 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005850 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005851 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005852 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09005853 } else {
junyulaid91e7052020-08-28 13:44:33 +08005854 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005855 }
5856 }
5857 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07005858
James Mattis02220e22021-03-13 19:27:21 -08005859 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5860 @Override
5861 public void onReceive(Context context, Intent intent) {
5862 ensureRunningOnConnectivityServiceThread();
5863 switch (intent.getAction()) {
5864 case Intent.ACTION_PACKAGE_ADDED:
5865 case Intent.ACTION_PACKAGE_REMOVED:
5866 case Intent.ACTION_PACKAGE_REPLACED:
5867 onPackageChanged(intent.getData().getSchemeSpecificPart());
5868 break;
5869 default:
5870 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5871 }
5872 }
5873 };
5874
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005875 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005876 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005877
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005878 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005879 public final String name;
5880 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005881 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005882 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005883
lifraf3a3492021-03-10 13:58:14 +08005884 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5885 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005886 this.name = name;
5887 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005888 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005889 mDeathRecipient = deathRecipient;
5890
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005891 if (mDeathRecipient == null) {
5892 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005893 }
5894 }
5895
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005896 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005897 try {
5898 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5899 } catch (RemoteException e) {
5900 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005901 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005902 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005903 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005904
James Mattis4fce5d12020-11-12 15:53:42 -08005905 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
5906 for (int i = 0; i < requests.size(); i++) {
5907 ensureNetworkRequestHasType(requests.get(i));
5908 }
5909 }
5910
Lorenzo Colitti70964d32016-07-05 01:22:13 +09005911 private void ensureNetworkRequestHasType(NetworkRequest request) {
5912 if (request.type == NetworkRequest.Type.NONE) {
5913 throw new IllegalArgumentException(
5914 "All NetworkRequests in ConnectivityService must have a type");
5915 }
5916 }
5917
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005918 /**
5919 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08005920 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005921 */
James Mattis258ea3c2020-11-15 15:04:40 -08005922 @VisibleForTesting
5923 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08005924 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
5925 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08005926 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08005927
James Mattisa076c532020-12-02 14:12:41 -08005928 // mSatisfier and mActiveRequest rely on one another therefore set them together.
5929 void setSatisfier(
5930 @Nullable final NetworkAgentInfo satisfier,
5931 @Nullable final NetworkRequest activeRequest) {
5932 mSatisfier = satisfier;
5933 mActiveRequest = activeRequest;
5934 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005935
James Mattisd31bdfa2020-12-23 16:37:26 -08005936 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005937 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09005938 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08005939 private NetworkAgentInfo mSatisfier;
5940 NetworkAgentInfo getSatisfier() {
5941 return mSatisfier;
5942 }
5943
5944 // The request in mRequests assigned to a network agent. This is null if none of the
5945 // requests in mRequests can be satisfied. This member has the constraint of only being
5946 // accessible on the handler thread.
5947 @Nullable
5948 private NetworkRequest mActiveRequest;
5949 NetworkRequest getActiveRequest() {
5950 return mActiveRequest;
5951 }
5952
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005953 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08005954 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08005955 @Nullable
5956 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005957
5958 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08005959 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005960 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005961 final int mPid;
5962 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08005963 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005964 @Nullable
5965 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005966
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005967 // Counter keeping track of this NRI.
5968 final PerUidCounter mPerUidCounter;
5969
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005970 // Effective UID of this request. This is different from mUid when a privileged process
5971 // files a request on behalf of another UID. This UID is used to determine blocked status,
5972 // UID matching, and so on. mUid above is used for permission checks and to enforce the
5973 // maximum limit of registered callbacks per UID.
5974 final int mAsUid;
5975
paulhu48291862021-07-14 14:53:57 +08005976 // Preference order of this request.
5977 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08005978
James Mattis3ce3d3c2021-02-09 18:18:28 -08005979 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
5980 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
5981 // maintained for keying off of. This is only a concern when the original nri
5982 // mNetworkRequests changes which happens currently for apps that register callbacks to
5983 // track the default network. In those cases, the nri is updated to have mNetworkRequests
5984 // that match the per-app default nri that currently tracks the calling app's uid so that
5985 // callbacks are fired at the appropriate time. When the callbacks fire,
5986 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
5987 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
5988 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
5989 @NonNull
5990 private final NetworkRequest mNetworkRequestForCallback;
5991 NetworkRequest getNetworkRequestForCallback() {
5992 return mNetworkRequestForCallback;
5993 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005994
James Mattisd31bdfa2020-12-23 16:37:26 -08005995 /**
5996 * Get the list of UIDs this nri applies to.
5997 */
5998 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00005999 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006000 // networkCapabilities.getUids() returns a defensive copy.
6001 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006002 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6003 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006004 }
6005
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006006 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6007 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006008 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006009 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006010 }
6011
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006012 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006013 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006014 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006015 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006016 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006017 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006018 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006019 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006020 mBinder = null;
6021 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006022 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006023 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006024 mPerUidCounter = getRequestCounter(this);
6025 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006026 /**
6027 * Location sensitive data not included in pending intent. Only included in
6028 * {@link NetworkCallback}.
6029 */
6030 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006031 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006032 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006033 }
6034
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006035 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006036 @Nullable final IBinder binder,
6037 @NetworkCallback.Flag int callbackFlags,
6038 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006039 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
6040 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08006041 }
6042
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006043 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006044 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006045 @Nullable final IBinder binder,
6046 @NetworkCallback.Flag int callbackFlags,
6047 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006048 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006049 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006050 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006051 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006052 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006053 mBinder = binder;
6054 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006055 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006056 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006057 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006058 mPerUidCounter = getRequestCounter(this);
6059 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006060 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006061 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006062 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006063 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006064 }
6065
James Mattis3ce3d3c2021-02-09 18:18:28 -08006066 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6067 @NonNull final List<NetworkRequest> r) {
6068 super();
6069 ensureAllNetworkRequestsHaveType(r);
6070 mRequests = initializeRequests(r);
6071 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006072 final NetworkAgentInfo satisfier = nri.getSatisfier();
6073 if (null != satisfier) {
6074 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6075 // The active request is necessary to figure out what callbacks to send, in
6076 // particular then a network updates its capabilities.
6077 // As this code creates a new NRI with a new set of requests, figure out which of
6078 // the list of requests should be the active request. It is always the first
6079 // request of the list that can be satisfied by the satisfier since the order of
6080 // requests is a priority order.
6081 // Note even in the presence of a satisfier there may not be an active request,
6082 // when the satisfier is the no-service network.
6083 NetworkRequest activeRequest = null;
6084 for (final NetworkRequest candidate : r) {
6085 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6086 activeRequest = candidate;
6087 break;
6088 }
6089 }
6090 setSatisfier(satisfier, activeRequest);
6091 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006092 mMessenger = nri.mMessenger;
6093 mBinder = nri.mBinder;
6094 mPid = nri.mPid;
6095 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006096 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006097 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006098 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006099 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006100 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006101 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006102 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006103 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006104 }
6105
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006106 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006107 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006108 }
6109
paulhue9913722021-05-26 15:19:20 +08006110 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006111 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006112 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006113 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006114 }
6115
James Mattis2516da32021-01-31 17:06:19 -08006116 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6117 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6118 // false.
6119 boolean isBeingSatisfied() {
6120 return (null != mSatisfier && null != mActiveRequest);
6121 }
6122
James Mattis3d229892020-11-16 16:46:28 -08006123 boolean isMultilayerRequest() {
6124 return mRequests.size() > 1;
6125 }
6126
James Mattis45d81842021-01-10 14:24:24 -08006127 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6128 // Creating a defensive copy to prevent the sender from modifying the list being
6129 // reflected in the return value of this method.
6130 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006131 return Collections.unmodifiableList(tempRequests);
6132 }
6133
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006134 void decrementRequestCount() {
6135 mPerUidCounter.decrementCount(mUid);
6136 }
6137
James Mattisb1392002021-03-31 13:57:52 -07006138 void linkDeathRecipient() {
6139 if (null != mBinder) {
6140 try {
6141 mBinder.linkToDeath(this, 0);
6142 } catch (RemoteException e) {
6143 binderDied();
6144 }
6145 }
6146 }
6147
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006148 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006149 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006150 try {
6151 mBinder.unlinkToDeath(this, 0);
6152 } catch (NoSuchElementException e) {
6153 // Temporary workaround for b/194394697 pending analysis of additional logs
6154 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6155 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006156 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006157 }
6158
paulhu48291862021-07-14 14:53:57 +08006159 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6160 // Compare two preference orders.
6161 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006162 }
6163
paulhu48291862021-07-14 14:53:57 +08006164 int getPreferenceOrderForNetd() {
6165 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6166 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6167 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006168 }
paulhu48291862021-07-14 14:53:57 +08006169 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006170 }
6171
James Mattis4fce5d12020-11-12 15:53:42 -08006172 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006173 public void binderDied() {
6174 log("ConnectivityService NetworkRequestInfo binderDied(" +
Chalard Jean524f0b12021-10-25 21:11:56 +09006175 "uid/pid:" + mUid + "/" + mPid + ", " + mRequests + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09006176 // As an immutable collection, mRequests cannot change by the time the
6177 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6178 // is acceptable. Use handleReleaseNetworkRequest and not directly
6179 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6180 // the app already unregistered the request.
6181 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6182 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006183 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006184
James Mattis4fce5d12020-11-12 15:53:42 -08006185 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006186 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006187 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6188 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006189 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006190 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006191 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006192 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006193 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006194 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006195 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006196 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006197 }
6198
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006199 // This checks that the passed capabilities either do not request a
6200 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006201 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006202 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006203 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006204 throw new SecurityException("Insufficient permissions to request a specific SSID");
6205 }
paulhu1a407652019-03-22 16:35:06 +08006206
6207 if (nc.hasSignalStrength()
6208 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6209 throw new SecurityException(
6210 "Insufficient permissions to request a specific signal strength");
6211 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006212 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006213
junyulai2217bec2021-04-14 23:33:31 +08006214 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006215 enforceNetworkFactoryPermission();
6216 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006217 }
6218
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006219 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006220 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006221 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006222 // mNetworkRequests may contain the same value multiple times in case of
6223 // multilayer requests. It won't matter in this case because the thresholds
6224 // will then be the same and be deduplicated as they enter the `thresholds` set.
6225 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006226 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6227 for (final NetworkRequest req : nri.mRequests) {
6228 if (req.networkCapabilities.hasSignalStrength()
6229 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6230 thresholds.add(req.networkCapabilities.getSignalStrength());
6231 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006232 }
6233 }
6234 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006235 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006236 }
6237
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006238 private void updateSignalStrengthThresholds(
6239 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006240 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006241
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006242 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006243 String detail;
6244 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6245 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6246 } else {
6247 detail = reason;
6248 }
6249 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006250 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006251 }
6252
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006253 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006254 }
6255
Chalard Jeandd421992021-12-16 23:16:02 +09006256 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07006257 if (nc == null) {
6258 return;
6259 }
6260 NetworkSpecifier ns = nc.getNetworkSpecifier();
6261 if (ns == null) {
6262 return;
6263 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006264 if (ns instanceof MatchAllNetworkSpecifier) {
6265 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6266 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006267 }
6268
Chalard Jeandd421992021-12-16 23:16:02 +09006269 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08006270 ensureValidNetworkSpecifier(nc);
6271 if (nc.isPrivateDnsBroken()) {
6272 throw new IllegalArgumentException("Can't request broken private DNS");
6273 }
Chalard Jean9a30acf2021-12-13 22:53:51 +09006274 if (nc.hasAccessUids()) {
6275 throw new IllegalArgumentException("Can't request access UIDs");
6276 }
lucasline117e2e2019-10-22 18:27:33 +08006277 }
6278
Chalard Jeandd421992021-12-16 23:16:02 +09006279 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
6280 ensureListenableCapabilities(nc);
6281 final String badCapability = nc.describeFirstNonRequestableCapability();
6282 if (badCapability != null) {
6283 throw new IllegalArgumentException("Cannot request network with " + badCapability);
6284 }
6285 }
6286
Chiachang Wang3bc52762021-11-25 14:17:57 +08006287 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6288 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006289 private boolean isTargetSdkAtleast(int version, int callingUid,
6290 @NonNull String callingPackageName) {
6291 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006292 final PackageManager pm =
6293 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006294 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006295 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006296 if (callingVersion < version) return false;
6297 } catch (PackageManager.NameNotFoundException e) { }
6298 return true;
6299 }
6300
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006301 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006302 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006303 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006304 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006305 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006306 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006307 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6308 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006309 throw new SecurityException("Insufficient permissions to specify legacy type");
6310 }
markchienfac84a22020-03-18 21:16:15 +08006311 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006312 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006313 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006314 // Privileged callers can track the default network of another UID by passing in a UID.
6315 if (asUid != Process.INVALID_UID) {
6316 enforceSettingsPermission();
6317 } else {
6318 asUid = callingUid;
6319 }
junyulaiad010792021-01-11 16:53:38 +08006320 final NetworkRequest.Type reqType;
6321 try {
6322 reqType = NetworkRequest.Type.values()[reqTypeInt];
6323 } catch (ArrayIndexOutOfBoundsException e) {
6324 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6325 }
6326 switch (reqType) {
6327 case TRACK_DEFAULT:
6328 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006329 // is unused and will be replaced by ones appropriate for the UID (usually, the
6330 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006331 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006332 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006333 enforceAccessPermission();
6334 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006335 case TRACK_SYSTEM_DEFAULT:
6336 enforceSettingsPermission();
6337 networkCapabilities = new NetworkCapabilities(defaultNc);
6338 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006339 case BACKGROUND_REQUEST:
6340 enforceNetworkStackOrSettingsPermission();
6341 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006342 case REQUEST:
6343 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6344 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6345 callingAttributionTag);
6346 // TODO: this is incorrect. We mark the request as metered or not depending on
6347 // the state of the app when the request is filed, but we never change the
6348 // request if the app changes network state. http://b/29964605
6349 enforceMeteredApnPolicy(networkCapabilities);
6350 break;
junyulai1b1c8742021-03-12 20:05:08 +08006351 case LISTEN_FOR_BEST:
6352 enforceAccessPermission();
6353 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6354 break;
junyulaiad010792021-01-11 16:53:38 +08006355 default:
6356 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006357 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006358 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006359 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006360 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006361
junyulai1b1c8742021-03-12 20:05:08 +08006362 // Enforce FOREGROUND if the caller does not have permission to use background network.
6363 if (reqType == LISTEN_FOR_BEST) {
6364 restrictBackgroundRequestForCaller(networkCapabilities);
6365 }
6366
6367 // Set the UID range for this request to the single UID of the requester, unless the
6368 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006369 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6370 // are no visible methods to set the UIDs, an app could use reflection to try and get
6371 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006372 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006373 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6374 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006375
Etan Cohen85000162017-02-05 10:42:27 -08006376 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006377 throw new IllegalArgumentException("Bad timeout specified");
6378 }
Etan Cohen9786d922015-11-18 10:56:15 -08006379
James Mattis3ce3d3c2021-02-09 18:18:28 -08006380 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006381 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006382 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006383 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006384 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006385 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006386
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006387 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6388 // copied from the default request above. (This is necessary to ensure, for example, that
6389 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6390 // changes don't alter request matching.
6391 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6392 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006393 throw new IllegalStateException(
6394 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006395 + networkCapabilities + " vs. " + defaultNc);
6396 }
6397
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006398 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006399 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006400 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006401 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006402 }
6403 return networkRequest;
6404 }
6405
James Mattis3ce3d3c2021-02-09 18:18:28 -08006406 /**
6407 * Return the nri to be used when registering a network request. Specifically, this is used with
6408 * requests registered to track the default request. If there is currently a per-app default
6409 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6410 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006411 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6412 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006413 * @param nr the network request for the nri.
6414 * @param msgr the messenger for the nri.
6415 * @param binder the binder for the nri.
6416 * @param callingAttributionTag the calling attribution tag for the nri.
6417 * @return the nri to register.
6418 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006419 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006420 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006421 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006422 @Nullable String callingAttributionTag) {
6423 final List<NetworkRequest> requests;
6424 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6425 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006426 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006427 } else {
6428 requests = Collections.singletonList(nr);
6429 }
Roshan Pius951c0032020-12-22 15:10:42 -08006430 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006431 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006432 }
6433
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006434 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
6435 String callingPackageName, String callingAttributionTag) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006436 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006437 if (!networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
6438 enforceConnectivityRestrictedNetworksPermission();
6439 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006440 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006441 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006442 }
6443 }
6444
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006445 private boolean checkConnectivityRestrictedNetworksPermission(int callerPid, int callerUid) {
6446 if (checkAnyPermissionOf(callerPid, callerUid,
6447 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)
6448 || checkAnyPermissionOf(callerPid, callerUid,
6449 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
6450 return true;
6451 }
6452 return false;
6453 }
6454
fenglu3f357402015-03-20 11:29:56 -07006455 @Override
fenglub00f4882015-04-21 17:12:05 -07006456 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006457 enforceAccessPermission();
6458 NetworkAgentInfo nai = null;
6459 if (network == null) {
6460 return false;
6461 }
6462 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006463 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006464 }
6465 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006466 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006467 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006468 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006469 Integer uidReqs = mBandwidthRequests.get(uid);
6470 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006471 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006472 }
6473 mBandwidthRequests.put(uid, ++uidReqs);
6474 }
fenglu3f357402015-03-20 11:29:56 -07006475 return true;
6476 }
6477 return false;
6478 }
6479
Felipe Leme0a5ae422016-06-20 16:36:29 -07006480 private boolean isSystem(int uid) {
6481 return uid < Process.FIRST_APPLICATION_UID;
6482 }
fenglu3f357402015-03-20 11:29:56 -07006483
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006484 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006485 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006486 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006487 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006488 return;
6489 }
Hugo Benichi39621362017-02-11 17:04:43 +09006490 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6491 // Policy already enforced.
6492 return;
6493 }
paulhuaf50d7d2020-12-24 19:47:34 +08006494 final long ident = Binder.clearCallingIdentity();
6495 try {
6496 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6497 // If UID is restricted, don't allow them to bring up metered APNs.
6498 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6499 }
6500 } finally {
6501 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006502 }
6503 }
6504
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006505 @Override
6506 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006507 PendingIntent operation, @NonNull String callingPackageName,
6508 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006509 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006510 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006511 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006512 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6513 callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006514 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006515 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006516 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006517 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006518 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6519 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09006520
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006521 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006522 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006523 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6524 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006525 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006526 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6527 nri));
6528 return networkRequest;
6529 }
6530
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006531 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6532 mHandler.sendMessageDelayed(
6533 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006534 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006535 }
6536
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006537 @Override
6538 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006539 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006540 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006541 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006542 }
6543
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006544 // In order to implement the compatibility measure for pre-M apps that call
6545 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6546 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6547 // This ensures it has permission to do so.
6548 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6549 if (nc == null) {
6550 return false;
6551 }
6552 int[] transportTypes = nc.getTransportTypes();
6553 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6554 return false;
6555 }
6556 try {
6557 mContext.enforceCallingOrSelfPermission(
6558 android.Manifest.permission.ACCESS_WIFI_STATE,
6559 "ConnectivityService");
6560 } catch (SecurityException e) {
6561 return false;
6562 }
6563 return true;
6564 }
6565
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006566 @Override
6567 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08006568 Messenger messenger, IBinder binder,
6569 @NetworkCallback.Flag int callbackFlags,
6570 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006571 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006572 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6573 enforceAccessPermission();
6574 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006575
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006576 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006577 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006578 Binder.getCallingPid(), callingUid, callingPackageName);
6579 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09006580 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6581 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6582 // onLost and onAvailable callbacks when networks move in and out of the background.
6583 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6584 // can't request networks.
6585 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09006586 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07006587
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006588 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006589 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08006590 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006591 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08006592 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006593 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006594
6595 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6596 return networkRequest;
6597 }
6598
6599 @Override
6600 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08006601 PendingIntent operation, @NonNull String callingPackageName,
6602 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006603 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006604 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04006605 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6606 enforceAccessPermission();
6607 }
Chalard Jeandd421992021-12-16 23:16:02 +09006608 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006609 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006610 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006611 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006612 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006613
6614 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006615 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006616 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6617 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006618 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04006619
WeiZhang1cc3f172021-06-03 19:02:04 -05006620 mHandler.sendMessage(mHandler.obtainMessage(
6621 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006622 }
6623
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006624 /** Returns the next Network provider ID. */
6625 public final int nextNetworkProviderId() {
6626 return mNextNetworkProviderId.getAndIncrement();
6627 }
6628
Erik Kline0c04b742016-07-07 16:50:58 +09006629 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006630 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006631 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09006632 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006633 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006634 }
6635
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006636 private void releaseNetworkRequestAndCallOnUnavailable(NetworkRequest networkRequest) {
6637 ensureNetworkRequestHasType(networkRequest);
6638 mHandler.sendMessage(mHandler.obtainMessage(
6639 EVENT_RELEASE_NETWORK_REQUEST_AND_CALL_UNAVAILABLE, mDeps.getCallingUid(), 0,
6640 networkRequest));
6641 }
6642
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006643 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6644 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006645 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6646 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6647 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08006648 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006649 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006650 return;
6651 }
6652
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006653 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6654 mNetworkProviderInfos.put(npi.messenger, npi);
6655 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006656 }
6657
6658 @Override
6659 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006660 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08006661 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006662 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08006663 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006664 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6665 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006666 }
6667
6668 @Override
6669 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006670 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006671 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006672 }
6673
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006674 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09006675 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006676 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6677 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09006678 Objects.requireNonNull(score);
6679 Objects.requireNonNull(caps);
6680 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09006681 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006682 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09006683 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
6684 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006685 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6686 }
6687
Chalard Jeanbb902a52021-08-18 01:35:19 +09006688 private void updateOfferScore(final NetworkOffer offer) {
6689 final boolean yieldToBadWiFi =
6690 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
6691 final NetworkOffer newOffer = new NetworkOffer(
6692 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
6693 offer.caps, offer.callback, offer.providerId);
6694 if (offer.equals(newOffer)) return;
6695 handleRegisterNetworkOffer(newOffer);
6696 }
6697
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006698 @Override
6699 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6700 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6701 }
6702
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006703 private void handleUnregisterNetworkProvider(Messenger messenger) {
6704 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6705 if (npi == null) {
6706 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006707 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006708 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006709 // Unregister all the offers from this provider
6710 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6711 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09006712 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006713 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6714 toRemove.add(noi);
6715 }
6716 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09006717 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006718 handleUnregisterNetworkOffer(noi);
6719 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006720 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006721 }
6722
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006723 @Override
James Mattisf7027322020-12-13 16:28:14 -08006724 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006725 if (request.hasTransport(TRANSPORT_TEST)) {
6726 enforceNetworkFactoryOrTestNetworksPermission();
6727 } else {
6728 enforceNetworkFactoryPermission();
6729 }
James Mattisf7027322020-12-13 16:28:14 -08006730 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6731 if (nri != null) {
6732 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6733 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6734 mHandler.post(() -> handleReleaseNetworkRequest(
6735 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6736 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006737 }
6738
Paul Jensen1f567382015-02-13 14:18:39 -05006739 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6740 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006741 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05006742 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006743 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05006744 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006745 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006746
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09006747 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05006748 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006749 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006750
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006751 // UID ranges for users that are currently blocked by VPNs.
6752 // This array is accessed and iterated on multiple threads without holding locks, so its
6753 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6754 // (on the handler thread).
6755 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6756
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006757 // Must only be accessed on the handler thread
6758 @NonNull
6759 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6760
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006761 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006762 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006763
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006764 // Current OEM network preferences. This object must only be written to on the handler thread.
6765 // Since it is immutable and always non-null, other threads may read it if they only care
6766 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08006767 @NonNull
6768 private OemNetworkPreferences mOemNetworkPreferences =
6769 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006770 // Current per-profile network preferences. This object follows the same threading rules as
6771 // the OEM network preferences above.
6772 @NonNull
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006773 private ProfileNetworkPreferenceList mProfileNetworkPreferences =
6774 new ProfileNetworkPreferenceList();
James Mattis45d81842021-01-10 14:24:24 -08006775
paulhu51f77dc2021-06-07 02:34:20 +00006776 // A set of UIDs that should use mobile data preferentially if available. This object follows
6777 // the same threading rules as the OEM network preferences above.
6778 @NonNull
6779 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
6780
James Mattiscb1e0362021-04-06 17:07:42 -07006781 // OemNetworkPreferences activity String log entries.
6782 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6783 @NonNull
6784 private final LocalLog mOemNetworkPreferencesLogs =
6785 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6786
James Mattis02220e22021-03-13 19:27:21 -08006787 /**
6788 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6789 * @param packageName the package name to check existence of a mapping for.
6790 * @return true if a mapping exists, false otherwise
6791 */
6792 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6793 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6794 }
6795
James Mattise3ef1912020-12-20 11:09:58 -08006796 // The always-on request for an Internet-capable network that apps without a specific default
6797 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08006798 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09006799 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006800 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08006801 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08006802 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08006803 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006804 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006805
James Mattisd31bdfa2020-12-23 16:37:26 -08006806 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6807 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6808 }
6809
6810 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08006811 * Return the default network request currently tracking the given uid.
6812 * @param uid the uid to check.
6813 * @return the NetworkRequestInfo tracking the given uid.
6814 */
6815 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08006816 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08006817 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006818 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006819 // Checking the first request is sufficient as only multilayer requests will have more
6820 // than one request and for multilayer, all requests will track the same uids.
6821 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08006822 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08006823 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08006824 highestPriorityNri = nri;
6825 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006826 }
6827 }
paulhuaa0743d2021-05-26 21:56:03 +08006828 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006829 }
6830
6831 /**
6832 * Get a copy of the network requests of the default request that is currently tracking the
6833 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006834 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6835 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006836 * @param requestorUid the uid to check the default for.
6837 * @param requestorPackageName the requestor's package name.
6838 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6839 */
6840 @NonNull
6841 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006842 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006843 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006844 getDefaultRequestTrackingUid(asUid).mRequests,
6845 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006846 }
6847
6848 /**
6849 * Copy the given nri's NetworkRequest collection.
6850 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006851 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6852 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006853 * @param requestorUid the uid to set on the copied collection.
6854 * @param requestorPackageName the package name to set on the copied collection.
6855 * @return the copied NetworkRequest collection.
6856 */
6857 @NonNull
6858 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006859 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6860 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006861 final List<NetworkRequest> requests = new ArrayList<>();
6862 for (final NetworkRequest nr : requestsToCopy) {
6863 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006864 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08006865 nr.legacyType, nextNetworkRequestId(), nr.type));
6866 }
6867 return requests;
6868 }
6869
6870 @NonNull
6871 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006872 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6873 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09006874 // These capabilities are for a TRACK_DEFAULT callback, so:
6875 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6876 // mDefaultRequest and a per-UID default request.
6877 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006878 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09006879 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006880 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6881 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006882 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006883 restrictRequestUidsForCallerAndSetRequestorInfo(
6884 netCap, requestorUid, requestorPackageName);
6885 return netCap;
6886 }
6887
6888 /**
6889 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6890 * @param nr the network request to check for equality against.
6891 * @return the nri if one exists, null otherwise.
6892 */
6893 @Nullable
6894 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6895 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6896 if (nri.getNetworkRequestForCallback().equals(nr)) {
6897 return nri;
6898 }
6899 }
6900 return null;
6901 }
6902
6903 /**
6904 * Check if an nri is currently being managed by per-app default networking.
6905 * @param nri the nri to check.
6906 * @return true if this nri is currently being managed by per-app default networking.
6907 */
6908 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
6909 // nri.mRequests.get(0) is only different from the original request filed in
6910 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
6911 // functionality therefore if these two don't match, it means this particular nri is
6912 // currently being managed by a per-app default.
6913 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
6914 }
6915
6916 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08006917 * Determine if an nri is a managed default request that disallows default networking.
6918 * @param nri the request to evaluate
6919 * @return true if device-default networking is disallowed
6920 */
6921 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
6922 // Check if this nri is a managed default that supports the default network at its
6923 // lowest priority request.
6924 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
6925 final NetworkCapabilities lowestPriorityNetCap =
6926 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
6927 return isPerAppDefaultRequest(nri)
6928 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
6929 lowestPriorityNetCap));
6930 }
6931
Erik Kline05f2b402015-04-30 12:58:40 +09006932 // Request used to optionally keep mobile data active even when higher
6933 // priority networks like Wi-Fi are active.
6934 private final NetworkRequest mDefaultMobileDataRequest;
6935
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006936 // Request used to optionally keep wifi data active even when higher
6937 // priority networks like ethernet are active.
6938 private final NetworkRequest mDefaultWifiRequest;
6939
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08006940 // Request used to optionally keep vehicle internal network always active
6941 private final NetworkRequest mDefaultVehicleRequest;
6942
James Mattisd31bdfa2020-12-23 16:37:26 -08006943 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
6944 // network with no service. This NAI should never be matched against, nor should any public API
6945 // ever return the associated network. For this reason, this NAI is not in the list of available
6946 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
6947 // default requests that don't support using the device default network which will ultimately
6948 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
6949 @VisibleForTesting
6950 final NetworkAgentInfo mNoServiceNetwork;
6951
Chalard Jean5b409c72021-02-04 13:12:59 +09006952 // The NetworkAgentInfo currently satisfying the default request, if any.
6953 private NetworkAgentInfo getDefaultNetwork() {
6954 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09006955 }
6956
James Mattis2516da32021-01-31 17:06:19 -08006957 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08006958 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08006959 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6960 // Currently, all network requests will have the same uids therefore checking the first
6961 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006962 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08006963 if (null == uids) {
6964 continue;
6965 }
6966 for (final UidRange range : uids) {
6967 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08006968 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08006969 highestPriorityNri = nri;
6970 }
James Mattis2516da32021-01-31 17:06:19 -08006971 }
6972 }
6973 }
paulhuaa0743d2021-05-26 21:56:03 +08006974 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08006975 }
6976
Varun Ananddf569952019-02-06 10:13:38 -08006977 @Nullable
6978 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
6979 return nai != null ? nai.network : null;
6980 }
6981
6982 private void ensureRunningOnConnectivityServiceThread() {
6983 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
6984 throw new IllegalStateException(
6985 "Not running on ConnectivityService thread: "
6986 + Thread.currentThread().getName());
6987 }
6988 }
6989
Chalard Jean3a3f5f22019-04-10 23:07:55 +09006990 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09006991 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
6992 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006993 }
6994
Chalard Jean29d06db2018-05-02 21:14:54 +09006995 /**
6996 * Register a new agent with ConnectivityService to handle a network.
6997 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006998 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09006999 * @param networkInfo the initial info associated with this network. It can be updated later :
7000 * see {@link #updateNetworkInfo}.
7001 * @param linkProperties the initial link properties of this network. They can be updated
7002 * later : see {@link #updateLinkProperties}.
7003 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007004 * later : see {@link #updateCapabilities}.
Chalard Jean28018572020-12-21 18:36:52 +09007005 * @param initialScore the initial score of the network. See
Chalard Jean29d06db2018-05-02 21:14:54 +09007006 * {@link NetworkAgentInfo#getCurrentScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007007 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007008 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007009 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007010 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007011 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007012 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007013 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7014 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007015 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7016 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7017 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007018 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007019 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007020 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
7021 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007022 } else {
7023 enforceNetworkFactoryPermission();
7024 }
7025
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007026 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007027 final long token = Binder.clearCallingIdentity();
7028 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007029 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007030 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007031 } finally {
7032 Binder.restoreCallingIdentity(token);
7033 }
7034 }
7035
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007036 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007037 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007038 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7039 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007040
Chalard Jean366c5252022-01-25 18:27:53 +09007041 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
7042 // the capabilities' access UID comply with security limitations. They will be sanitized
7043 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7044 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007045 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jean366c5252022-01-25 18:27:53 +09007046 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo),
7047 linkProperties, networkCapabilities,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007048 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007049 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7050 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007051
Chalard Jeanf2da1772018-04-26 16:16:10 +09007052 final String extraInfo = networkInfo.getExtraInfo();
7053 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007054 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007055 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007056 mDeps.getNetworkStack().makeNetworkMonitor(
7057 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007058 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7059 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007060 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007061 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007062 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007063 }
7064
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007065 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007066 if (VDBG) log("Network Monitor created for " + nai);
7067 // nai.nc and nai.lp are the same object that was passed by the network agent if the agent
7068 // lives in the same process as this code (e.g. wifi), so make sure this code doesn't
7069 // mutate their object
7070 final NetworkCapabilities nc = new NetworkCapabilities(nai.networkCapabilities);
7071 final LinkProperties lp = new LinkProperties(nai.linkProperties);
7072 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
7073 processCapabilitiesFromAgent(nai, nc);
7074 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
7075 processLinkPropertiesFromAgent(nai, lp);
7076 nai.linkProperties = lp;
7077
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007078 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007079
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007080 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007081 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007082 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007083 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007084
7085 try {
7086 networkMonitor.start();
7087 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007088 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007089 }
Chalard Jean366c5252022-01-25 18:27:53 +09007090
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007091 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007092 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007093 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007094 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007095 }
7096
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007097 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7098 @NonNull public final NetworkOffer offer;
7099
7100 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7101 this.offer = offer;
7102 }
7103
7104 @Override
7105 public void binderDied() {
7106 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7107 }
7108 }
7109
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007110 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7111 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7112 if (npi.providerId == providerId) return true;
7113 }
7114 return false;
7115 }
7116
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007117 /**
7118 * Register or update a network offer.
7119 * @param newOffer The new offer. If the callback member is the same as an existing
7120 * offer, it is an update of that offer.
7121 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007122 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007123 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7124 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007125 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007126 // This may actually happen if a provider updates its score or registers and then
7127 // immediately unregisters. The offer would still be in the handler queue, but the
7128 // provider would have been removed.
7129 if (DBG) log("Received offer from an unregistered provider");
7130 return;
7131 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007132 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7133 if (null != existingOffer) {
7134 handleUnregisterNetworkOffer(existingOffer);
7135 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007136 if (DBG) {
7137 // handleUnregisterNetworkOffer has already logged the old offer
7138 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7139 }
7140 } else {
7141 if (DBG) {
7142 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7143 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007144 }
7145 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7146 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007147 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007148 } catch (RemoteException e) {
7149 noi.binderDied();
7150 return;
7151 }
7152 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007153 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007154 }
7155
7156 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7157 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007158 if (DBG) {
7159 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7160 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007161
7162 // If the provider removes the offer and dies immediately afterwards this
7163 // function may be called twice in a row, but the array will no longer contain
7164 // the offer.
7165 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007166 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007167 }
7168
7169 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7170 @NonNull final INetworkOfferCallback callback) {
7171 ensureRunningOnConnectivityServiceThread();
7172 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007173 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007174 }
7175 return null;
7176 }
7177
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007178 /**
7179 * Called when receiving LinkProperties directly from a NetworkAgent.
7180 * Stores into |nai| any data coming from the agent that might also be written to the network's
7181 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7182 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007183 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007184 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007185 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7186 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007187 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007188 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007189 }
7190
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007191 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007192 @NonNull LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007193 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007194
Lorenzo Colittid523d142020-04-01 20:16:30 +09007195 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7196 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7197 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007198 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007199
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007200 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007201
7202 // update filtering rules, need to happen after the interface update so netd knows about the
7203 // new interface (the interface name -> index map becomes initialized)
7204 updateVpnFiltering(newLp, oldLp, networkAgent);
7205
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007206 updateMtu(newLp, oldLp);
7207 // TODO - figure out what to do for clat
7208// for (LinkProperties lp : newLp.getStackedLinks()) {
7209// updateMtu(lp, null);
7210// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007211 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007212 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7213 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007214
Erik Klineb9888902016-04-05 13:30:49 +09007215 updateRoutes(newLp, oldLp, netId);
7216 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007217 // Make sure LinkProperties represents the latest private DNS status.
7218 // This does not need to be done before updateDnses because the
7219 // LinkProperties are not the source of the private DNS configuration.
7220 // updateDnses will fetch the private DNS configuration from DnsManager.
7221 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007222
Chalard Jean5b409c72021-02-04 13:12:59 +09007223 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007224 handleApplyDefaultProxy(newLp.getHttpProxy());
7225 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007226 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007227 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007228
7229 updateWakeOnLan(newLp);
7230
Hai Shalome58bdc62021-01-11 18:45:34 -08007231 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7232 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7233 // does, it needs to be merged here.
7234 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7235 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007236
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007237 // TODO - move this check to cover the whole function
7238 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007239 synchronized (networkAgent) {
7240 networkAgent.linkProperties = newLp;
7241 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007242 // Start or stop DNS64 detection and 464xlat according to network state.
7243 networkAgent.clatd.update();
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08007244 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007245 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7246 new LinkProperties(newLp, true /* parcelSensitiveFields */));
lucaslin74fa3972018-11-28 12:51:55 +08007247 if (networkAgent.everConnected) {
7248 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
7249 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007250 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007251
7252 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007253 }
7254
Hai Shalome58bdc62021-01-11 18:45:34 -08007255 /**
7256 * @param naData captive portal data from NetworkAgent
7257 * @param apiData captive portal data from capport API
7258 */
7259 @Nullable
7260 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7261 CaptivePortalData apiData) {
7262 if (naData == null || apiData == null) {
7263 return naData == null ? apiData : naData;
7264 }
7265 final CaptivePortalData.Builder captivePortalBuilder =
7266 new CaptivePortalData.Builder(naData);
7267
7268 if (apiData.isCaptive()) {
7269 captivePortalBuilder.setCaptive(true);
7270 }
7271 if (apiData.isSessionExtendable()) {
7272 captivePortalBuilder.setSessionExtendable(true);
7273 }
7274 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7275 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7276 // otherwise data would be inconsistent. Prefer the capport API info if present,
7277 // as it can generally be refreshed more often.
7278 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7279 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7280 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7281 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7282 // No source has time / bytes remaining information: surface the newest refresh time
7283 // for other fields
7284 captivePortalBuilder.setRefreshTime(
7285 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7286 }
7287
Hai Shalom7c6ab402021-02-04 19:34:06 -08007288 // Prioritize the user portal URL from the network agent if the source is authenticated.
7289 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7290 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7291 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7292 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007293 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007294 // Prioritize the venue information URL from the network agent if the source is
7295 // authenticated.
7296 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7297 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7298 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7299 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007300 }
7301 return captivePortalBuilder.build();
7302 }
7303
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007304 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007305 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007306 // marks on unsupported interfaces is harmless.
7307 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7308 return;
7309 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007310
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007311 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7312 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7313
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007314 // Mask/mark of zero will not detect anything interesting.
7315 // Don't install rules unless both values are nonzero.
7316 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007317 return;
7318 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007319
7320 final String prefix = "iface:" + iface;
7321 try {
7322 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007323 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007324 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007325 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007326 }
7327 } catch (Exception e) {
7328 loge("Exception modifying wakeup packet monitoring: " + e);
7329 }
7330
Joel Scherpelza235a812017-05-22 13:47:41 +09007331 }
7332
Chalard Jean9589e722019-11-19 19:03:53 +09007333 private void updateInterfaces(final @Nullable LinkProperties newLp,
7334 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007335 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09007336 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fa7d9e2017-08-22 16:35:52 +01007337 oldLp != null ? oldLp.getAllInterfaceNames() : null,
7338 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jean9589e722019-11-19 19:03:53 +09007339 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007340 for (final String iface : interfaceDiff.added) {
7341 try {
7342 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007343 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09007344 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007345 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7346 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007347 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007348 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007349 }
Paul Jensenbff73492014-04-28 10:33:11 -04007350 }
7351 }
Chalard Jean9589e722019-11-19 19:03:53 +09007352 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007353 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007354 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007355 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007356 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007357 } catch (Exception e) {
7358 loge("Exception removing interface: " + e);
7359 }
7360 }
7361 }
7362
Tyler Weare4314862019-12-05 14:55:30 -08007363 // TODO: move to frameworks/libs/net.
7364 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7365 final String nextHop;
7366
7367 switch (route.getType()) {
7368 case RouteInfo.RTN_UNICAST:
7369 if (route.hasGateway()) {
7370 nextHop = route.getGateway().getHostAddress();
7371 } else {
7372 nextHop = INetd.NEXTHOP_NONE;
7373 }
7374 break;
7375 case RouteInfo.RTN_UNREACHABLE:
7376 nextHop = INetd.NEXTHOP_UNREACHABLE;
7377 break;
7378 case RouteInfo.RTN_THROW:
7379 nextHop = INetd.NEXTHOP_THROW;
7380 break;
7381 default:
7382 nextHop = INetd.NEXTHOP_NONE;
7383 break;
7384 }
7385
7386 final RouteInfoParcel rip = new RouteInfoParcel();
7387 rip.ifName = route.getInterface();
7388 rip.destination = route.getDestination().toString();
7389 rip.nextHop = nextHop;
7390 rip.mtu = route.getMtu();
7391
7392 return rip;
7393 }
7394
Paul Jensene0fd4a82014-08-06 15:51:33 -04007395 /**
7396 * Have netd update routes from oldLp to newLp.
7397 * @return true if routes changed between oldLp and newLp
7398 */
7399 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007400 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007401 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7402 new CompareOrUpdateResult<>(
7403 oldLp != null ? oldLp.getAllRoutes() : null,
7404 newLp != null ? newLp.getAllRoutes() : null,
7405 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007406
7407 // add routes before removing old in case it helps with continuous connectivity
7408
Chalard Jean9dd11612018-06-04 16:52:49 +09007409 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007410 for (RouteInfo route : routeDiff.added) {
7411 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007412 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007413 try {
Tyler Weare4314862019-12-05 14:55:30 -08007414 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007415 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007416 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007417 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007418 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007419 }
7420 }
7421 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007422 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007423 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007424 try {
Tyler Weare4314862019-12-05 14:55:30 -08007425 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007426 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007427 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007428 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007429 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007430 }
7431 }
7432
7433 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007434 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007435 try {
Tyler Weare4314862019-12-05 14:55:30 -08007436 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007437 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007438 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007439 }
7440 }
Tyler Weare4314862019-12-05 14:55:30 -08007441
7442 for (RouteInfo route : routeDiff.updated) {
7443 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7444 try {
7445 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7446 } catch (Exception e) {
7447 loge("Exception in networkUpdateRouteParcel: " + e);
7448 }
7449 }
7450 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7451 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007452 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007453
Erik Klineb9888902016-04-05 13:30:49 +09007454 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7455 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7456 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007457 }
Erik Klineb9888902016-04-05 13:30:49 +09007458
Erik Kline31b4a9e2018-01-11 21:07:29 +09007459 if (DBG) {
7460 final Collection<InetAddress> dnses = newLp.getDnsServers();
7461 log("Setting DNS servers for network " + netId + " to " + dnses);
7462 }
Erik Klineb9888902016-04-05 13:30:49 +09007463 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007464 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007465 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007466 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007467 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007468 }
Erik Kline54e35c02017-04-07 15:29:29 +09007469 }
7470
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007471 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7472 NetworkAgentInfo nai) {
7473 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
7474 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
7475 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
7476 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
7477
7478 if (!wasFiltering && !needsFiltering) {
7479 // Nothing to do.
7480 return;
7481 }
7482
7483 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7484 // Nothing changed.
7485 return;
7486 }
7487
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007488 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Qingxi Libb8da982020-01-17 17:54:27 -08007489 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007490 // TODO: this create a window of opportunity for apps to receive traffic between the time
7491 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007492 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007493 // old rules are being removed.
7494 if (wasFiltering) {
7495 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7496 }
7497 if (needsFiltering) {
7498 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7499 }
7500 }
7501
Valentin Iftime9fa35092019-09-24 13:32:13 +02007502 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007503 if (mWolSupportedInterfaces == null) {
7504 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007505 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007506 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007507 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7508 }
7509
Luke Huangb913c812018-08-24 20:33:16 +08007510 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007511 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007512 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007513 }
7514 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007515 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007516 }
Luke Huangb913c812018-08-24 20:33:16 +08007517 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007518 }
7519
Chalard Jean62edfd82019-12-02 18:39:29 +09007520 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7521 @NonNull final NetworkCapabilities newNc) {
7522 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7523 final int newPermission = getNetworkPermission(newNc);
7524 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7525 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007526 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08007527 } catch (RemoteException | ServiceSpecificException e) {
7528 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09007529 }
7530 }
7531 }
7532
Paul Jensen53f08952015-06-16 14:27:36 -04007533 /**
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007534 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7535 * Stores into |nai| any data coming from the agent that might also be written to the network's
7536 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7537 * agent is not lost when updateCapabilities is called.
7538 */
7539 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
Chalard Jean15228572022-01-28 19:29:12 +09007540 if (nc.hasConnectivityManagedCapability()) {
7541 Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
7542 }
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007543 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7544 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7545 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7546 // the owner UID here and behave as if the agent had never tried to change it.
Lorenzo Colitti93401342020-12-09 18:30:52 +09007547 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7548 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7549 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7550 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7551 }
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007552 nai.declaredCapabilities = new NetworkCapabilities(nc);
Chalard Jeanac9ace02022-01-26 16:54:05 +09007553 NetworkAgentInfo.restrictCapabilitiesFromNetworkAgent(nc, nai.creatorUid,
7554 mCarrierPrivilegeAuthenticator);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007555 }
7556
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007557 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007558 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09007559 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007560 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08007561 underlyingNetworks = underlyingNetworksOrDefault(
7562 agentCaps.getOwnerUid(), underlyingNetworks);
lifrade6c2a2021-03-04 14:08:08 +08007563 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007564 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7565 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007566 // metered if any underlying is metered, or originally declared metered by the agent.
7567 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007568 boolean roaming = false; // roaming if any underlying is roaming
7569 boolean congested = false; // congested if any underlying is congested
7570 boolean suspended = true; // suspended if all underlying are suspended
7571
7572 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08007573 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007574 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08007575 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007576 for (Network underlyingNetwork : underlyingNetworks) {
7577 final NetworkAgentInfo underlying =
7578 getNetworkAgentInfoForNetwork(underlyingNetwork);
7579 if (underlying == null) continue;
7580
7581 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7582 hadUnderlyingNetworks = true;
7583 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007584 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007585 }
7586
7587 // Merge capabilities of this underlying network. For bandwidth, assume the
7588 // worst case.
7589 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7590 underlyingCaps.getLinkDownstreamBandwidthKbps());
7591 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7592 underlyingCaps.getLinkUpstreamBandwidthKbps());
7593 // If this underlying network is metered, the VPN is metered (it may cost money
7594 // to send packets on this network).
7595 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7596 // If this underlying network is roaming, the VPN is roaming (the billing structure
7597 // is different than the usual, local one).
7598 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7599 // If this underlying network is congested, the VPN is congested (the current
7600 // condition of the network affects the performance of this network).
7601 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7602 // If this network is not suspended, the VPN is not suspended (the VPN
7603 // is able to transfer some data).
7604 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08007605 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007606 }
7607 }
7608 if (!hadUnderlyingNetworks) {
7609 // No idea what the underlying networks are; assume reasonable defaults
7610 metered = true;
7611 roaming = false;
7612 congested = false;
7613 suspended = false;
7614 }
7615
lifrade6c2a2021-03-04 14:08:08 +08007616 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007617 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7618 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7619 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7620 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7621 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7622 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08007623 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007624 }
7625
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007626 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007627 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7628 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7629 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04007630 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007631 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007632 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09007633 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007634 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7635 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007636 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007637 // avoid connect/teardown loops.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007638 if (nai.everConnected &&
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007639 !nai.isVPN() &&
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007640 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7641 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09007642 // does not cause any request (that is not a listen) currently matching that agent to
7643 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007644 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09007645 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007646 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09007647 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007648 }
7649
Paul Jensen53f08952015-06-16 14:27:36 -04007650 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007651 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensende49eb12015-06-25 15:30:08 -04007652 if (nai.lastValidated) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007653 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007654 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007655 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007656 }
Paul Jensende49eb12015-06-25 15:30:08 -04007657 if (nai.lastCaptivePortalDetected) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007658 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007659 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007660 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007661 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007662 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007663 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007664 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007665 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007666 }
lucaslin2240ef62019-03-12 13:08:03 +08007667 if (nai.partialConnectivity) {
7668 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7669 } else {
7670 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7671 }
lucasline117e2e2019-10-22 18:27:33 +08007672 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007673
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007674 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09007675 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7676 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007677 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09007678 }
7679
Lorenzo Colittibd079452021-07-02 11:47:57 +09007680 if (nai.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007681 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7682 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007683 }
7684
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007685 return newNc;
7686 }
7687
Lorenzo Colitti44840702021-01-11 22:27:57 +09007688 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7689 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7690 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7691 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7692 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7693 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7694 if (prevSuspended != suspended) {
7695 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7696 // onResumed have been removed.
7697 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7698 : ConnectivityManager.CALLBACK_RESUMED);
7699 }
7700 if (prevSuspended != suspended || prevRoaming != roaming) {
7701 // updateNetworkInfo will mix in the suspended info from the capabilities and
7702 // take appropriate action for the network having possibly changed state.
7703 updateNetworkInfo(nai, nai.networkInfo);
7704 }
7705 }
7706
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007707 /**
7708 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7709 *
7710 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7711 * capabilities we manage and store in {@code nai}, such as validated status and captive
7712 * portal status)
7713 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7714 * potentially triggers rematches.
7715 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7716 * change.)
7717 *
7718 * @param oldScore score of the network before any of the changes that prompted us
7719 * to call this function.
7720 * @param nai the network having its capabilities updated.
7721 * @param nc the new network capabilities.
7722 */
Chalard Jean62edfd82019-12-02 18:39:29 +09007723 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7724 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007725 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007726 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean62edfd82019-12-02 18:39:29 +09007727 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09007728 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007729
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007730 updateVpnUids(nai, prevNc, newNc);
7731 updateAccessUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09007732 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007733
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007734 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007735 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7736 // the change we're processing can't affect any requests, it can only affect the listens
7737 // on this network. We might have been called by rematchNetworkAndRequests when a
7738 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09007739 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007740 } else {
7741 // If the requestable capabilities have changed or the score changed, we can't have been
7742 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09007743 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04007744 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07007745 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09007746 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007747
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007748 final boolean oldMetered = prevNc.isMetered();
7749 final boolean newMetered = newNc.isMetered();
7750 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08007751
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007752 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00007753 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7754 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007755 }
junyulaif2c67e42018-08-07 19:50:45 +08007756
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007757 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7758 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08007759
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007760 // Report changes that are interesting for network statistics tracking.
7761 if (meteredChanged || roamingChanged) {
7762 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06007763 }
7764
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007765 // This network might have been underlying another network. Propagate its capabilities.
7766 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08007767
7768 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007769 mDnsManager.updateTransportsForNetwork(
7770 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08007771 }
lucaslin53e8a262021-06-08 01:43:59 +08007772
7773 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007774 }
7775
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007776 /** Convenience method to update the capabilities for a given network. */
7777 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7778 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7779 }
7780
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007781 /**
7782 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7783 * network.
7784 *
7785 * Ingress interface filtering enforces that all apps under the given network can only receive
7786 * packets from the network's interface (and loopback). This is important for VPNs because
7787 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7788 * non-VPN interfaces.
7789 *
7790 * As a result, this method should return true iff
7791 * 1. the network is an app VPN (not legacy VPN)
7792 * 2. the VPN does not allow bypass
7793 * 3. the VPN is fully-routed
7794 * 4. the VPN interface is non-null
7795 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007796 * @see INetd#firewallAddUidInterfaceRules
7797 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007798 */
7799 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7800 LinkProperties lp) {
7801 if (nc == null || lp == null) return false;
7802 return nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007803 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08007804 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007805 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08007806 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7807 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007808 }
7809
Chiachang Wang28afaff2020-12-10 22:24:47 +08007810 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7811 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7812 int index = 0;
7813 for (UidRange range : ranges) {
7814 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7815 index++;
7816 }
7817 return stableRanges;
7818 }
7819
Chalard Jeane6c95272022-01-25 21:04:21 +09007820 private static UidRangeParcel[] intsToUidRangeStableParcels(
7821 final @NonNull ArraySet<Integer> uids) {
7822 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
7823 int index = 0;
7824 for (int uid : uids) {
7825 stableRanges[index] = new UidRangeParcel(uid, uid);
7826 index++;
7827 }
7828 return stableRanges;
7829 }
7830
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007831 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7832 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7833 for (int i = 0; i < ranges.length; i++) {
7834 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7835 }
7836 return stableRanges;
7837 }
7838
Ken Chen5e65a852020-12-24 12:59:10 +08007839 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7840 int[] exemptUids) {
7841 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7842 try {
7843 mNetd.socketDestroy(ranges, exemptUids);
7844 } catch (Exception e) {
7845 loge("Exception in socket destroy: ", e);
7846 }
7847 }
7848 }
7849
paulhuaa0743d2021-05-26 21:56:03 +08007850 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08007851 int[] exemptUids = new int[2];
7852 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7853 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7854 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7855 exemptUids[0] = VPN_UID;
7856 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7857 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7858
7859 maybeCloseSockets(nai, ranges, exemptUids);
7860 try {
7861 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08007862 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007863 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08007864 } else {
paulhu0e79d952021-06-09 16:11:35 +08007865 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007866 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08007867 }
7868 } catch (Exception e) {
7869 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7870 " on netId " + nai.network.netId + ". " + e);
7871 }
7872 maybeCloseSockets(nai, ranges, exemptUids);
7873 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007874
lucaslin53e8a262021-06-08 01:43:59 +08007875 private boolean isProxySetOnAnyDefaultNetwork() {
7876 ensureRunningOnConnectivityServiceThread();
7877 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7878 final NetworkAgentInfo nai = nri.getSatisfier();
7879 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
7880 return true;
7881 }
7882 }
7883 return false;
7884 }
7885
7886 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7887 NetworkCapabilities newNc) {
7888 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
7889 // the proxy might be changed since the default network satisfied by the apps might also
7890 // changed.
7891 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
7892 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09007893 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
7894 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
7895 if (nai.isVPN() && nai.everConnected && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08007896 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
7897 mProxyTracker.sendProxyBroadcast();
7898 }
7899 }
7900
Chalard Jeane6c95272022-01-25 21:04:21 +09007901 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
7902 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007903 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7904 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007905 if (null == prevRanges) prevRanges = new ArraySet<>();
7906 if (null == newRanges) newRanges = new ArraySet<>();
7907 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
7908
7909 prevRanges.removeAll(newRanges);
7910 newRanges.removeAll(prevRangesCopy);
7911
7912 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007913 // When updating the VPN uid routing rules, add the new range first then remove the old
7914 // range. If old range were removed first, there would be a window between the old
7915 // range being removed and the new range being added, during which UIDs contained
7916 // in both ranges are not subject to any VPN routing rules. Adding new range before
7917 // removing old range works because, unlike the filtering rules below, it's possible to
7918 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08007919 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
7920 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
7921 // [1-5] & [1-2],[4-5] == [3]
7922 // Then we can do:
7923 // maybeCloseSockets([3])
7924 // mNetd.networkAddUidRanges([1-2],[4-5])
7925 // mNetd.networkRemoveUidRanges([1-5])
7926 // maybeCloseSockets([3])
7927 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
7928 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09007929 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08007930 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007931 }
7932 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08007933 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007934 }
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007935 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
7936 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
7937 final String iface = nai.linkProperties.getInterfaceName();
7938 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09007939 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007940 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
7941 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
7942 // were added first and then newRanges got removed later, there would be only one uid
7943 // 10013 left. A consequence of removing old ranges before adding new ranges is that
7944 // there is now a window of opportunity when the UIDs are not subject to any filtering.
7945 // Note that this is in contrast with the (more robust) update of VPN routing rules
7946 // above, where the addition of new ranges happens before the removal of old ranges.
7947 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
7948 // to be removed will never overlap with the new range to be added.
7949 if (wasFiltering && !prevRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08007950 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007951 }
7952 if (shouldFilter && !newRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08007953 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007954 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09007955 } catch (Exception e) {
7956 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007957 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007958 }
7959 }
7960
Chalard Jeane6c95272022-01-25 21:04:21 +09007961 private void updateAccessUids(@NonNull NetworkAgentInfo nai,
7962 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
7963 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
7964 final boolean prevEmpty = null == prevNc || prevNc.getAccessUidsNoCopy().isEmpty();
7965 final boolean newEmpty = null == newNc || newNc.getAccessUidsNoCopy().isEmpty();
7966 if (prevEmpty && newEmpty) return;
7967
7968 final ArraySet<Integer> prevUids =
7969 null == prevNc ? new ArraySet<>() : prevNc.getAccessUidsNoCopy();
7970 final ArraySet<Integer> newUids =
7971 null == newNc ? new ArraySet<>() : newNc.getAccessUidsNoCopy();
7972
7973 if (prevUids.equals(newUids)) return;
7974
7975 // This implementation is very simple and vastly faster for sets of Integers than
7976 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
7977 // a key computed from the value and has storage for that.
7978 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
7979 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
7980 toRemove.removeAll(newUids);
7981 toAdd.removeAll(prevUids);
7982
7983 try {
7984 if (!toAdd.isEmpty()) {
7985 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
7986 nai.network.netId,
7987 intsToUidRangeStableParcels(toAdd),
7988 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
7989 }
7990 if (!toRemove.isEmpty()) {
7991 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
7992 nai.network.netId,
7993 intsToUidRangeStableParcels(toRemove),
7994 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
7995 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007996 } catch (ServiceSpecificException e) {
7997 // Has the interface disappeared since the network was built ?
7998 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09007999 } catch (RemoteException e) {
8000 // Netd died. This usually causes a runtime restart anyway.
8001 }
8002 }
8003
Hugo Benichi9d35b752017-09-01 01:23:32 +00008004 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008005 ensureRunningOnConnectivityServiceThread();
8006
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008007 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008008 // Ignore updates for disconnected networks
8009 return;
8010 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008011 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008012 log("Update of LinkProperties for " + nai.toShortString()
8013 + "; created=" + nai.created
8014 + "; everConnected=" + nai.everConnected);
Hugo Benichi9d35b752017-09-01 01:23:32 +00008015 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008016 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8017 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008018 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008019 }
8020
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008021 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8022 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008023 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008024 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008025 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008026 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8027 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8028 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008029 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8030 // need to be sent as a separate extra.
8031 final NetworkRequest req = nri.isMultilayerRequest()
8032 ? nri.getActiveRequest()
8033 // Non-multilayer listen requests do not have an active request
8034 : nri.mRequests.get(0);
8035 if (req == null) {
8036 Log.wtf(TAG, "No request in NRI " + nri);
8037 }
8038 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008039 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008040 sendIntent(nri.mPendingIntent, intent);
8041 }
8042 // else not handled
8043 }
8044
8045 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8046 mPendingIntentWakeLock.acquire();
8047 try {
8048 if (DBG) log("Sending " + pendingIntent);
8049 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
8050 } catch (PendingIntent.CanceledException e) {
8051 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8052 mPendingIntentWakeLock.release();
8053 releasePendingNetworkRequest(pendingIntent);
8054 }
8055 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8056 }
8057
8058 @Override
8059 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8060 String resultData, Bundle resultExtras) {
8061 if (DBG) log("Finished sending " + pendingIntent);
8062 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008063 // Release with a delay so the receiving client has an opportunity to put in its
8064 // own request.
8065 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008066 }
8067
James Mattis212df9e2020-12-03 19:57:41 -08008068 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
8069 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
8070 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008071 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008072 // Default request has no msgr. Also prevents callbacks from being invoked for
8073 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8074 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8075 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008076 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008077 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008078 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008079 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008080 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008081 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008082 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008083 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8084 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008085 }
Roshan Pius951c0032020-12-22 15:10:42 -08008086 final boolean includeLocationSensitiveInfo =
8087 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008088 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008089 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008090 final NetworkCapabilities nc =
8091 networkCapabilitiesRestrictedForCallerPermissions(
8092 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8093 putParcelable(
8094 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008095 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008096 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008097 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008098 nri.mCallingAttributionTag));
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008099 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8100 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008101 // For this notification, arg1 contains the blocked status.
8102 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008103 break;
8104 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008105 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008106 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008107 break;
8108 }
8109 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008110 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008111 final NetworkCapabilities netCap =
8112 networkCapabilitiesRestrictedForCallerPermissions(
8113 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8114 putParcelable(
8115 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008116 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008117 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008118 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008119 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008120 break;
8121 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008122 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008123 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8124 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008125 break;
8126 }
junyulaif2c67e42018-08-07 19:50:45 +08008127 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008128 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008129 msg.arg1 = arg1;
8130 break;
8131 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008132 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008133 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008134 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008135 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008136 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008137 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008138 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008139 }
James Mattis45d81842021-01-10 14:24:24 -08008140 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008141 } catch (RemoteException e) {
8142 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008143 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008144 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008145 }
8146
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008147 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8148 bundle.putParcelable(t.getClass().getSimpleName(), t);
8149 }
8150
Chalard Jean0702f982021-09-16 21:50:07 +09008151 /**
8152 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8153 *
8154 * When a request should be assigned to a new network, it is normally lingered to give
8155 * time for apps to gracefully migrate their connections. When both networks are on the same
8156 * radio, but that radio can't do time-sharing efficiently, this may end up being
8157 * counter-productive because any traffic on the old network may drastically reduce the
8158 * performance of the new network.
8159 * The stack supports a configuration to let modem vendors state that their radio can't
8160 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8161 * from one cell network to another can't be done gracefully.
8162 *
8163 * @param oldNai the old network serving the request
8164 * @param newNai the new network serving the request
8165 * @return whether the switch can be graceful
8166 */
8167 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8168 @NonNull final NetworkAgentInfo newSatisfier) {
8169 if (mCellularRadioTimesharingCapable) return true;
8170 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8171 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8172 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8173 }
8174
Paul Jensenaf94b982014-09-30 15:37:41 -04008175 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008176 if (nai.numRequestNetworkRequests() != 0) {
8177 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8178 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008179 // Ignore listening and track default requests.
8180 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008181 loge("Dead network still had at least " + nr);
8182 break;
8183 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008184 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008185 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008186 }
8187
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008188 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8189 if (oldNetwork == null) {
8190 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8191 return;
8192 }
Chalard Jean49707572019-12-10 21:07:02 +09008193 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008194
8195 // If we get here it means that the last linger timeout for this network expired. So there
8196 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008197 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008198
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008199 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008200 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008201 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008202 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008203 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008204 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008205 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008206 }
8207
James Mattise3ef1912020-12-20 11:09:58 -08008208 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8209 boolean isDefaultChanged = false;
8210 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8211 final NetworkReassignment.RequestReassignment reassignment =
8212 changes.getReassignment(defaultRequestInfo);
8213 if (null == reassignment) {
8214 continue;
8215 }
8216 // reassignment only contains those instances where the satisfying network changed.
8217 isDefaultChanged = true;
8218 // Notify system services of the new default.
8219 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8220 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008221
James Mattise3ef1912020-12-20 11:09:58 -08008222 if (isDefaultChanged) {
8223 // Hold a wakelock for a short time to help apps in migrating to a new default.
8224 scheduleReleaseNetworkTransitionWakelock();
8225 }
8226 }
8227
8228 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8229 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8230 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8231 if (DBG) {
8232 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8233 }
Chalard Jean8e382112019-12-03 20:45:30 +09008234
James Mattisd31bdfa2020-12-23 16:37:26 -08008235 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8236 if (newDefaultNetwork != null) {
8237 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008238 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008239
James Mattisd31bdfa2020-12-23 16:37:26 -08008240 // Set an app level managed default and return since further processing only applies to the
8241 // default network.
8242 if (mDefaultRequest != nri) {
8243 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8244 return;
8245 }
8246
8247 makeDefaultNetwork(newDefaultNetwork);
8248
James Mattise3ef1912020-12-20 11:09:58 -08008249 if (oldDefaultNetwork != null) {
8250 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8251 }
8252 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008253 handleApplyDefaultProxy(null != newDefaultNetwork
8254 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8255 updateTcpBufferSizes(null != newDefaultNetwork
8256 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008257 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008258 }
8259
James Mattisd31bdfa2020-12-23 16:37:26 -08008260 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8261 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8262 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8263 try {
8264 if (VDBG) {
8265 log("Setting default network for " + nri
8266 + " using UIDs " + nri.getUids()
8267 + " with old network " + (oldDefaultNetwork != null
8268 ? oldDefaultNetwork.network().getNetId() : "null")
8269 + " and new network " + (newDefaultNetwork != null
8270 ? newDefaultNetwork.network().getNetId() : "null"));
8271 }
8272 if (nri.getUids().isEmpty()) {
8273 throw new IllegalStateException("makeDefaultForApps called without specifying"
8274 + " any applications to set as the default." + nri);
8275 }
8276 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008277 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008278 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008279 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008280 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008281 }
8282 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008283 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008284 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008285 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008286 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008287 }
8288 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008289 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008290 }
8291 }
8292
8293 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8294 try {
8295 if (null != newDefaultNetwork) {
8296 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8297 } else {
8298 mNetd.networkClearDefault();
8299 }
8300 } catch (RemoteException | ServiceSpecificException e) {
8301 loge("Exception setting default network :" + e);
8302 }
8303 }
8304
Chalard Jean05cbe972019-12-09 11:50:38 +09008305 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008306 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09008307 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09008308 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09008309 processNewlySatisfiedListenRequests(nai);
8310 }
8311
8312 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008313 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8314 if (nri.isMultilayerRequest()) {
8315 continue;
8316 }
8317 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008318 if (!nr.isListen()) continue;
8319 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08008320 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008321 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
8322 }
8323 }
Chalard Jeancd397a22019-11-22 22:33:33 +09008324 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008325
Chalard Jeancd397a22019-11-22 22:33:33 +09008326 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008327 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8328 if (nri.isMultilayerRequest()) {
8329 continue;
8330 }
8331 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008332 if (!nr.isListen()) continue;
8333 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
8334 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09008335 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008336 }
8337 }
8338 }
8339
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008340 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008341 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008342 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08008343 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09008344 @Nullable public final NetworkRequest mOldNetworkRequest;
8345 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008346 @Nullable public final NetworkAgentInfo mOldNetwork;
8347 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08008348 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008349 @Nullable final NetworkRequest oldNetworkRequest,
8350 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008351 @Nullable final NetworkAgentInfo oldNetwork,
8352 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008353 mNetworkRequestInfo = networkRequestInfo;
8354 mOldNetworkRequest = oldNetworkRequest;
8355 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008356 mOldNetwork = oldNetwork;
8357 mNewNetwork = newNetwork;
8358 }
Chalard Jean49707572019-12-10 21:07:02 +09008359
8360 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09008361 final NetworkRequest requestToShow = null != mNewNetworkRequest
8362 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
8363 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08008364 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
8365 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09008366 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008367 }
8368
Chalard Jean46a62372019-12-10 21:25:24 +09008369 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008370
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008371 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09008372 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008373 }
8374
8375 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09008376 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09008377 // The code is never supposed to add two reassignments of the same request. Make
8378 // sure this stays true, but without imposing this expensive check on all
8379 // reassignments on all user devices.
8380 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08008381 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09008382 throw new IllegalStateException("Trying to reassign ["
8383 + reassignment + "] but already have ["
8384 + existing + "]");
8385 }
8386 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09008387 }
Chalard Jean46a62372019-12-10 21:25:24 +09008388 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008389 }
8390
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008391 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09008392 // the passed request.
8393 @Nullable
8394 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008395 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008396 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008397 }
8398 return null;
8399 }
Chalard Jean49707572019-12-10 21:07:02 +09008400
8401 public String toString() {
8402 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8403 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09008404 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008405 for (final RequestReassignment rr : getRequestReassignments()) {
8406 sj.add(rr.toString());
8407 }
8408 return sj.toString();
8409 }
8410
8411 public String debugString() {
8412 final StringBuilder sb = new StringBuilder();
8413 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09008414 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008415 for (final RequestReassignment rr : getRequestReassignments()) {
8416 sb.append("\n ").append(rr);
8417 }
8418 return sb.append("\n").toString();
8419 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008420 }
8421
Chalard Jean24344d72019-12-04 13:32:31 +09008422 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008423 @Nullable final NetworkRequest previousRequest,
8424 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09008425 @Nullable final NetworkAgentInfo previousSatisfier,
8426 @Nullable final NetworkAgentInfo newSatisfier,
8427 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08008428 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09008429 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09008430 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008431 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008432 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09008433 }
James Mattisa076c532020-12-02 14:12:41 -08008434 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean0702f982021-09-16 21:50:07 +09008435 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)) {
8436 // If this network switch can't be supported gracefully, the request is not
8437 // lingered. This allows letting go of the network sooner to reclaim some
8438 // performance on the new network, since the radio can't do both at the same
8439 // time while preserving good performance.
8440 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8441 }
Chalard Jean24344d72019-12-04 13:32:31 +09008442 } else {
8443 if (VDBG || DDBG) log(" accepting network in place of null");
8444 }
junyulai0ac374f2020-12-14 18:41:52 +08008445
8446 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8447 // and immediately satisfies a request then remove the timer. This will happen for
8448 // all networks except in the case of an underlying network for a VCN.
8449 if (newSatisfier.isNascent()) {
8450 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08008451 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008452 }
8453
Chalard Jean5d6e23b2021-03-01 22:00:20 +09008454 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08008455 newSatisfier.unlingerRequest(newRequest.requestId);
8456 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008457 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08008458 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008459 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09008460 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008461 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008462 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08008463 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008464 }
James Mattisa076c532020-12-02 14:12:41 -08008465 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008466 }
James Mattisa076c532020-12-02 14:12:41 -08008467 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008468 }
8469
James Mattisa076c532020-12-02 14:12:41 -08008470 /**
8471 * This function is triggered when something can affect what network should satisfy what
8472 * request, and it computes the network reassignment from the passed collection of requests to
8473 * network match to the one that the system should now have. That data is encoded in an
8474 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8475 * satisfier.
8476 *
8477 * After the reassignment is computed, it is applied to the state objects.
8478 *
8479 * @param networkRequests the nri objects to evaluate for possible network reassignment
8480 * @return NetworkReassignment listing of proposed network assignment changes
8481 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008482 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08008483 private NetworkReassignment computeNetworkReassignment(
8484 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09008485 final NetworkReassignment changes = new NetworkReassignment();
8486
Chalard Jeanc81d4c32021-04-07 17:06:19 +09008487 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09008488 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008489 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattisa076c532020-12-02 14:12:41 -08008490 if (!nai.everConnected) {
8491 continue;
8492 }
Chalard Jean857a1712019-12-10 21:08:07 +09008493 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09008494 }
Chalard Jean857a1712019-12-10 21:08:07 +09008495
James Mattisa076c532020-12-02 14:12:41 -08008496 for (final NetworkRequestInfo nri : networkRequests) {
8497 // Non-multilayer listen requests can be ignored.
8498 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8499 continue;
8500 }
8501 NetworkAgentInfo bestNetwork = null;
8502 NetworkRequest bestRequest = null;
8503 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09008504 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08008505 // Stop evaluating as the highest possible priority request is satisfied.
8506 if (null != bestNetwork) {
8507 bestRequest = req;
8508 break;
8509 }
8510 }
James Mattisd31bdfa2020-12-23 16:37:26 -08008511 if (null == bestNetwork && isDefaultBlocked(nri)) {
8512 // Remove default networking if disallowed for managed default requests.
8513 bestNetwork = mNoServiceNetwork;
8514 }
8515 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09008516 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09008517 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08008518 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09008519 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008520 }
8521 return changes;
8522 }
8523
James Mattisa076c532020-12-02 14:12:41 -08008524 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8525 return new HashSet<>(mNetworkRequests.values());
8526 }
8527
Paul Jensenc88b39b2015-06-16 14:27:36 -04008528 /**
James Mattisa076c532020-12-02 14:12:41 -08008529 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04008530 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04008531 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008532 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08008533 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8534 }
8535
8536 /**
8537 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8538 * being disconnected.
8539 */
8540 private void rematchNetworksAndRequests(
8541 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8542 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09008543 // TODO: This may be slow, and should be optimized.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008544 final long now = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08008545 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jean49707572019-12-10 21:07:02 +09008546 if (VDBG || DDBG) {
8547 log(changes.debugString());
8548 } else if (DBG) {
8549 log(changes.toString()); // Shorter form, only one line of log
8550 }
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008551 applyNetworkReassignment(changes, now);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008552 issueNetworkNeeds();
Chalard Jeand7f762d2019-12-10 19:01:29 +09008553 }
Chalard Jean64520dc2019-12-04 19:55:32 +09008554
Chalard Jeand7f762d2019-12-10 19:01:29 +09008555 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008556 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008557 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09008558
8559 // Since most of the time there are only 0 or 1 background networks, it would probably
8560 // be more efficient to just use an ArrayList here. TODO : measure performance
8561 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8562 for (final NetworkAgentInfo nai : nais) {
8563 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8564 }
8565
Chalard Jeand7f762d2019-12-10 19:01:29 +09008566 // First, update the lists of satisfied requests in the network agents. This is necessary
8567 // because some code later depends on this state to be correct, most prominently computing
8568 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09008569 for (final NetworkReassignment.RequestReassignment event :
8570 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008571 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8572 event.mOldNetworkRequest, event.mNewNetworkRequest,
8573 event.mOldNetwork, event.mNewNetwork,
8574 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09008575 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008576
James Mattise3ef1912020-12-20 11:09:58 -08008577 // Process default network changes if applicable.
8578 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008579
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008580 // Notify requested networks are available after the default net is switched, but
8581 // before LegacyTypeTracker sends legacy broadcasts
8582 for (final NetworkReassignment.RequestReassignment event :
8583 changes.getRequestReassignments()) {
8584 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008585 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008586 } else {
James Mattisa076c532020-12-02 14:12:41 -08008587 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008588 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008589 }
8590 }
8591
junyulai0ac374f2020-12-14 18:41:52 +08008592 // Update the inactivity state before processing listen callbacks, because the background
8593 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008594 // just yet though, because they have to be sent after the listens are processed to keep
8595 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08008596 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09008597 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08008598 // Rematching may have altered the inactivity state of some networks, so update all
8599 // inactivity timers. updateInactivityState reads the state from the network agent
8600 // and does nothing if the state has not changed : the source of truth is controlled
8601 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8602 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08008603 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08008604 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008605 }
8606 }
8607
Chalard Jeanb10ab412019-12-11 14:12:30 +09008608 for (final NetworkAgentInfo nai : nais) {
8609 if (!nai.everConnected) continue;
8610 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008611 // Process listen requests and update capabilities if the background state has
8612 // changed for this network. For consistency with previous behavior, send onLost
8613 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09008614 processNewlyLostListenRequests(nai);
8615 if (oldBackground != nai.isBackgroundNetwork()) {
8616 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008617 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09008618 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008619 }
8620
junyulai0ac374f2020-12-14 18:41:52 +08008621 for (final NetworkAgentInfo nai : inactiveNetworks) {
8622 // For nascent networks, if connecting with no foreground request, skip broadcasting
8623 // LOSING for backward compatibility. This is typical when mobile data connected while
8624 // wifi connected with mobile data always-on enabled.
8625 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008626 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008627 }
8628
James Mattise3ef1912020-12-20 11:09:58 -08008629 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09008630
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008631 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008632 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008633 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08008634 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008635 // This network has active linger timers and no requests, but is not
8636 // lingering. Linger it.
8637 //
8638 // One way (the only way?) this can happen if this network is unvalidated
8639 // and became unneeded due to another network improving its score to the
8640 // point where this network will no longer be able to satisfy any requests
8641 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08008642 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008643 notifyNetworkLosing(nai, now);
8644 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09008645 } else {
Chalard Jean49707572019-12-10 21:07:02 +09008646 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09008647 teardownUnneededNetwork(nai);
8648 }
8649 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04008650 }
8651 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008652
Chalard Jean62edfd82019-12-02 18:39:29 +09008653 /**
8654 * Apply a change in background state resulting from rematching networks with requests.
8655 *
8656 * During rematch, a network may change background states by starting to satisfy or stopping
8657 * to satisfy a foreground request. Listens don't count for this. When a network changes
8658 * background states, its capabilities need to be updated and callbacks fired for the
8659 * capability change.
8660 *
8661 * @param nai The network that changed background states
8662 */
8663 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8664 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8665 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8666 updateNetworkPermissions(nai, newNc);
8667 nai.getAndSetNetworkCapabilities(newNc);
8668 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8669 }
8670
Chalard Jeanf0344532019-11-19 19:23:38 +09008671 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08008672 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008673 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09008674 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8675 changes.getReassignment(mDefaultRequest);
8676 final NetworkAgentInfo oldDefaultNetwork =
8677 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8678 final NetworkAgentInfo newDefaultNetwork =
8679 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08008680
Chalard Jean5b409c72021-02-04 13:12:59 +09008681 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008682 // Maintain the illusion : since the legacy API only understands one network at a time,
8683 // if the default network changed, apps should see a disconnected broadcast for the
8684 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09008685 if (oldDefaultNetwork != null) {
8686 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8687 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008688 }
Chalard Jean5b409c72021-02-04 13:12:59 +09008689 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008690 // The new default network can be newly null if and only if the old default
8691 // network doesn't satisfy the default request any more because it lost a
8692 // capability.
Chalard Jean5b409c72021-02-04 13:12:59 +09008693 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08008694 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09008695 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008696 }
8697 }
8698
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008699 // Now that all the callbacks have been sent, send the legacy network broadcasts
8700 // as needed. This is necessary so that legacy requests correctly bind dns
8701 // requests to this network. The legacy users are listening for this broadcast
8702 // and will generally do a dns request so they can ensureRouteToHost and if
8703 // they do that before the callbacks happen they'll use the default network.
8704 //
8705 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8706 // callbacks, but if apps can receive the broadcast before the callback, they still might
8707 // have an inconsistent view of networking.
8708 //
8709 // This *does* introduce a race where if the user uses the new api
8710 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8711 // they may get old info. Reverse this after the old startUsing api is removed.
8712 // This is on top of the multiple intent sequencing referenced in the todo above.
8713 for (NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008714 if (nai.everConnected) {
8715 addNetworkToLegacyTypeTracker(nai);
8716 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08008717 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008718 }
8719
Chalard Jean0354d8c2021-01-12 10:58:56 +09008720 private void issueNetworkNeeds() {
8721 ensureRunningOnConnectivityServiceThread();
8722 for (final NetworkOfferInfo noi : mNetworkOffers) {
8723 issueNetworkNeeds(noi);
8724 }
8725 }
8726
8727 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8728 ensureRunningOnConnectivityServiceThread();
8729 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8730 informOffer(nri, noi.offer, mNetworkRanker);
8731 }
8732 }
8733
8734 /**
8735 * Inform a NetworkOffer about any new situation of a request.
8736 *
8737 * This function handles updates to offers. A number of events may happen that require
8738 * updating the registrant for this offer about the situation :
8739 * • The offer itself was updated. This may lead the offer to no longer being able
8740 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8741 * or conversely being strengthened enough to beat the satisfier (and therefore
8742 * start being needed)
8743 * • The network satisfying a request changed (including cases where the request
8744 * starts or stops being satisfied). The new network may be a stronger or weaker
8745 * match than the old one, possibly affecting whether the offer is needed.
8746 * • The network satisfying a request updated their score. This may lead the offer
8747 * to no longer be able to beat it if the current satisfier got better, or
8748 * conversely start being a good choice if the current satisfier got weaker.
8749 *
8750 * @param nri The request
8751 * @param offer The offer. This may be an updated offer.
8752 */
8753 private static void informOffer(@NonNull NetworkRequestInfo nri,
8754 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
8755 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
8756 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09008757
8758 // Multi-layer requests have a currently active request, the one being satisfied.
8759 // Since the system will try to bring up a better network than is currently satisfying
8760 // the request, NetworkProviders need to be told the offers matching the requests *above*
8761 // the currently satisfied one are needed, that the ones *below* the satisfied one are
8762 // not needed, and the offer is needed for the active request iff the offer can beat
8763 // the satisfier.
8764 // For non-multilayer requests, the logic above gracefully degenerates to only the
8765 // last case.
8766 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
8767 // providers that the offer is needed for this request, until the active request is found.
8768 // In a second phase, deal with the currently active request. In a third phase, inform
8769 // the providers that offer is unneeded for the remaining requests.
8770
8771 // First phase : inform providers of all requests above the active request.
8772 int i;
8773 for (i = 0; nri.mRequests.size() > i; ++i) {
8774 final NetworkRequest request = nri.mRequests.get(i);
8775 if (activeRequest == request) break; // Found the active request : go to phase 2
8776 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8777 // Since this request is higher-priority than the one currently satisfied, if the
8778 // offer can satisfy it, the provider should try and bring up the network for sure ;
8779 // no need to even ask the ranker – an offer that can satisfy is always better than
8780 // no network. Hence tell the provider so unless it already knew.
8781 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
8782 offer.onNetworkNeeded(request);
8783 }
8784 }
8785
8786 // Second phase : deal with the active request (if any)
8787 if (null != activeRequest && activeRequest.isRequest()) {
8788 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00008789 // If an offer can satisfy the request, it is considered needed if it is currently
8790 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09008791 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00008792 && satisfier.factorySerialNumber == offer.providerId
8793 && activeRequest.canBeSatisfiedBy(offer.caps);
8794 final boolean newNeeded = currentlyServing
8795 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008796 if (newNeeded != oldNeeded) {
8797 if (newNeeded) {
8798 offer.onNetworkNeeded(activeRequest);
8799 } else {
8800 // The offer used to be able to beat the satisfier. Now it can't.
8801 offer.onNetworkUnneeded(activeRequest);
8802 }
8803 }
8804 }
8805
8806 // Third phase : inform the providers that the offer isn't needed for any request
8807 // below the active one.
8808 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
8809 final NetworkRequest request = nri.mRequests.get(i);
8810 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8811 // Since this request is lower-priority than the one currently satisfied, if the
8812 // offer can satisfy it, the provider should not try and bring up the network.
8813 // Hence tell the provider so unless it already knew.
8814 if (offer.neededFor(request)) {
8815 offer.onNetworkUnneeded(request);
8816 }
8817 }
8818 }
8819
Chalard Jean61c79252019-11-07 23:07:32 +09008820 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8821 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8822 NetworkRequest nr = nai.requestAt(i);
8823 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8824 // legacy type tracker filters out repeat adds
8825 mLegacyTypeTracker.add(nr.legacyType, nai);
8826 }
8827 }
8828
8829 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09008830 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09008831 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8832 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8833 if (nai.isVPN()) {
8834 mLegacyTypeTracker.add(TYPE_VPN, nai);
8835 }
8836 }
8837
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008838 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04008839 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittia8de5ca2014-12-17 11:14:42 +09008840 if (!nai.everValidated) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09008841 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04008842 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09008843 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008844
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008845 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008846 // Don't repeat publish.
8847 if (newInetCondition == mDefaultInetConditionPublished) return;
8848
8849 mDefaultInetConditionPublished = newInetCondition;
8850 sendInetConditionBroadcast(nai.networkInfo);
8851 }
8852
Chalard Jeand61375d2020-01-14 22:46:36 +09008853 @NonNull
8854 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8855 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008856 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09008857 final boolean suspended =
8858 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8859 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8860 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8861 // state. This is because the network could have been suspended before connecting,
8862 // or it could be disconnecting while being suspended, and in both these cases
8863 // the state should not be overridden. Note that the only detailed state that
8864 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8865 // worry about multiple different substates of CONNECTED.
8866 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8867 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08008868 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8869 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8870 // network agent is created, then goes to suspended, then goes out of suspended without
8871 // ever setting connected. Check if network agent is ever connected to update the state.
8872 newInfo.setDetailedState(nai.everConnected
8873 ? NetworkInfo.DetailedState.CONNECTED
8874 : NetworkInfo.DetailedState.CONNECTING,
8875 info.getReason(),
8876 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09008877 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008878 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09008879 return newInfo;
8880 }
8881
8882 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8883 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8884
Erik Kline99f301b2017-02-15 19:59:17 +09008885 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008886 NetworkInfo oldInfo = null;
8887 synchronized (networkAgent) {
8888 oldInfo = networkAgent.networkInfo;
8889 networkAgent.networkInfo = newInfo;
8890 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008891
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008892 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008893 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8894 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008895 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07008896
Robin Leea8c0b6e2016-05-01 23:00:00 +01008897 if (!networkAgent.created
8898 && (state == NetworkInfo.State.CONNECTED
8899 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008900
8901 // A network that has just connected has zero requests and is thus a foreground network.
8902 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8903
Luke Huangfdd11f82019-04-09 18:41:49 +08008904 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09008905 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008906 // Initialize the network's capabilities to their starting values according to the
8907 // underlying networks. This ensures that the capabilities are correct before
8908 // anything happens to the network.
8909 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09008910 }
Paul Jensen74940202014-08-04 12:21:19 -04008911 networkAgent.created = true;
Chiachang Wang3f6cc072021-03-24 18:39:17 +08008912 networkAgent.onNetworkCreated();
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008913 updateAccessUids(networkAgent, null, networkAgent.networkCapabilities);
Robin Leea8c0b6e2016-05-01 23:00:00 +01008914 }
8915
8916 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
8917 networkAgent.everConnected = true;
8918
lucaslin45e639b2019-04-03 17:09:28 +08008919 // NetworkCapabilities need to be set before sending the private DNS config to
8920 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09008921 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
8922
Erik Kline9a62f012018-03-21 07:18:33 -07008923 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08008924 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
8925 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008926
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008927 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
8928 // command must be sent after updating LinkProperties to maximize chances of
8929 // NetworkMonitor seeing the correct LinkProperties when starting.
8930 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008931 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09008932 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008933 }
Chalard Jeand4900722022-02-06 12:25:38 +09008934 final NetworkMonitorParameters params = new NetworkMonitorParameters();
8935 params.networkAgentConfig = networkAgent.networkAgentConfig;
8936 params.networkCapabilities = networkAgent.networkCapabilities;
8937 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
8938 true /* parcelSensitiveFields */);
8939 networkAgent.networkMonitor().notifyNetworkConnected(params);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09008940 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008941
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008942 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
8943 // be communicated to a particular NetworkAgent depends only on the network's immutable,
8944 // capabilities, so it only needs to be done once on initial connect, not every time the
8945 // network's capabilities change. Note that we do this before rematching the network,
8946 // so we could decide to tear it down immediately afterwards. That's fine though - on
8947 // disconnection NetworkAgents should stop any signal strength monitoring they have been
8948 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09008949 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008950
junyulai0ac374f2020-12-14 18:41:52 +08008951 // Before first rematching networks, put an inactivity timer without any request, this
8952 // allows {@code updateInactivityState} to update the state accordingly and prevent
8953 // tearing down for any {@code unneeded} evaluation in this period.
8954 // Note that the timer will not be rescheduled since the expiry time is
8955 // fixed after connection regardless of the network satisfying other requests or not.
8956 // But it will be removed as soon as the network satisfies a request for the first time.
8957 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
8958 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08008959 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008960
Paul Jensen05e85ee2014-09-11 11:00:39 -04008961 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008962 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008963
8964 // This has to happen after matching the requests, because callbacks are just requests.
8965 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008966 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008967 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04008968 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008969 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04008970 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09008971 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00008972 if (networkAgent.isVPN()) {
8973 // As the active or bound network changes for apps, broadcast the default proxy, as
8974 // apps may need to update their proxy data. This is called after disconnecting from
8975 // VPN to make sure we do not broadcast the old proxy data.
8976 // TODO(b/122649188): send the broadcast only to VPN users.
8977 mProxyTracker.sendProxyBroadcast();
8978 }
Yintang Gu5014b522019-06-18 14:24:32 +08008979 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
8980 state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008981 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008982 }
8983 }
8984
Chalard Jean28018572020-12-21 18:36:52 +09008985 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09008986 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
8987 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008988 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07008989 }
8990
Erik Kline99f301b2017-02-15 19:59:17 +09008991 // Notify only this one new request of the current state. Transfer all the
8992 // current state by calling NetworkCapabilities and LinkProperties callbacks
8993 // so that callers can be guaranteed to have as close to atomicity in state
8994 // transfer as can be supported by this current API.
8995 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07008996 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09008997 if (nri.mPendingIntent != null) {
8998 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
8999 // Attempt no subsequent state pushes where intents are involved.
9000 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009001 }
Erik Kline99f301b2017-02-15 19:59:17 +09009002
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009003 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08009004 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009005 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
9006 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
9007 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08009008 }
9009
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009010 // Notify the requests on this NAI that the network is now lingered.
9011 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08009012 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009013 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
9014 }
9015
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009016 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
9017 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
9018 return vpnBlocked
9019 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
9020 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
9021 }
9022
9023 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
9024 if (blockedReasons == BLOCKED_REASON_NONE) {
9025 mUidBlockedReasons.delete(uid);
9026 } else {
9027 mUidBlockedReasons.put(uid, blockedReasons);
9028 }
9029 }
9030
junyulaif2c67e42018-08-07 19:50:45 +08009031 /**
9032 * Notify of the blocked state apps with a registered callback matching a given NAI.
9033 *
9034 * Unlike other callbacks, blocked status is different between each individual uid. So for
9035 * any given nai, all requests need to be considered according to the uid who filed it.
9036 *
9037 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009038 * @param oldMetered True if the previous network capabilities were metered.
9039 * @param newMetered True if the current network capabilities are metered.
9040 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
9041 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08009042 */
9043 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00009044 boolean newMetered, List<UidRange> oldBlockedUidRanges,
9045 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08009046
9047 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9048 NetworkRequest nr = nai.requestAt(i);
9049 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009050
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009051 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9052 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9053 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009054 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009055 : oldVpnBlocked;
9056
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009057 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9058 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9059 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009060 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009061 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009062 }
9063 }
9064 }
9065
9066 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009067 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009068 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009069 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009070 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009071 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009072 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009073 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009074 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009075
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009076 final int oldBlockedState = getBlockedState(
9077 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9078 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9079 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009080 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009081 }
junyulaif2c67e42018-08-07 19:50:45 +08009082 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9083 NetworkRequest nr = nai.requestAt(i);
9084 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009085 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009086 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
9087 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009088 }
9089 }
9090 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009091 }
9092
Chalard Jean3a3f5f22019-04-10 23:07:55 +09009093 @VisibleForTesting
9094 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09009095 // The NetworkInfo we actually send out has no bearing on the real
9096 // state of affairs. For example, if the default connection is mobile,
9097 // and a request for HIPRI has just gone away, we need to pretend that
9098 // HIPRI has just disconnected. So we need to set the type to HIPRI and
9099 // the state to DISCONNECTED, even though the network is of type MOBILE
9100 // and is still connected.
9101 NetworkInfo info = new NetworkInfo(nai.networkInfo);
9102 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09009103 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009104 if (state != DetailedState.DISCONNECTED) {
9105 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09009106 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009107 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009108 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07009109 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
9110 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
9111 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
9112 if (info.isFailover()) {
9113 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
9114 nai.networkInfo.setFailover(false);
9115 }
9116 if (info.getReason() != null) {
9117 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
9118 }
9119 if (info.getExtraInfo() != null) {
9120 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
9121 }
9122 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09009123 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08009124 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07009125 if (newDefaultAgent != null) {
9126 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
9127 newDefaultAgent.networkInfo);
9128 } else {
9129 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
9130 }
9131 }
9132 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
9133 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09009134 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009135 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09009136 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009137 }
9138 }
9139 }
9140
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009141 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009142 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009143 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09009144 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09009145 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009146 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
9147 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009148 NetworkRequestInfo nri = mNetworkRequests.get(nr);
9149 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009150 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009151 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009152 } else {
9153 sendPendingIntentForRequest(nri, networkAgent, notifyType);
9154 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009155 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009156 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009157
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009158 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
9159 notifyNetworkCallbacks(networkAgent, notifyType, 0);
9160 }
9161
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009162 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09009163 * Returns the list of all interfaces that could be used by network traffic that does not
9164 * explicitly specify a network. This includes the default network, but also all VPNs that are
9165 * currently connected.
9166 *
9167 * Must be called on the handler thread.
9168 */
junyulaie7c7d2a2021-01-26 15:29:15 +08009169 @NonNull
9170 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009171 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08009172 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08009173 final Set<Integer> activeNetIds = new ArraySet<>();
9174 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9175 if (nri.isBeingSatisfied()) {
9176 activeNetIds.add(nri.getSatisfier().network().netId);
9177 }
9178 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009179 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattis2516da32021-01-31 17:06:19 -08009180 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09009181 defaultNetworks.add(nai.network);
9182 }
9183 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009184 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09009185 }
9186
9187 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09009188 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
9189 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009190 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08009191 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009192 ensureRunningOnConnectivityServiceThread();
9193 String activeIface = null;
9194 LinkProperties activeLinkProperties = getActiveLinkProperties();
9195 if (activeLinkProperties != null) {
9196 activeIface = activeLinkProperties.getInterfaceName();
9197 }
Benedict Wong9308cd32019-06-12 17:46:31 +00009198
junyulai2050bed2021-01-23 09:46:34 +08009199 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009200 try {
junyulaide41fc22021-01-22 22:46:01 +08009201 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
junyulai69114da2021-03-05 14:46:25 +08009202 for (final NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaide41fc22021-01-22 22:46:01 +08009203 snapshots.add(snapshot);
9204 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009205 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
9206 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009207 } catch (Exception ignored) {
9208 }
9209 }
9210
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07009211 @Override
Udam Sainicd645462016-01-04 12:16:14 -08009212 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08009213 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009214 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009215 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009216
9217 if (!TextUtils.isEmpty(settingUrl)) {
9218 return settingUrl;
9219 }
9220
9221 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009222 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009223 if (!TextUtils.isEmpty(settingUrl)) {
9224 return settingUrl;
9225 }
9226
9227 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009228 }
9229
9230 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009231 public void startNattKeepalive(Network network, int intervalSeconds,
9232 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009233 enforceKeepalivePermission();
9234 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009235 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai070f9ff2019-01-16 20:23:34 +08009236 intervalSeconds, cb,
junyulai011b1f12019-01-03 18:50:15 +08009237 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009238 }
9239
9240 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009241 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009242 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulaid05a1922019-01-15 11:32:44 +08009243 String dstAddr) {
Josh Gao461a1222020-06-16 15:58:11 -07009244 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009245 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009246 mKeepaliveTracker.startNattKeepalive(
9247 getNetworkAgentInfoForNetwork(network), fd, resourceId,
9248 intervalSeconds, cb,
9249 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
9250 } finally {
9251 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9252 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009253 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9254 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009255 }
9256 }
junyulaid05a1922019-01-15 11:32:44 +08009257 }
9258
9259 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009260 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009261 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009262 try {
9263 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08009264 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009265 mKeepaliveTracker.startTcpKeepalive(
9266 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
9267 } finally {
9268 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9269 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009270 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9271 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009272 }
9273 }
junyulai0835a1e2019-01-08 20:04:33 +08009274 }
9275
9276 @Override
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009277 public void stopKeepalive(Network network, int slot) {
9278 mHandler.sendMessage(mHandler.obtainMessage(
junyulai011b1f12019-01-03 18:50:15 +08009279 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009280 }
9281
9282 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07009283 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08009284 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07009285
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009286 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08009287 final long token = Binder.clearCallingIdentity();
9288 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009289 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
9290 UserHandle.getUserHandleForUid(uid))) {
9291 return;
9292 }
9293
Heemin Seogdb8489d2019-06-12 09:21:44 -07009294 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
9295 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009296
9297 // Turn airplane mode off
9298 setAirplaneMode(false);
9299
9300 // restore private DNS settings to default mode (opportunistic)
9301 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
9302 UserHandle.getUserHandleForUid(uid))) {
9303 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
9304 PRIVATE_DNS_MODE_OPPORTUNISTIC);
9305 }
9306
9307 Settings.Global.putString(mContext.getContentResolver(),
9308 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08009309 } finally {
9310 Binder.restoreCallingIdentity(token);
9311 }
Stuart Scottd5463642015-04-02 18:00:02 -07009312 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04009313
Ricky Wai7097cc92018-01-23 04:09:45 +00009314 @Override
9315 public byte[] getNetworkWatchlistConfigHash() {
9316 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
9317 if (nwm == null) {
9318 loge("Unable to get NetworkWatchlistManager");
9319 return null;
9320 }
9321 // Redirect it to network watchlist service to access watchlist file and calculate hash.
9322 return nwm.getWatchlistConfigHash();
9323 }
9324
Hugo Benichibe0c7652016-05-31 16:28:06 +09009325 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09009326 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08009327 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09009328 }
Hugo Benichif4210292017-04-21 15:07:12 +09009329
9330 private static boolean toBool(int encodedBoolean) {
9331 return encodedBoolean != 0; // Only 0 means false.
9332 }
9333
9334 private static int encodeBool(boolean b) {
9335 return b ? 1 : 0;
9336 }
mswest4632928412018-03-12 10:34:34 -07009337
9338 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009339 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
9340 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
9341 @NonNull String[] args) {
9342 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
9343 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07009344 }
9345
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009346 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07009347 @Override
9348 public int onCommand(String cmd) {
9349 if (cmd == null) {
9350 return handleDefaultCommands(cmd);
9351 }
9352 final PrintWriter pw = getOutPrintWriter();
9353 try {
9354 switch (cmd) {
9355 case "airplane-mode":
9356 final String action = getNextArg();
9357 if ("enable".equals(action)) {
9358 setAirplaneMode(true);
9359 return 0;
9360 } else if ("disable".equals(action)) {
9361 setAirplaneMode(false);
9362 return 0;
9363 } else if (action == null) {
9364 final ContentResolver cr = mContext.getContentResolver();
9365 final int enabled = Settings.Global.getInt(cr,
9366 Settings.Global.AIRPLANE_MODE_ON);
9367 pw.println(enabled == 0 ? "disabled" : "enabled");
9368 return 0;
9369 } else {
9370 onHelp();
9371 return -1;
9372 }
9373 default:
9374 return handleDefaultCommands(cmd);
9375 }
9376 } catch (Exception e) {
9377 pw.println(e);
9378 }
9379 return -1;
9380 }
9381
9382 @Override
9383 public void onHelp() {
9384 PrintWriter pw = getOutPrintWriter();
9385 pw.println("Connectivity service commands:");
9386 pw.println(" help");
9387 pw.println(" Print this help text.");
9388 pw.println(" airplane-mode [enable|disable]");
9389 pw.println(" Turn airplane mode on or off.");
9390 pw.println(" airplane-mode");
9391 pw.println(" Get airplane mode.");
9392 }
9393 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009394
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09009395 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009396 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
9397 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
9398 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +08009399 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009400 }
9401
9402 /**
9403 * @param connectionInfo the connection to resolve.
9404 * @return {@code uid} if the connection is found and the app has permission to observe it
9405 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
9406 * connection is not found.
9407 */
9408 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009409 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
9410 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
9411 }
9412
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09009413 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009414 connectionInfo.local, connectionInfo.remote);
9415
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009416 if (uid == INVALID_UID) return uid; // Not found.
9417
9418 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
9419 // VPN, if any, that applies to the UID that owns the connection.
9420 if (checkNetworkStackPermission()) return uid;
9421
9422 final NetworkAgentInfo vpn = getVpnForUid(uid);
9423 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09009424 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009425 return INVALID_UID;
9426 }
9427
9428 return uid;
9429 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +00009430
Benedict Wong493e04b2018-11-09 14:45:34 -08009431 /**
9432 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
9433 *
9434 * <p>The TestNetworkService must be run in the system server due to TUN creation.
9435 */
9436 @Override
9437 public IBinder startOrGetTestNetworkService() {
9438 synchronized (mTNSLock) {
9439 TestNetworkService.enforceTestNetworkPermissions(mContext);
9440
9441 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +08009442 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -08009443 }
9444
9445 return mTNS;
9446 }
9447 }
Cody Kestingd199a9d2019-12-17 12:55:28 -08009448
Cody Kesting73708bf2019-12-18 10:57:50 -08009449 /**
9450 * Handler used for managing all Connectivity Diagnostics related functions.
9451 *
9452 * @see android.net.ConnectivityDiagnosticsManager
9453 *
9454 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9455 */
9456 @VisibleForTesting
9457 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009458 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9459
Cody Kesting73708bf2019-12-18 10:57:50 -08009460 /**
9461 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9462 * android.net.ConnectivityDiagnosticsManager}.
9463 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9464 * NetworkRequestInfo to be registered
9465 */
9466 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9467
9468 /**
9469 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9470 * android.net.ConnectivityDiagnosticsManager}.
9471 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9472 * arg1 = the uid of the caller
9473 */
9474 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9475
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009476 /**
9477 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
9478 * after processing {@link #EVENT_NETWORK_TESTED} events.
9479 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9480 * NetworkMonitor.
9481 * data = PersistableBundle of extras passed from NetworkMonitor.
9482 *
9483 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
9484 */
9485 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
9486
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009487 /**
9488 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9489 * been detected on the network.
9490 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9491 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9492 * arg2 = NetID.
9493 * data = PersistableBundle of extras passed from NetworkMonitor.
9494 */
9495 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9496
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009497 /**
9498 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9499 * the platform. This event will invoke {@link
9500 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9501 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -07009502 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009503 */
9504 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9505
Cody Kesting73708bf2019-12-18 10:57:50 -08009506 private ConnectivityDiagnosticsHandler(Looper looper) {
9507 super(looper);
9508 }
9509
9510 @Override
9511 public void handleMessage(Message msg) {
9512 switch (msg.what) {
9513 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9514 handleRegisterConnectivityDiagnosticsCallback(
9515 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9516 break;
9517 }
9518 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9519 handleUnregisterConnectivityDiagnosticsCallback(
9520 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9521 break;
9522 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009523 case EVENT_NETWORK_TESTED: {
9524 final ConnectivityReportEvent reportEvent =
9525 (ConnectivityReportEvent) msg.obj;
9526
Aaron Huang959d3642021-01-21 15:47:41 +08009527 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009528 break;
9529 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009530 case EVENT_DATA_STALL_SUSPECTED: {
9531 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +08009532 final Pair<Long, PersistableBundle> arg =
9533 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009534 if (nai == null) break;
9535
Aaron Huang959d3642021-01-21 15:47:41 +08009536 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009537 break;
9538 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009539 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -07009540 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009541 break;
9542 }
9543 default: {
9544 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9545 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009546 }
9547 }
9548 }
9549
9550 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9551 @VisibleForTesting
9552 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9553 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9554 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009555 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009556
9557 @VisibleForTesting
9558 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009559 @NonNull IConnectivityDiagnosticsCallback cb,
9560 @NonNull NetworkRequestInfo nri,
9561 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009562 mCb = cb;
9563 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009564 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009565 }
9566
9567 @Override
9568 public void binderDied() {
9569 log("ConnectivityDiagnosticsCallback IBinder died.");
9570 unregisterConnectivityDiagnosticsCallback(mCb);
9571 }
9572 }
9573
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009574 /**
9575 * Class used for sending information from {@link
9576 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9577 */
9578 private static class NetworkTestedResults {
9579 private final int mNetId;
9580 private final int mTestResult;
9581 private final long mTimestampMillis;
9582 @Nullable private final String mRedirectUrl;
9583
9584 private NetworkTestedResults(
9585 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9586 mNetId = netId;
9587 mTestResult = testResult;
9588 mTimestampMillis = timestampMillis;
9589 mRedirectUrl = redirectUrl;
9590 }
9591 }
9592
9593 /**
9594 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9595 * ConnectivityDiagnosticsHandler}.
9596 */
9597 private static class ConnectivityReportEvent {
9598 private final long mTimestampMillis;
9599 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +08009600 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009601
Aaron Huang959d3642021-01-21 15:47:41 +08009602 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9603 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009604 mTimestampMillis = timestampMillis;
9605 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +08009606 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009607 }
9608 }
9609
Cody Kestingf1120be2020-08-03 18:01:40 -07009610 /**
9611 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
9612 * ConnectivityDiagnosticsHandler}.
9613 */
9614 private static class ReportedNetworkConnectivityInfo {
9615 public final boolean hasConnectivity;
9616 public final boolean isNetworkRevalidating;
9617 public final int reporterUid;
9618 @NonNull public final NetworkAgentInfo nai;
9619
9620 private ReportedNetworkConnectivityInfo(
9621 boolean hasConnectivity,
9622 boolean isNetworkRevalidating,
9623 int reporterUid,
9624 @NonNull NetworkAgentInfo nai) {
9625 this.hasConnectivity = hasConnectivity;
9626 this.isNetworkRevalidating = isNetworkRevalidating;
9627 this.reporterUid = reporterUid;
9628 this.nai = nai;
9629 }
9630 }
9631
Cody Kesting73708bf2019-12-18 10:57:50 -08009632 private void handleRegisterConnectivityDiagnosticsCallback(
9633 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9634 ensureRunningOnConnectivityServiceThread();
9635
9636 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -08009637 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009638 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9639
James Mattis64b8b0f2020-11-24 17:40:49 -08009640 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9641 // confusing for these networks to change when an NRI is satisfied in another layer.
9642 if (nri.isMultilayerRequest()) {
9643 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9644 + "network requests.");
9645 }
9646
Cody Kesting73708bf2019-12-18 10:57:50 -08009647 // This means that the client registered the same callback multiple times. Do
9648 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -08009649 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009650 if (VDBG) log("Diagnostics callback is already registered");
9651
9652 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9653 // incremented when the NetworkRequestInfo is created as part of
9654 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009655 nri.decrementRequestCount();
Cody Kesting73708bf2019-12-18 10:57:50 -08009656 return;
9657 }
9658
Cody Kesting31f1ff62020-03-05 10:46:02 -08009659 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -08009660
9661 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -08009662 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009663 } catch (RemoteException e) {
9664 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -08009665 return;
9666 }
9667
9668 // Once registered, provide ConnectivityReports for matching Networks
9669 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9670 synchronized (mNetworkForNetId) {
9671 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9672 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -08009673 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9674 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -08009675 matchingNetworks.add(nai);
9676 }
9677 }
9678 }
9679 for (final NetworkAgentInfo nai : matchingNetworks) {
9680 final ConnectivityReport report = nai.getConnectivityReport();
9681 if (report == null) {
9682 continue;
9683 }
9684 if (!checkConnectivityDiagnosticsPermissions(
9685 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9686 continue;
9687 }
9688
9689 try {
9690 cb.onConnectivityReportAvailable(report);
9691 } catch (RemoteException e) {
9692 // Exception while sending the ConnectivityReport. Move on to the next network.
9693 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009694 }
9695 }
9696
9697 private void handleUnregisterConnectivityDiagnosticsCallback(
9698 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9699 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009700 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009701
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009702 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9703 mConnectivityDiagnosticsCallbacks.remove(iCb);
9704 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009705 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9706 return;
9707 }
9708
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009709 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -08009710
Cody Kesting70fa2b22020-12-02 12:16:56 -08009711 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9712 // (if the Binder died)
9713 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9714 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -08009715 return;
9716 }
9717
Cody Kesting46cb1672020-03-04 13:35:20 -08009718 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9719 // incremented when the NetworkRequestInfo is created as part of
9720 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009721 nri.decrementRequestCount();
Cody Kesting46cb1672020-03-04 13:35:20 -08009722
Cody Kesting31f1ff62020-03-05 10:46:02 -08009723 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009724 }
9725
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009726 private void handleNetworkTestedWithExtras(
9727 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9728 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -08009729 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009730 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009731 final ConnectivityReport report =
9732 new ConnectivityReport(
9733 reportEvent.mNai.network,
9734 reportEvent.mTimestampMillis,
9735 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009736 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009737 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -08009738 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -07009739
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009740 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009741 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009742 for (final IConnectivityDiagnosticsCallback cb : results) {
9743 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -08009744 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009745 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -07009746 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009747 }
9748 }
9749 }
9750
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009751 private void handleDataStallSuspected(
9752 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9753 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -08009754 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009755 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009756 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -08009757 new DataStallReport(
9758 nai.network,
9759 timestampMillis,
9760 detectionMethod,
9761 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009762 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -08009763 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009764 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009765 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009766 for (final IConnectivityDiagnosticsCallback cb : results) {
9767 try {
9768 cb.onDataStallSuspected(report);
9769 } catch (RemoteException ex) {
9770 loge("Error invoking onDataStallSuspected", ex);
9771 }
9772 }
9773 }
9774
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009775 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -07009776 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
9777 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
9778 final ConnectivityReport cachedReport = nai.getConnectivityReport();
9779
9780 // If the Network is being re-validated as a result of this call to
9781 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
9782 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009783 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009784 getMatchingPermissionedCallbacks(
9785 nai,
9786 reportedNetworkConnectivityInfo.isNetworkRevalidating
9787 ? Process.INVALID_UID
9788 : reportedNetworkConnectivityInfo.reporterUid);
9789
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009790 for (final IConnectivityDiagnosticsCallback cb : results) {
9791 try {
Cody Kestingf1120be2020-08-03 18:01:40 -07009792 cb.onNetworkConnectivityReported(
9793 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009794 } catch (RemoteException ex) {
9795 loge("Error invoking onNetworkConnectivityReported", ex);
9796 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009797
9798 // If the Network isn't re-validating, also provide the cached report. If there is no
9799 // cached report, the Network is still being validated and a report will be sent once
9800 // validation is complete. Note that networks which never undergo validation will still
9801 // have a cached ConnectivityReport with RESULT_SKIPPED.
9802 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
9803 try {
9804 cb.onConnectivityReportAvailable(cachedReport);
9805 } catch (RemoteException ex) {
9806 loge("Error invoking onConnectivityReportAvailable", ex);
9807 }
9808 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009809 }
9810 }
9811
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009812 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +09009813 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9814 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009815 sanitized.setUids(null);
9816 sanitized.setAdministratorUids(new int[0]);
9817 sanitized.setOwnerUid(Process.INVALID_UID);
9818 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -08009819 }
9820
Cody Kestingf1120be2020-08-03 18:01:40 -07009821 /**
9822 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
9823 *
9824 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
9825 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009826 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -07009827 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009828 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009829 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009830 mConnectivityDiagnosticsCallbacks.entrySet()) {
9831 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9832 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -07009833
James Mattis64b8b0f2020-11-24 17:40:49 -08009834 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -07009835 if (!nai.satisfies(nri.mRequests.get(0))) {
9836 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009837 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009838
9839 // UID for this callback must either be:
9840 // - INVALID_UID (which sends callbacks to all UIDs), or
9841 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
9842 // notified as a result)
9843 if (uid != Process.INVALID_UID && uid != nri.mUid) {
9844 continue;
9845 }
9846
9847 if (!checkConnectivityDiagnosticsPermissions(
9848 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9849 continue;
9850 }
9851
9852 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009853 }
9854 return results;
9855 }
9856
Cody Kesting7474f672021-05-11 14:22:40 -07009857 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
9858 @NonNull NetworkAgentInfo nai) {
9859 // TODO(b/188483916): replace with a transport-agnostic location-aware check
9860 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
9861 }
9862
Cody Kesting160ef392021-05-05 13:17:22 -07009863 private boolean hasLocationPermission(String packageName, int uid) {
9864 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9865 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9866 // call in a try-catch.
9867 try {
9868 if (!mLocationPermissionChecker.checkLocationPermission(
9869 packageName, null /* featureId */, uid, null /* message */)) {
9870 return false;
9871 }
9872 } catch (SecurityException e) {
9873 return false;
9874 }
9875
9876 return true;
9877 }
9878
9879 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
9880 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +09009881 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -07009882 && virtual.networkCapabilities.getOwnerUid() == uid
9883 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
9884 return true;
9885 }
9886 }
9887
9888 return false;
9889 }
9890
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009891 @VisibleForTesting
9892 boolean checkConnectivityDiagnosticsPermissions(
9893 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9894 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9895 return true;
9896 }
9897
Cody Kesting160ef392021-05-05 13:17:22 -07009898 // Administrator UIDs also contains the Owner UID
9899 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
9900 if (!CollectionUtils.contains(administratorUids, callbackUid)
9901 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009902 return false;
9903 }
9904
Cody Kesting7474f672021-05-11 14:22:40 -07009905 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
9906 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009907 }
9908
Cody Kestingd199a9d2019-12-17 12:55:28 -08009909 @Override
9910 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009911 @NonNull IConnectivityDiagnosticsCallback callback,
9912 @NonNull NetworkRequest request,
9913 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -07009914 Objects.requireNonNull(callback, "callback must not be null");
9915 Objects.requireNonNull(request, "request must not be null");
9916 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
9917
Cody Kesting73708bf2019-12-18 10:57:50 -08009918 if (request.legacyType != TYPE_NONE) {
9919 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
9920 + " Please use NetworkCapabilities instead.");
9921 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009922 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -08009923 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009924
9925 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
9926 // and administrator uids to be safe.
9927 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08009928 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009929
9930 final NetworkRequest requestWithId =
9931 new NetworkRequest(
9932 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
9933
9934 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
9935 //
9936 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
9937 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
9938 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009939 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -08009940 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009941 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009942
9943 mConnectivityDiagnosticsHandler.sendMessage(
9944 mConnectivityDiagnosticsHandler.obtainMessage(
9945 ConnectivityDiagnosticsHandler
9946 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9947 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -08009948 }
9949
9950 @Override
9951 public void unregisterConnectivityDiagnosticsCallback(
9952 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +08009953 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -08009954 mConnectivityDiagnosticsHandler.sendMessage(
9955 mConnectivityDiagnosticsHandler.obtainMessage(
9956 ConnectivityDiagnosticsHandler
9957 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009958 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -08009959 0,
9960 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -08009961 }
Cody Kestingf53a0752020-04-15 12:33:28 -07009962
9963 @Override
9964 public void simulateDataStall(int detectionMethod, long timestampMillis,
9965 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -07009966 Objects.requireNonNull(network, "network must not be null");
9967 Objects.requireNonNull(extras, "extras must not be null");
9968
Cody Kestingf53a0752020-04-15 12:33:28 -07009969 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
9970 android.Manifest.permission.NETWORK_STACK);
9971 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
9972 if (!nc.hasTransport(TRANSPORT_TEST)) {
Chalard Jean15228572022-01-28 19:29:12 +09009973 throw new SecurityException("Data Stall simulation is only possible for test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -07009974 }
9975
9976 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009977 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -07009978 throw new SecurityException("Data Stall simulation is only possible for network "
9979 + "creators");
9980 }
9981
Cody Kesting652e3ec2020-05-21 12:08:21 -07009982 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
9983 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
9984 // Data Stall information as a DataStallReportParcelable and passing to
9985 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
9986 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -07009987 final DataStallReportParcelable p = new DataStallReportParcelable();
9988 p.timestampMillis = timestampMillis;
9989 p.detectionMethod = detectionMethod;
9990
9991 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
9992 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
9993 }
9994 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
9995 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
9996 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
9997 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
9998 }
9999
Serik Beketayevec8ad212020-12-07 22:43:07 -080010000 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070010001 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010002
lucaslin66f44212021-02-23 01:12:55 +080010003 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
10004 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080010005 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080010006 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080010007 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080010008 }
lucaslin37a16d92021-01-21 19:48:09 +080010009
10010 @Override
10011 public void onInterfaceLinkStateChanged(String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080010012 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010013 nai.clatd.interfaceLinkStateChanged(iface, up);
10014 }
10015 }
10016
10017 @Override
10018 public void onInterfaceRemoved(String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080010019 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010020 nai.clatd.interfaceRemoved(iface);
10021 }
lucaslin66f44212021-02-23 01:12:55 +080010022 }
10023 }
10024
lucaslin1a8b4c62021-01-21 02:02:55 +080010025 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
10026
10027 /**
10028 * Class used for updating network activity tracking with netd and notify network activity
10029 * changes.
10030 */
10031 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080010032 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080010033 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080010034 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080010035 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
10036 new RemoteCallbackList<>();
10037 // Indicate the current system default network activity is active or not.
10038 @GuardedBy("mActiveIdleTimers")
10039 private boolean mNetworkActive;
10040 @GuardedBy("mActiveIdleTimers")
10041 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
10042 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010043
lucaslin1193a5d2021-01-21 02:04:15 +080010044 private class IdleTimerParams {
10045 public final int timeout;
10046 public final int transportType;
10047
10048 IdleTimerParams(int timeout, int transport) {
10049 this.timeout = timeout;
10050 this.transportType = transport;
10051 }
10052 }
10053
10054 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080010055 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080010056 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080010057 mNetd = netd;
10058 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010059 }
10060
lucaslin66f44212021-02-23 01:12:55 +080010061 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
10062 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
10063 synchronized (mActiveIdleTimers) {
10064 mNetworkActive = active;
10065 // If there are no idle timers, it means that system is not monitoring
10066 // activity, so the system default network for those default network
10067 // unspecified apps is always considered active.
10068 //
10069 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
10070 // any network activity change event. Whenever this event is received,
10071 // the mActiveIdleTimers should be always not empty. The legacy behavior
10072 // is no-op. Remove to refer to mNetworkActive only.
10073 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
10074 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
10075 }
10076 }
10077 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010078
lucaslin1193a5d2021-01-21 02:04:15 +080010079 // The network activity should only be updated from ConnectivityService handler thread
10080 // when mActiveIdleTimers lock is held.
10081 @GuardedBy("mActiveIdleTimers")
10082 private void reportNetworkActive() {
10083 final int length = mNetworkActivityListeners.beginBroadcast();
10084 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
10085 try {
10086 for (int i = 0; i < length; i++) {
10087 try {
10088 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
10089 } catch (RemoteException | RuntimeException e) {
10090 loge("Fail to send network activie to listener " + e);
10091 }
10092 }
10093 } finally {
10094 mNetworkActivityListeners.finishBroadcast();
10095 }
10096 }
10097
10098 @GuardedBy("mActiveIdleTimers")
10099 public void handleReportNetworkActivity() {
10100 synchronized (mActiveIdleTimers) {
10101 reportNetworkActive();
10102 }
10103 }
10104
lucaslin1a8b4c62021-01-21 02:02:55 +080010105 // This is deprecated and only to support legacy use cases.
10106 private int transportTypeToLegacyType(int type) {
10107 switch (type) {
10108 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010109 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080010110 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010111 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080010112 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010113 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080010114 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010115 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080010116 default:
10117 loge("Unexpected transport in transportTypeToLegacyType: " + type);
10118 }
10119 return ConnectivityManager.TYPE_NONE;
10120 }
10121
10122 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
10123 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
10124 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
10125 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
10126 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
10127 final long ident = Binder.clearCallingIdentity();
10128 try {
10129 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
10130 RECEIVE_DATA_ACTIVITY_CHANGE,
10131 null /* resultReceiver */,
10132 null /* scheduler */,
10133 0 /* initialCode */,
10134 null /* initialData */,
10135 null /* initialExtra */);
10136 } finally {
10137 Binder.restoreCallingIdentity(ident);
10138 }
10139 }
10140
10141 /**
10142 * Setup data activity tracking for the given network.
10143 *
10144 * Every {@code setupDataActivityTracking} should be paired with a
10145 * {@link #removeDataActivityTracking} for cleanup.
10146 */
10147 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
10148 final String iface = networkAgent.linkProperties.getInterfaceName();
10149
10150 final int timeout;
10151 final int type;
10152
10153 if (networkAgent.networkCapabilities.hasTransport(
10154 NetworkCapabilities.TRANSPORT_CELLULAR)) {
10155 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010156 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080010157 10);
10158 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10159 } else if (networkAgent.networkCapabilities.hasTransport(
10160 NetworkCapabilities.TRANSPORT_WIFI)) {
10161 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010162 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080010163 15);
10164 type = NetworkCapabilities.TRANSPORT_WIFI;
10165 } else {
10166 return; // do not track any other networks
10167 }
10168
lucaslinb961efc2021-01-21 02:03:17 +080010169 updateRadioPowerState(true /* isActive */, type);
10170
lucaslin1a8b4c62021-01-21 02:02:55 +080010171 if (timeout > 0 && iface != null) {
10172 try {
lucaslin1193a5d2021-01-21 02:04:15 +080010173 synchronized (mActiveIdleTimers) {
10174 // Networks start up.
10175 mNetworkActive = true;
10176 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
10177 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
10178 reportNetworkActive();
10179 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010180 } catch (Exception e) {
10181 // You shall not crash!
10182 loge("Exception in setupDataActivityTracking " + e);
10183 }
10184 }
10185 }
10186
10187 /**
10188 * Remove data activity tracking when network disconnects.
10189 */
10190 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
10191 final String iface = networkAgent.linkProperties.getInterfaceName();
10192 final NetworkCapabilities caps = networkAgent.networkCapabilities;
10193
lucaslinb961efc2021-01-21 02:03:17 +080010194 if (iface == null) return;
10195
10196 final int type;
10197 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
10198 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10199 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
10200 type = NetworkCapabilities.TRANSPORT_WIFI;
10201 } else {
10202 return; // do not track any other networks
10203 }
10204
10205 try {
10206 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080010207 synchronized (mActiveIdleTimers) {
10208 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
10209 // The call fails silently if no idle timer setup for this interface
10210 mNetd.idletimerRemoveInterface(iface, params.timeout,
10211 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080010212 }
lucaslinb961efc2021-01-21 02:03:17 +080010213 } catch (Exception e) {
10214 // You shall not crash!
10215 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080010216 }
10217 }
10218
10219 /**
10220 * Update data activity tracking when network state is updated.
10221 */
10222 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
10223 NetworkAgentInfo oldNetwork) {
10224 if (newNetwork != null) {
10225 setupDataActivityTracking(newNetwork);
10226 }
10227 if (oldNetwork != null) {
10228 removeDataActivityTracking(oldNetwork);
10229 }
10230 }
lucaslinb961efc2021-01-21 02:03:17 +080010231
10232 private void updateRadioPowerState(boolean isActive, int transportType) {
10233 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
10234 switch (transportType) {
10235 case NetworkCapabilities.TRANSPORT_CELLULAR:
10236 bs.reportMobileRadioPowerState(isActive, NO_UID);
10237 break;
10238 case NetworkCapabilities.TRANSPORT_WIFI:
10239 bs.reportWifiRadioPowerState(isActive, NO_UID);
10240 break;
10241 default:
10242 logw("Untracked transport type:" + transportType);
10243 }
10244 }
lucaslin1193a5d2021-01-21 02:04:15 +080010245
10246 public boolean isDefaultNetworkActive() {
10247 synchronized (mActiveIdleTimers) {
10248 // If there are no idle timers, it means that system is not monitoring activity,
10249 // so the default network is always considered active.
10250 //
10251 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
10252 // tracking is disabled (negative idle timer value configured), or no active default
10253 // network. In the latter case, this reports active but it should report inactive.
10254 return mNetworkActive || mActiveIdleTimers.isEmpty();
10255 }
10256 }
10257
10258 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
10259 mNetworkActivityListeners.register(l);
10260 }
10261
10262 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
10263 mNetworkActivityListeners.unregister(l);
10264 }
lucaslin012f7a12021-01-21 02:04:35 +080010265
10266 public void dump(IndentingPrintWriter pw) {
10267 synchronized (mActiveIdleTimers) {
10268 pw.print("mNetworkActive="); pw.println(mNetworkActive);
10269 pw.println("Idle timers:");
10270 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
10271 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
10272 final IdleTimerParams params = ent.getValue();
10273 pw.print(" timeout="); pw.print(params.timeout);
10274 pw.print(" type="); pw.println(params.transportType);
10275 }
10276 }
10277 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010278 }
James Mattis47db0582021-01-01 14:13:35 -080010279
Daniel Brightf9e945b2020-06-15 16:10:01 -070010280 /**
10281 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
10282 *
10283 * @param socketInfo the socket information
10284 * @param callback the callback to register
10285 */
10286 @Override
10287 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
10288 @NonNull final IQosCallback callback) {
10289 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
10290 if (nai == null || nai.networkCapabilities == null) {
10291 try {
10292 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
10293 } catch (final RemoteException ex) {
10294 loge("registerQosCallbackInternal: RemoteException", ex);
10295 }
10296 return;
10297 }
10298 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
10299 }
10300
10301 /**
10302 * Register a {@link IQosCallback} with base {@link QosFilter}.
10303 *
10304 * @param filter the filter to register
10305 * @param callback the callback to register
10306 * @param nai the agent information related to the filter's network
10307 */
10308 @VisibleForTesting
10309 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
10310 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
10311 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
10312 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
10313
10314 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
10315 enforceConnectivityRestrictedNetworksPermission();
10316 }
10317 mQosCallbackTracker.registerCallback(callback, filter, nai);
10318 }
10319
10320 /**
10321 * Unregisters the given callback.
10322 *
10323 * @param callback the callback to unregister
10324 */
10325 @Override
10326 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010327 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010328 mQosCallbackTracker.unregisterCallback(callback);
10329 }
James Mattis47db0582021-01-01 14:13:35 -080010330
James Mattis45d81842021-01-10 14:24:24 -080010331 /**
Chalard Jeanfa45a682021-02-25 17:23:40 +090010332 * Request that a user profile is put by default on a network matching a given preference.
10333 *
10334 * See the documentation for the individual preferences for a description of the supported
10335 * behaviors.
10336 *
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010337 * @param profile the user profile for whih the preference is being set.
10338 * @param preferences the list of profile network preferences for the
10339 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010340 * @param listener an optional listener to listen for completion of the operation.
10341 */
10342 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010343 public void setProfileNetworkPreferences(
10344 @NonNull final UserHandle profile,
10345 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090010346 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010347 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010348 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010349
10350 if (preferences.size() == 0) {
10351 preferences.add((new ProfileNetworkPreference.Builder()).build());
10352 }
10353
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010354 PermissionUtils.enforceNetworkStackPermission(mContext);
10355 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010356 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010357 }
10358 if (profile.getIdentifier() < 0) {
10359 throw new IllegalArgumentException("Must explicitly specify a user handle ("
10360 + "UserHandle.CURRENT not supported)");
10361 }
Chalard Jeana21ef9b2021-04-02 19:24:44 +090010362 final UserManager um = mContext.getSystemService(UserManager.class);
10363 if (!um.isManagedProfile(profile.getIdentifier())) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010364 throw new IllegalArgumentException("Profile must be a managed profile");
10365 }
paulhuaa0743d2021-05-26 21:56:03 +080010366
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010367 final List<ProfileNetworkPreferenceList.Preference> preferenceList =
10368 new ArrayList<ProfileNetworkPreferenceList.Preference>();
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010369 boolean allowFallback = true;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010370 for (final ProfileNetworkPreference preference : preferences) {
10371 final NetworkCapabilities nc;
10372 switch (preference.getPreference()) {
10373 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
10374 nc = null;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010375 if (preference.getPreferenceEnterpriseId() != 0) {
10376 throw new IllegalArgumentException(
10377 "Invalid enterprise identifier in setProfileNetworkPreferences");
10378 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010379 break;
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010380 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
10381 allowFallback = false;
10382 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010383 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010384 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
10385 throw new IllegalArgumentException(
10386 "Invalid enterprise identifier in setProfileNetworkPreferences");
10387 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010388 final Set<UidRange> uidRangeSet =
10389 getUidListToBeAppliedForNetworkPreference(profile, preference);
10390 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
10391 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
10392 } else {
10393 throw new IllegalArgumentException(
10394 "Overlapping uid range in setProfileNetworkPreferences");
10395 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010396 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010397 nc.addEnterpriseId(
10398 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010399 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10400 break;
10401 default:
10402 throw new IllegalArgumentException(
10403 "Invalid preference in setProfileNetworkPreferences");
10404 }
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010405 preferenceList.add(new ProfileNetworkPreferenceList.Preference(
10406 profile, nc, allowFallback));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010407 }
10408 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010409 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010410 }
10411
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010412 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
10413 @NonNull final UserHandle profile,
10414 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
10415 final UidRange profileUids = UidRange.createForUser(profile);
10416 Set<UidRange> uidRangeSet = UidRangeUtils.convertListToUidRange(
10417 profileNetworkPreference.getIncludedUids());
10418 if (uidRangeSet.size() > 0) {
10419 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
10420 throw new IllegalArgumentException(
10421 "Allow uid range is outside the uid range of profile.");
10422 }
10423 } else {
10424 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertListToUidRange(
10425 profileNetworkPreference.getExcludedUids());
10426 if (disallowUidRangeSet.size() > 0) {
10427 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
10428 throw new IllegalArgumentException(
10429 "disallow uid range is outside the uid range of profile.");
10430 }
10431 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
10432 disallowUidRangeSet);
10433 } else {
10434 uidRangeSet = new ArraySet<UidRange>();
10435 uidRangeSet.add(profileUids);
10436 }
10437 }
10438 return uidRangeSet;
10439 }
10440
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010441 private boolean isEnterpriseIdentifierValid(
10442 @NetworkCapabilities.EnterpriseId int identifier) {
10443 if ((identifier >= NET_ENTERPRISE_ID_1)
10444 && (identifier <= NET_ENTERPRISE_ID_5)) {
10445 return true;
10446 }
10447 return false;
10448 }
10449
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010450 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
10451 @Nullable final NetworkCapabilities nc) {
10452 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
10453 ensureRequestableCapabilities(nc);
10454 }
10455
10456 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010457 @NonNull final ProfileNetworkPreferenceList prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010458 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010459 for (final ProfileNetworkPreferenceList.Preference pref : prefs.preferences) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010460 // The NRI for a user should contain the request for capabilities.
10461 // If fallback to default network is needed then NRI should include
10462 // the request for the default network. Create an image of it to
10463 // have the correct UIDs in it (also a request can only be part of one NRI, because
10464 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010465 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
10466 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010467 if (pref.allowFallback) {
10468 nrs.add(createDefaultInternetRequestForTransport(
10469 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10470 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010471 if (VDBG) {
10472 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
10473 pref.capabilities.getUids()));
10474 }
10475
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010476 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080010477 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080010478 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010479 result.add(nri);
10480 }
10481 return result;
10482 }
10483
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010484 /**
10485 * Compare if the given UID range sets have the same UIDs.
10486 *
10487 */
10488 private boolean isRangeAlreadyInPreferenceList(
10489 @NonNull List<ProfileNetworkPreferenceList.Preference> preferenceList,
10490 @NonNull Set<UidRange> uidRangeSet) {
10491 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
10492 return false;
10493 }
10494 for (ProfileNetworkPreferenceList.Preference pref : preferenceList) {
10495 if (UidRangeUtils.doesRangeSetOverlap(
10496 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
10497 return true;
10498 }
10499 }
10500 return false;
10501 }
10502
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010503 private void handleSetProfileNetworkPreference(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010504 @NonNull final List<ProfileNetworkPreferenceList.Preference> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010505 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010506 for (final ProfileNetworkPreferenceList.Preference preference : preferenceList) {
10507 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
10508 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
10509 }
paulhu74128522021-09-28 02:29:03 +000010510 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
10511 addPerAppDefaultNetworkRequests(
10512 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010513 // Finally, rematch.
10514 rematchAllNetworksAndRequests();
10515
10516 if (null != listener) {
10517 try {
10518 listener.onComplete();
10519 } catch (RemoteException e) {
10520 loge("Listener for setProfileNetworkPreference has died");
10521 }
10522 }
10523 }
10524
paulhu51f77dc2021-06-07 02:34:20 +000010525 @VisibleForTesting
10526 @NonNull
10527 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
10528 @NonNull final Set<Integer> uids) {
10529 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10530 if (uids.size() == 0) {
10531 // Should not create NetworkRequestInfo if no preferences. Without uid range in
10532 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
10533 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
10534 return nris;
10535 }
10536
10537 final List<NetworkRequest> requests = new ArrayList<>();
10538 // The NRI should be comprised of two layers:
10539 // - The request for the mobile network preferred.
10540 // - The request for the default network, for fallback.
10541 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090010542 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000010543 requests.add(createDefaultInternetRequestForTransport(
10544 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10545 final Set<UidRange> ranges = new ArraySet<>();
10546 for (final int uid : uids) {
10547 ranges.add(new UidRange(uid, uid));
10548 }
10549 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080010550 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080010551 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000010552 return nris;
10553 }
10554
10555 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000010556 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000010557 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
10558 addPerAppDefaultNetworkRequests(
10559 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000010560 // Finally, rematch.
10561 rematchAllNetworksAndRequests();
10562 }
10563
James Mattis45d81842021-01-10 14:24:24 -080010564 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080010565 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
10566 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080010567 }
10568
10569 /**
10570 * Used by automotive devices to set the network preferences used to direct traffic at an
10571 * application level as per the given OemNetworkPreferences. An example use-case would be an
10572 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
10573 * vehicle via a particular network.
10574 *
10575 * Calling this will overwrite the existing preference.
10576 *
James Mattisda32cfe2021-01-26 16:23:52 -080010577 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090010578 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080010579 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080010580 */
James Mattis47db0582021-01-01 14:13:35 -080010581 @Override
James Mattis45d81842021-01-10 14:24:24 -080010582 public void setOemNetworkPreference(
10583 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010584 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080010585
James Mattisfa270db2021-05-31 17:11:10 -070010586 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10587 // Only bypass the permission/device checks if this is a valid test request.
10588 if (isValidTestOemNetworkPreference(preference)) {
10589 enforceManageTestNetworksPermission();
10590 } else {
10591 enforceAutomotiveDevice();
10592 enforceOemNetworkPreferencesPermission();
10593 validateOemNetworkPreferences(preference);
10594 }
James Mattis45d81842021-01-10 14:24:24 -080010595
James Mattis45d81842021-01-10 14:24:24 -080010596 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
10597 new Pair<>(preference, listener)));
10598 }
10599
James Mattisfa270db2021-05-31 17:11:10 -070010600 /**
10601 * Check the validity of an OEM network preference to be used for testing purposes.
10602 * @param preference the preference to validate
10603 * @return true if this is a valid OEM network preference test request.
10604 */
10605 private boolean isValidTestOemNetworkPreference(
10606 @NonNull final OemNetworkPreferences preference) {
10607 // Allow for clearing of an existing OemNetworkPreference used for testing.
10608 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
10609 // changes after this check is complete. This is an unlikely scenario as calling of this API
10610 // is controlled by the OEM therefore the added complexity is not worth adding given those
10611 // circumstances. That said, it is an edge case to be aware of hence this comment.
10612 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
10613 && isTestOemNetworkPreference(mOemNetworkPreferences);
10614 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
10615 }
10616
10617 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
10618 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
10619 return prefMap.size() == 1
10620 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
10621 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
10622 }
10623
James Mattis45d81842021-01-10 14:24:24 -080010624 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
10625 for (@OemNetworkPreferences.OemNetworkPreference final int pref
10626 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070010627 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
10628 throw new IllegalArgumentException(
10629 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
10630 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080010631 }
10632 }
10633 }
10634
10635 private void handleSetOemNetworkPreference(
10636 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010637 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080010638 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10639 if (DBG) {
10640 log("set OEM network preferences :" + preference.toString());
10641 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010642
James Mattiscb1e0362021-04-06 17:07:42 -070010643 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000010644 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
10645 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
10646 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080010647 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080010648
10649 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010650 try {
10651 listener.onComplete();
10652 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080010653 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010654 }
James Mattis45d81842021-01-10 14:24:24 -080010655 }
10656 }
10657
paulhu74128522021-09-28 02:29:03 +000010658 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080010659 // Skip the requests which are set by other network preference. Because the uid range rules
10660 // should stay in netd.
10661 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080010662 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080010663 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080010664 }
10665
James Mattis3ce3d3c2021-02-09 18:18:28 -080010666 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
10667 ensureRunningOnConnectivityServiceThread();
10668 mDefaultNetworkRequests.addAll(nris);
10669 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
10670 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080010671 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000010672 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
10673 nrisToRegister.addAll(
10674 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
10675 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010676 }
10677
10678 /**
10679 * All current requests that are tracking the default network need to be assessed as to whether
10680 * or not the current set of per-application default requests will be changing their default
10681 * network. If so, those requests will need to be updated so that they will send callbacks for
10682 * default network changes at the appropriate time. Additionally, those requests tracking the
10683 * default that were previously updated by this flow will need to be reassessed.
10684 * @return the nris which will need to be updated.
10685 */
10686 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
10687 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
10688 // Get the distinct nris to check since for multilayer requests, it is possible to have the
10689 // same nri in the map's values for each of its NetworkRequest objects.
10690 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080010691 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010692 // Include this nri if it is currently being tracked.
10693 if (isPerAppTrackedNri(nri)) {
10694 defaultCallbackRequests.add(nri);
10695 continue;
10696 }
10697 // We only track callbacks for requests tracking the default.
10698 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
10699 continue;
10700 }
10701 // Include this nri if it will be tracked by the new per-app default requests.
10702 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010703 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080010704 if (isNriGoingToBeTracked) {
10705 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080010706 }
10707 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080010708 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080010709 }
10710
James Mattis3ce3d3c2021-02-09 18:18:28 -080010711 /**
10712 * Create nris for those network requests that are currently tracking the default network that
10713 * are being controlled by a per-application default.
10714 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
10715 * foundation when creating the nri. Important items include the calling uid's original
10716 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
10717 * requests are assumed to have already been validated as needing to be updated.
10718 * @return the Set of nris to use when registering network requests.
10719 */
10720 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
10721 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
10722 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
10723 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
10724 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010725 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010726
Chalard Jean9473c982021-07-29 20:03:04 +090010727 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080010728 if (trackingNri == mDefaultRequest) {
10729 callbackRequestsToRegister.add(new NetworkRequestInfo(
10730 callbackRequest,
10731 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
10732 continue;
10733 }
10734
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010735 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010736 callbackRequestsToRegister.add(new NetworkRequestInfo(
10737 callbackRequest,
10738 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010739 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090010740 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080010741 }
10742 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080010743 }
10744
Chalard Jean17215832021-03-01 14:06:28 +090010745 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
10746 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090010747 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010748 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090010749 }
10750 }
10751
James Mattis45d81842021-01-10 14:24:24 -080010752 /**
10753 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
10754 */
10755 @VisibleForTesting
10756 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010757 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080010758 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010759 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080010760 final SparseArray<Set<Integer>> uids =
10761 createUidsFromOemNetworkPreferences(preference);
10762 for (int i = 0; i < uids.size(); i++) {
10763 final int key = uids.keyAt(i);
10764 final Set<Integer> value = uids.valueAt(i);
10765 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
10766 // No need to add an nri without any requests.
10767 if (0 == nri.mRequests.size()) {
10768 continue;
10769 }
10770 nris.add(nri);
10771 }
10772
10773 return nris;
10774 }
10775
10776 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
10777 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070010778 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080010779 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080010780 final List<UserHandle> users =
10781 mContext.getSystemService(UserManager.class).getUserHandles(true);
10782 if (null == users || users.size() == 0) {
10783 if (VDBG || DDBG) {
10784 log("No users currently available for setting the OEM network preference.");
10785 }
James Mattisb6b6a432021-06-01 22:30:36 -070010786 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080010787 }
James Mattis45d81842021-01-10 14:24:24 -080010788 for (final Map.Entry<String, Integer> entry :
10789 preference.getNetworkPreferences().entrySet()) {
10790 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070010791 // Add the rules for all users as this policy is device wide.
10792 for (final UserHandle user : users) {
10793 try {
10794 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
10795 if (!prefToUids.contains(pref)) {
10796 prefToUids.put(pref, new ArraySet<>());
10797 }
10798 prefToUids.get(pref).add(uid);
10799 } catch (PackageManager.NameNotFoundException e) {
10800 // Although this may seem like an error scenario, it is ok that uninstalled
10801 // packages are sent on a network preference as the system will watch for
10802 // package installations associated with this network preference and update
10803 // accordingly. This is done to minimize race conditions on app install.
10804 continue;
James Mattis45d81842021-01-10 14:24:24 -080010805 }
James Mattis45d81842021-01-10 14:24:24 -080010806 }
10807 }
James Mattisb6b6a432021-06-01 22:30:36 -070010808 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080010809 }
10810
10811 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10812 @OemNetworkPreferences.OemNetworkPreference final int preference,
10813 @NonNull final Set<Integer> uids) {
10814 final List<NetworkRequest> requests = new ArrayList<>();
10815 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10816 switch (preference) {
10817 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10818 requests.add(createUnmeteredNetworkRequest());
10819 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070010820 requests.add(createDefaultInternetRequestForTransport(
10821 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080010822 break;
10823 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10824 requests.add(createUnmeteredNetworkRequest());
10825 requests.add(createOemPaidNetworkRequest());
10826 break;
10827 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10828 requests.add(createOemPaidNetworkRequest());
10829 break;
10830 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10831 requests.add(createOemPrivateNetworkRequest());
10832 break;
James Mattisfa270db2021-05-31 17:11:10 -070010833 case OEM_NETWORK_PREFERENCE_TEST:
10834 requests.add(createUnmeteredNetworkRequest());
10835 requests.add(createTestNetworkRequest());
10836 requests.add(createDefaultRequest());
10837 break;
10838 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
10839 requests.add(createTestNetworkRequest());
10840 break;
James Mattis45d81842021-01-10 14:24:24 -080010841 default:
10842 // This should never happen.
10843 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10844 + " called with invalid preference of " + preference);
10845 }
10846
James Mattisfa270db2021-05-31 17:11:10 -070010847 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090010848 for (final int uid : uids) {
10849 ranges.add(new UidRange(uid, uid));
10850 }
10851 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080010852 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080010853 }
10854
10855 private NetworkRequest createUnmeteredNetworkRequest() {
10856 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10857 .addCapability(NET_CAPABILITY_NOT_METERED)
10858 .addCapability(NET_CAPABILITY_VALIDATED);
10859 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10860 }
10861
10862 private NetworkRequest createOemPaidNetworkRequest() {
10863 // NET_CAPABILITY_OEM_PAID is a restricted capability.
10864 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10865 .addCapability(NET_CAPABILITY_OEM_PAID)
10866 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10867 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10868 }
10869
10870 private NetworkRequest createOemPrivateNetworkRequest() {
10871 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
10872 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10873 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
10874 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10875 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10876 }
10877
10878 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070010879 final NetworkCapabilities netcap = new NetworkCapabilities();
10880 netcap.addCapability(NET_CAPABILITY_INTERNET);
10881 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
10882 return netcap;
10883 }
10884
10885 private NetworkRequest createTestNetworkRequest() {
10886 final NetworkCapabilities netcap = new NetworkCapabilities();
10887 netcap.clearAll();
10888 netcap.addTransportType(TRANSPORT_TEST);
10889 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080010890 }
James Mattis47db0582021-01-01 14:13:35 -080010891 }
markchien738ad912021-12-09 18:15:45 +080010892
10893 @Override
10894 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
10895 enforceNetworkStackOrSettingsPermission();
10896
10897 try {
10898 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080010899 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080010900 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080010901 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080010902 }
Ken Chenf5f51332022-01-28 10:08:16 +080010903 } catch (RemoteException | ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080010904 throw new IllegalStateException(e);
10905 }
10906 }
10907
10908 @Override
10909 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
10910 enforceNetworkStackOrSettingsPermission();
10911
10912 try {
10913 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080010914 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080010915 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080010916 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080010917 }
Ken Chenf5f51332022-01-28 10:08:16 +080010918 } catch (RemoteException | ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080010919 throw new IllegalStateException(e);
10920 }
10921 }
markchiene1561fa2021-12-09 22:00:56 +080010922
10923 @Override
10924 public void updateFirewallRule(final int chain, final int uid, final boolean allow) {
10925 enforceNetworkStackOrSettingsPermission();
10926
10927 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080010928 mBpfNetMaps.setUidRule(chain, uid,
markchiene1561fa2021-12-09 22:00:56 +080010929 allow ? INetd.FIREWALL_RULE_ALLOW : INetd.FIREWALL_RULE_DENY);
Ken Chenf5f51332022-01-28 10:08:16 +080010930 } catch (RemoteException | ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080010931 throw new IllegalStateException(e);
10932 }
10933 }
markchien98a6f952022-01-13 23:43:53 +080010934
10935 @Override
10936 public void setFirewallChainEnabled(final int chain, final boolean enable) {
10937 enforceNetworkStackOrSettingsPermission();
10938
10939 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080010940 mBpfNetMaps.setChildChain(chain, enable);
Ken Chenf5f51332022-01-28 10:08:16 +080010941 } catch (RemoteException | ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080010942 throw new IllegalStateException(e);
10943 }
10944 }
10945
markchien00a0bed2022-01-13 23:46:13 +080010946 @Override
10947 public void replaceFirewallChain(final int chain, final int[] uids) {
10948 enforceNetworkStackOrSettingsPermission();
10949
10950 try {
10951 switch (chain) {
10952 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
Wayne Ma2fde98c2022-01-17 18:04:05 +080010953 mBpfNetMaps.replaceUidChain("fw_dozable", true /* isAllowList */, uids);
markchien00a0bed2022-01-13 23:46:13 +080010954 break;
10955 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Wayne Ma2fde98c2022-01-17 18:04:05 +080010956 mBpfNetMaps.replaceUidChain("fw_standby", false /* isAllowList */, uids);
markchien00a0bed2022-01-13 23:46:13 +080010957 break;
10958 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
Wayne Ma2fde98c2022-01-17 18:04:05 +080010959 mBpfNetMaps.replaceUidChain("fw_powersave", true /* isAllowList */, uids);
markchien00a0bed2022-01-13 23:46:13 +080010960 break;
10961 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
Wayne Ma2fde98c2022-01-17 18:04:05 +080010962 mBpfNetMaps.replaceUidChain("fw_restricted", true /* isAllowList */, uids);
markchien00a0bed2022-01-13 23:46:13 +080010963 break;
Robert Horvath1db49e12022-01-27 19:54:29 +010010964 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
10965 mBpfNetMaps.replaceUidChain("fw_low_power_standby", true /* isAllowList */,
10966 uids);
10967 break;
markchien00a0bed2022-01-13 23:46:13 +080010968 default:
10969 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
10970 + chain);
10971 }
Ken Chenf5f51332022-01-28 10:08:16 +080010972 } catch (RemoteException | ServiceSpecificException e) {
markchien00a0bed2022-01-13 23:46:13 +080010973 throw new IllegalStateException(e);
10974 }
10975 }
markchien9c806112022-01-11 23:28:23 +080010976
10977 @Override
10978 public void swapActiveStatsMap() {
10979 enforceNetworkStackOrSettingsPermission();
10980 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080010981 mBpfNetMaps.swapActiveStatsMap();
Ken Chenf5f51332022-01-28 10:08:16 +080010982 } catch (RemoteException | ServiceSpecificException e) {
markchien9c806112022-01-11 23:28:23 +080010983 throw new IllegalStateException(e);
10984 }
10985 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070010986}