blob: d2c0e183959ad1ca5cc9d44ff6381f28cba83c48 [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;
paulhu7c0a2e62021-01-08 00:51:49 +0800194import android.net.resolv.aidl.DnsHealthEventParcel;
195import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
196import android.net.resolv.aidl.Nat64PrefixEventParcel;
197import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900198import android.net.shared.PrivateDnsConfig;
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900199import android.net.util.MultinetworkPolicyTracker;
lucaslinb961efc2021-01-21 02:03:17 +0800200import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800201import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800202import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700203import android.os.Bundle;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800204import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700205import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700206import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800207import android.os.Looper;
208import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700209import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700210import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900211import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800212import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700213import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700214import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800215import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700216import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900217import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900218import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700219import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700220import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400221import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800222import android.provider.Settings;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900223import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700224import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700225import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700226import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800227import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900228import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000229import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600230import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900231import android.util.Pair;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700232import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700233import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800234
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900235import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400236import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400237import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700238import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900239import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800240import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900241import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800242import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900243import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900244import com.android.net.module.util.DeviceConfigUtils;
Chalard Jean79162542020-08-19 16:07:22 +0900245import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
246import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900247import com.android.net.module.util.LocationPermissionChecker;
lifrade6c2a2021-03-04 14:08:08 +0800248import com.android.net.module.util.NetworkCapabilitiesUtils;
paulhudf23d662021-01-25 18:53:17 +0800249import com.android.net.module.util.PermissionUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000250import com.android.net.module.util.netlink.InetDiagMessage;
Chalard Jean7284daa2019-05-30 14:58:29 +0900251import com.android.server.connectivity.AutodestructReference;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900252import com.android.server.connectivity.ConnectivityFlags;
Erik Kline32120082017-12-13 19:40:49 +0900253import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500254import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700255import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900256import com.android.server.connectivity.FullScore;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900257import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100258import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700259import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700260import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600261import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900262import com.android.server.connectivity.NetworkNotificationManager;
263import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900264import com.android.server.connectivity.NetworkOffer;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900265import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700266import com.android.server.connectivity.PermissionMonitor;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800267import com.android.server.connectivity.ProfileNetworkPreferenceList;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900268import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700269import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800270import com.android.server.connectivity.UidRangeUtils;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600271
Josh Gao461a1222020-06-16 15:58:11 -0700272import libcore.io.IoUtils;
273
The Android Open Source Project28527d22009-03-03 19:31:44 -0800274import java.io.FileDescriptor;
275import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900276import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700277import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700278import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900279import java.net.InetSocketAddress;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700280import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700281import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700282import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700283import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800284import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900285import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800286import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700287import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700288import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700289import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700290import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900291import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700292import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900293import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600294import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900295import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600296import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900297import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800298
299/**
300 * @hide
301 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800302public class ConnectivityService extends IConnectivityManager.Stub
303 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900304 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800305
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900306 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900307 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900308 private static final String NETWORK_ARG = "networks";
309 private static final String REQUEST_ARG = "requests";
Erik Klined364a242017-05-12 16:52:48 +0900310
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900311 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900312 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
313 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800314
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900315 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700316
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100317 /**
318 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
319 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800320 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100321 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
322 * (preferably via runtime resource overlays).
323 */
324 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
325 "http://connectivitycheck.gstatic.com/generate_204";
326
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700327 // TODO: create better separation between radio types and network types
328
Robert Greenwalt2034b912009-08-12 16:08:25 -0700329 // how long to wait before switching back to a radio's default network
330 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
331 // system property that can override the above value
332 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
333 "android.telephony.apn-restore";
334
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900335 // How long to wait before putting up a "This network doesn't have an Internet connection,
336 // connect anyway?" dialog after the user selects a network that doesn't validate.
337 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
338
junyulai0ac374f2020-12-14 18:41:52 +0800339 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900340 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
341 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800342 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700343
344 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900345 @VisibleForTesting
346 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700347
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900348 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700349 @VisibleForTesting
350 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900351
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900352 @VisibleForTesting
353 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800354 @VisibleForTesting
355 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900356 // True if the cell radio of the device is capable of time-sharing.
357 @VisibleForTesting
358 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900359
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800360 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800361 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800362 private final int mReleasePendingIntentDelayMs;
363
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900364 private MockableSystemProperties mSystemProperties;
365
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000366 @VisibleForTesting
367 protected final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700368
Chalard Jean9473c982021-07-29 20:03:04 +0900369 @VisibleForTesting
370 final PerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700371 @VisibleForTesting
372 final PerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700373
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900374 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700375
junyulaif2c67e42018-08-07 19:50:45 +0800376 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000377 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
378 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800379 */
Sudheer Shanka9967d462021-03-18 19:09:25 +0000380 private SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800381
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900382 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900383 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000384 // The Context is created for UserHandle.ALL.
385 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900386 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900387 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700388 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700389 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800390
Chenbo Feng15416292018-11-08 17:36:21 -0800391 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800392 protected IDnsResolver mDnsResolver;
393 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800394 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700395 private DscpPolicyTracker mDscpPolicyTracker = null;
junyulaie7c7d2a2021-01-26 15:29:15 +0800396 private NetworkStatsManager mStatsManager;
paulhu9a9f71b2020-12-29 18:15:13 +0800397 private NetworkPolicyManager mPolicyManager;
lucaslin66f44212021-02-23 01:12:55 +0800398 private final NetdCallback mNetdCallback;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700399
Benedict Wong493e04b2018-11-09 14:45:34 -0800400 /**
401 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
402 * instances.
403 */
404 @GuardedBy("mTNSLock")
405 private TestNetworkService mTNS;
406
407 private final Object mTNSLock = new Object();
408
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700409 private String mCurrentTcpBufferSizes;
410
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900411 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
lifraf3a3492021-03-10 13:58:14 +0800412 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900413
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500414 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400415 // Tear down networks that have no chance (e.g. even if validated) of becoming
416 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500417 // all networks have been rematched against all NetworkRequests.
418 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400419 // Don't reap networks. This should be passed when some networks have not yet been
420 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500421 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900422 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500423
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900424 private enum UnneededFor {
425 LINGER, // Determine whether this network is unneeded and should be lingered.
426 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
427 }
428
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700429 /**
paulhuaa0743d2021-05-26 21:56:03 +0800430 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800431 * should have priority. The order is passed to netd which will use it together
432 * with UID ranges to generate the corresponding IP rule. This serves to
433 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800434 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800435 * Order ints passed to netd must be in the 0~999 range. Larger values code for
paulhuaa0743d2021-05-26 21:56:03 +0800436 * a lower priority, {@see NativeUidRangeConfig}
paulhue9913722021-05-26 15:19:20 +0800437 *
paulhu48291862021-07-14 14:53:57 +0800438 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
439 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800440 */
paulhu48291862021-07-14 14:53:57 +0800441 // Bound for the lowest valid preference order.
442 static final int PREFERENCE_ORDER_LOWEST = 999;
443 // Used when sending to netd to code for "no order".
444 static final int PREFERENCE_ORDER_NONE = 0;
445 // Order for requests that don't code for a per-app preference. As it is
446 // out of the valid range, the corresponding order should be
447 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800448 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800449 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
450 // Order for the default internet request. Since this must always have the
paulhuaa0743d2021-05-26 21:56:03 +0800451 // lowest priority, its value is larger than the largest acceptable value. As
paulhu48291862021-07-14 14:53:57 +0800452 // it is out of the valid range, the corresponding order should be
453 // PREFERENCE_ORDER_NONE when sending to netd.
454 static final int PREFERENCE_ORDER_DEFAULT = 1000;
paulhuaa0743d2021-05-26 21:56:03 +0800455 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800456 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
457 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800458 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800459 static final int PREFERENCE_ORDER_OEM = 10;
460 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800461 // See {@link #setProfileNetworkPreference}.
462 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800463 static final int PREFERENCE_ORDER_PROFILE = 20;
464 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800465 // better scores are connected.
466 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800467 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800468 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
paulhue9913722021-05-26 15:19:20 +0800469
470 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700471 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700472 * from one net to another. Clear happens when we get a new
473 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
474 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700475 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700476 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700477
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700478 /**
479 * used internally to reload global proxy settings
480 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700481 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700482
Robert Greenwalt34848c02011-03-25 13:09:25 -0700483 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400484 * PAC manager has received new port.
485 */
486 private static final int EVENT_PROXY_HAS_CHANGED = 16;
487
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700488 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900489 * used internally when registering NetworkProviders
490 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700491 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900492 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700493
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700494 /**
495 * used internally when registering NetworkAgents
496 * obj = Messenger
497 */
498 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
499
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700500 /**
501 * used to add a network request
502 * includes a NetworkRequestInfo
503 */
504 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
505
506 /**
507 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900508 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700509 * cancel it.
510 * includes a NetworkRequestInfo
511 */
512 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
513
514 /**
515 * used to add a network listener - no request
516 * includes a NetworkRequestInfo
517 */
518 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
519
520 /**
521 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400522 * arg1 = UID of caller
523 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700524 */
525 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
526
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700527 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900528 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700529 * obj = Messenger
530 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900531 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700532
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700533 /**
534 * used internally to expire a wakelock when transitioning
535 * from one net to another. Expire happens when we fail to find
536 * a new network (typically after 1 minute) -
537 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
538 * a replacement network.
539 */
540 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
541
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700542 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800543 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400544 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800545 */
546 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
547
548 /**
549 * used to remove a pending intent and its associated network request.
550 * arg1 = UID of caller
551 * obj = PendingIntent
552 */
553 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
554
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900555 /**
556 * used to specify whether a network should be used even if unvalidated.
557 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
558 * arg2 = whether to remember this choice in the future (1 or 0)
559 * obj = network
560 */
561 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
562
563 /**
564 * used to ask the user to confirm a connection to an unvalidated network.
565 * obj = network
566 */
567 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700568
Erik Kline05f2b402015-04-30 12:58:40 +0900569 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700570 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900571 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700572 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900573
Paul Jensenc8873fc2015-06-17 14:15:39 -0400574 /**
575 * used to add a network listener with a pending intent
576 * obj = NetworkRequestInfo
577 */
578 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
579
Hugo Benichid6b510a2017-04-06 17:22:18 +0900580 /**
581 * used to specify whether a network should not be penalized when it becomes unvalidated.
582 */
583 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
584
585 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700586 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900587 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700588 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900589
Erik Kline31b4a9e2018-01-11 21:07:29 +0900590 // Handle changes in Private DNS settings.
591 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
592
dalyk1720e542018-03-05 12:42:22 -0500593 // Handle private DNS validation status updates.
594 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
595
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900596 /**
597 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
598 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800599 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
600 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
601 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900602 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900603 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900604
605 /**
606 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
607 * config was resolved.
608 * obj = PrivateDnsConfig
609 * arg2 = netid
610 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900611 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900612
613 /**
614 * Request ConnectivityService display provisioning notification.
615 * arg1 = Whether to make the notification visible.
616 * arg2 = NetID.
617 * obj = Intent to be launched when notification selected by user, null if !arg1.
618 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900619 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900620
621 /**
lucaslin2240ef62019-03-12 13:08:03 +0800622 * Used to specify whether a network should be used even if connectivity is partial.
623 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
624 * false)
625 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
626 * obj = network
627 */
lucaslin444d43a2020-02-20 16:56:59 +0800628 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800629
630 /**
lucasline117e2e2019-10-22 18:27:33 +0800631 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
632 * Both of the arguments are bitmasks, and the value of bits come from
633 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
634 * arg1 = A bitmask to describe which probes are completed.
635 * arg2 = A bitmask to describe which probes are successful.
636 */
lucaslin444d43a2020-02-20 16:56:59 +0800637 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800638
639 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900640 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
641 * arg1 = unused
642 * arg2 = netId
643 * obj = captive portal data
644 */
lucaslin444d43a2020-02-20 16:56:59 +0800645 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900646
647 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900648 * Used by setRequireVpnForUids.
649 * arg1 = whether the specified UID ranges are required to use a VPN.
650 * obj = Array of UidRange objects.
651 */
652 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
653
654 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900655 * Used internally when setting the default networks for OemNetworkPreferences.
656 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800657 */
658 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
659
660 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800661 * Used to indicate the system default network becomes active.
662 */
663 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
664
665 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900666 * Used internally when setting a network preference for a user profile.
667 * obj = Pair<ProfileNetworkPreference, Listener>
668 */
669 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
670
671 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000672 * Event to specify that reasons for why an uid is blocked changed.
673 * arg1 = uid
674 * arg2 = blockedReasons
675 */
676 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
677
678 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900679 * Event to register a new network offer
680 * obj = NetworkOffer
681 */
682 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
683
684 /**
685 * Event to unregister an existing network offer
686 * obj = INetworkOfferCallback
687 */
688 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
689
690 /**
paulhu51f77dc2021-06-07 02:34:20 +0000691 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
692 */
693 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
694
695 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800696 * Event to set temporary allow bad wifi within a limited time to override
697 * {@code config_networkAvoidBadWifi}.
698 */
699 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
700
701 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900702 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
703 * should be shown.
704 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900705 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900706
707 /**
708 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
709 * should be hidden.
710 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900711 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900712
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800713 /**
714 * The maximum alive time to allow bad wifi configuration for testing.
715 */
716 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
717
Hugo Benichi47011212017-03-30 10:46:05 +0900718 private static String eventName(int what) {
719 return sMagicDecoderRing.get(what, Integer.toString(what));
720 }
721
paulhua10d8212020-11-10 15:32:56 +0800722 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900723 final DnsResolverServiceManager dsm = context.getSystemService(
724 DnsResolverServiceManager.class);
725 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800726 }
727
Cody Kesting73708bf2019-12-18 10:57:50 -0800728 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900729 @VisibleForTesting
730 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700731 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700732 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700733 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700734 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800735 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
736 @VisibleForTesting
737 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
738
Erik Kline32120082017-12-13 19:40:49 +0900739 private final DnsManager mDnsManager;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900740 private final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700741
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400742 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800743 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400744
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700745 private PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800746 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700747
Chalard Jean5d70ba42018-06-07 16:44:04 +0900748 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
749 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000750 @VisibleForTesting
751 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400752
Erik Kline05f2b402015-04-30 12:58:40 +0900753 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700754
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400755 private UserManager mUserManager;
756
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700757 // the set of network types that can only be enabled by system/sig apps
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900758 private List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700759
Valentin Iftime9fa35092019-09-24 13:32:13 +0200760 private Set<String> mWolSupportedInterfaces;
761
Roshan Pius08c94fb2020-01-16 12:17:17 -0800762 private final TelephonyManager mTelephonyManager;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800763 private final AppOpsManager mAppOpsManager;
764
765 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400766
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900767 private KeepaliveTracker mKeepaliveTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700768 private QosCallbackTracker mQosCallbackTracker;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900769 private NetworkNotificationManager mNotifier;
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +0900770 private LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900771
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700772 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800773 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700774
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900775 // Sequence number for NetworkProvider IDs.
776 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
777 NetworkProvider.FIRST_PROVIDER_ID);
778
Erik Klineedf878b2015-07-09 18:24:03 +0900779 // NetworkRequest activity String log entries.
780 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
781 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
782
Hugo Benichid159fdd2016-07-11 11:05:12 +0900783 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900784 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900785 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
786
Hugo Benichi47011212017-03-30 10:46:05 +0900787 private static final int MAX_WAKELOCK_LOGS = 20;
788 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900789 private int mTotalWakelockAcquisitions = 0;
790 private int mTotalWakelockReleases = 0;
791 private long mTotalWakelockDurationMs = 0;
792 private long mMaxWakelockDurationMs = 0;
793 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900794
Hugo Benichi208c0102016-07-28 17:53:06 +0900795 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900796
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700797 @GuardedBy("mBandwidthRequests")
798 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
799
Erik Kline95ecfee2016-10-02 18:02:14 +0900800 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900801 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900802
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900803 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800804 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
805 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800806
Robert Greenwalt802c1102014-06-02 15:32:02 -0700807 /**
808 * Implements support for the legacy "one network per network type" model.
809 *
810 * We used to have a static array of NetworkStateTrackers, one for each
811 * network type, but that doesn't work any more now that we can have,
812 * for example, more that one wifi network. This class stores all the
813 * NetworkAgentInfo objects that support a given type, but the legacy
814 * API will only see the first one.
815 *
816 * It serves two main purposes:
817 *
818 * 1. Provide information about "the network for a given type" (since this
819 * API only supports one).
820 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
821 * the first network for a given type changes, or if the default network
822 * changes.
823 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900824 @VisibleForTesting
825 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900826
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900827 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900828 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900829
Robert Greenwalt802c1102014-06-02 15:32:02 -0700830 /**
831 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
832 * Each list holds references to all NetworkAgentInfos that are used to
833 * satisfy requests for that network type.
834 *
835 * This array is built out at startup such that an unsupported network
836 * doesn't get an ArrayList instance, making this a tristate:
837 * unsupported, supported but not active and active.
838 *
839 * The actual lists are populated when we scan the network types that
840 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900841 *
842 * Threading model:
843 * - addSupportedType() is only called in the constructor
844 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
845 * They are therefore not thread-safe with respect to each other.
846 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
847 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900848 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900849 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700850 */
Hugo Benichi389633f2016-06-21 09:48:07 +0900851 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900852 @NonNull
853 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700854
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900855 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
856 // an entry have no timer (equivalent to -1). Lazily loaded.
857 @NonNull
858 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
859
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900860 LegacyTypeTracker(@NonNull ConnectivityService service) {
861 mService = service;
862 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700863 }
864
Chiachang Wang3bc52762021-11-25 14:17:57 +0800865 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
866 // addressed.
867 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900868 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
869 final PackageManager pm = ctx.getPackageManager();
870 if (pm.hasSystemFeature(FEATURE_WIFI)) {
871 addSupportedType(TYPE_WIFI);
872 }
873 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
874 addSupportedType(TYPE_WIFI_P2P);
875 }
876 if (tm.isDataCapable()) {
877 // Telephony does not have granular support for these types: they are either all
878 // supported, or none is supported
879 addSupportedType(TYPE_MOBILE);
880 addSupportedType(TYPE_MOBILE_MMS);
881 addSupportedType(TYPE_MOBILE_SUPL);
882 addSupportedType(TYPE_MOBILE_DUN);
883 addSupportedType(TYPE_MOBILE_HIPRI);
884 addSupportedType(TYPE_MOBILE_FOTA);
885 addSupportedType(TYPE_MOBILE_IMS);
886 addSupportedType(TYPE_MOBILE_CBS);
887 addSupportedType(TYPE_MOBILE_IA);
888 addSupportedType(TYPE_MOBILE_EMERGENCY);
889 }
890 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
891 addSupportedType(TYPE_BLUETOOTH);
892 }
893 if (pm.hasSystemFeature(FEATURE_WATCH)) {
894 // TYPE_PROXY is only used on Wear
895 addSupportedType(TYPE_PROXY);
896 }
897 // Ethernet is often not specified in the configs, although many devices can use it via
898 // USB host adapters. Add it as long as the ethernet service is here.
899 if (ctx.getSystemService(Context.ETHERNET_SERVICE) != null) {
900 addSupportedType(TYPE_ETHERNET);
901 }
902
903 // Always add TYPE_VPN as a supported type
904 addSupportedType(TYPE_VPN);
905 }
906
907 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700908 if (mTypeLists[type] != null) {
909 throw new IllegalStateException(
910 "legacy list for type " + type + "already initialized");
911 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900912 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -0700913 }
914
Robert Greenwalt802c1102014-06-02 15:32:02 -0700915 public boolean isTypeSupported(int type) {
916 return isNetworkTypeValid(type) && mTypeLists[type] != null;
917 }
918
919 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +0900920 synchronized (mTypeLists) {
921 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
922 return mTypeLists[type].get(0);
923 }
Robert Greenwalt802c1102014-06-02 15:32:02 -0700924 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900925 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700926 }
927
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900928 public int getRestoreTimerForType(int type) {
929 synchronized (mTypeLists) {
930 if (mRestoreTimers == null) {
931 mRestoreTimers = loadRestoreTimers();
932 }
933 return mRestoreTimers.getOrDefault(type, -1);
934 }
935 }
936
937 private ArrayMap<Integer, Integer> loadRestoreTimers() {
938 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900939 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900940 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
941 for (final String config : configs) {
942 final String[] splits = TextUtils.split(config, ",");
943 if (splits.length != 2) {
944 logwtf("Invalid restore timer token count: " + config);
945 continue;
946 }
947 try {
948 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
949 } catch (NumberFormatException e) {
950 logwtf("Invalid restore timer number format: " + config, e);
951 }
952 }
953 return ret;
954 }
955
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -0700956 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +0900957 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900958 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +0900959 log("Sending " + state
960 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +0900961 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900962 }
963 }
964
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900965 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
966 // network type, to preserve previous behaviour.
967 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
968 if (vpnNai != mService.getLegacyLockdownNai()) return;
969
970 if (vpnNai.declaredUnderlyingNetworks == null
971 || vpnNai.declaredUnderlyingNetworks.length != 1) {
972 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
973 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
974 return;
975 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +0900976 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900977 vpnNai.declaredUnderlyingNetworks[0]);
978 if (underlyingNai == null) return;
979
980 final int type = underlyingNai.networkInfo.getType();
981 final DetailedState state = DetailedState.CONNECTED;
982 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
983 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
984 }
985
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900986 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -0700987 public void add(int type, NetworkAgentInfo nai) {
988 if (!isTypeSupported(type)) {
989 return; // Invalid network type.
990 }
991 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
992
993 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
994 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700995 return;
996 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900997 synchronized (mTypeLists) {
998 list.add(nai);
999 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001000
Chalard Jean5b409c72021-02-04 13:12:59 +09001001 // Send a broadcast if this is the first network of its type or if it's the default.
1002 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001003
1004 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1005 // to preserve previous behaviour.
1006 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001007 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001008 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1009 mService.sendLegacyNetworkBroadcast(nai, state, type);
1010 }
1011
1012 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1013 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001014 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001015 }
1016
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001017 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001018 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001019 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1020 if (list == null || list.isEmpty()) {
1021 return;
1022 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001023 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001024
Hugo Benichi389633f2016-06-21 09:48:07 +09001025 synchronized (mTypeLists) {
1026 if (!list.remove(nai)) {
1027 return;
1028 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001029 }
1030
Lorenzo Colitti49767722015-05-01 00:30:10 +09001031 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001032 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1033 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001034 }
1035
1036 if (!list.isEmpty() && wasFirstNetwork) {
1037 if (DBG) log("Other network available for type " + type +
1038 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001039 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001040 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001041 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001042 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001043 }
1044 }
1045
1046 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001047 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1048 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001049 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001050 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001051 }
1052 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001053
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001054 // send out another legacy broadcast - currently only used for suspend/unsuspend
1055 // toggle
1056 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001057 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001058 final DetailedState state = nai.networkInfo.getDetailedState();
1059 for (int type = 0; type < mTypeLists.length; type++) {
1060 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001061 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001062 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001063 if (isFirst || contains && isDefault) {
1064 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001065 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001066 }
1067 }
1068 }
1069
Robert Greenwalt94e22142014-07-30 16:31:24 -07001070 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001071 pw.println("mLegacyTypeTracker:");
1072 pw.increaseIndent();
1073 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001074 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001075 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001076 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001077 pw.println();
1078 pw.println("Current state:");
1079 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001080 synchronized (mTypeLists) {
1081 for (int type = 0; type < mTypeLists.length; type++) {
1082 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1083 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001084 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001085 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001086 }
1087 }
1088 pw.decreaseIndent();
1089 pw.decreaseIndent();
1090 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001091 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001092 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001093 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001094
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001095 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001096 /**
1097 * Helper class which parses out priority arguments and dumps sections according to their
1098 * priority. If priority arguments are omitted, function calls the legacy dump command.
1099 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001100 private class LocalPriorityDump {
1101 private static final String PRIORITY_ARG = "--dump-priority";
1102 private static final String PRIORITY_ARG_HIGH = "HIGH";
1103 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1104
1105 LocalPriorityDump() {}
1106
1107 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1108 doDump(fd, pw, new String[] {DIAG_ARG});
1109 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001110 }
1111
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001112 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1113 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001114 }
1115
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001116 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1117 if (args == null) {
1118 dumpNormal(fd, pw, args);
1119 return;
1120 }
1121
1122 String priority = null;
1123 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1124 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1125 argIndex++;
1126 priority = args[argIndex];
1127 }
1128 }
1129
1130 if (PRIORITY_ARG_HIGH.equals(priority)) {
1131 dumpHigh(fd, pw);
1132 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1133 dumpNormal(fd, pw, args);
1134 } else {
1135 // ConnectivityService publishes binder service using publishBinderService() with
1136 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001137 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1138 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001139 // TODO: Integrate into signal dump.
1140 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001141 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001142 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001143 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001144
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001145 /**
Daniel Brightf9e945b2020-06-15 16:10:01 -07001146 * Keeps track of the number of requests made under different uids.
1147 */
1148 public static class PerUidCounter {
1149 private final int mMaxCountPerUid;
1150
1151 // Map from UID to number of NetworkRequests that UID has filed.
James Mattis20a4a8b2021-03-28 17:41:09 -07001152 @VisibleForTesting
Daniel Brightf9e945b2020-06-15 16:10:01 -07001153 @GuardedBy("mUidToNetworkRequestCount")
James Mattis20a4a8b2021-03-28 17:41:09 -07001154 final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
Daniel Brightf9e945b2020-06-15 16:10:01 -07001155
1156 /**
1157 * Constructor
1158 *
1159 * @param maxCountPerUid the maximum count per uid allowed
1160 */
1161 public PerUidCounter(final int maxCountPerUid) {
1162 mMaxCountPerUid = maxCountPerUid;
1163 }
1164
1165 /**
1166 * Increments the request count of the given uid. Throws an exception if the number
1167 * of open requests for the uid exceeds the value of maxCounterPerUid which is the value
1168 * passed into the constructor. see: {@link #PerUidCounter(int)}.
1169 *
1170 * @throws ServiceSpecificException with
1171 * {@link ConnectivityManager.Errors.TOO_MANY_REQUESTS} if the number of requests for
1172 * the uid exceed the allowed number.
1173 *
1174 * @param uid the uid that the request was made under
1175 */
1176 public void incrementCountOrThrow(final int uid) {
1177 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001178 incrementCountOrThrow(uid, 1 /* numToIncrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001179 }
1180 }
1181
James Mattis20a4a8b2021-03-28 17:41:09 -07001182 private void incrementCountOrThrow(final int uid, final int numToIncrement) {
1183 final int newRequestCount =
1184 mUidToNetworkRequestCount.get(uid, 0) + numToIncrement;
Chalard Jean9473c982021-07-29 20:03:04 +09001185 if (newRequestCount >= mMaxCountPerUid
1186 // HACK : the system server is allowed to go over the request count limit
1187 // when it is creating requests on behalf of another app (but not itself,
1188 // so it can still detect its own request leaks). This only happens in the
1189 // per-app API flows in which case the old requests for that particular
1190 // UID will be removed soon.
1191 // TODO : instead of this hack, addPerAppDefaultNetworkRequests and other
1192 // users of transact() should unregister the requests to decrease the count
1193 // before they increase it again by creating a new NRI. Then remove the
1194 // transact() method.
1195 && (Process.myUid() == uid || Process.myUid() != Binder.getCallingUid())) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001196 throw new ServiceSpecificException(
Chalard Jean9473c982021-07-29 20:03:04 +09001197 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
1198 "Uid " + uid + " exceeded its allotted requests limit");
James Mattis20a4a8b2021-03-28 17:41:09 -07001199 }
1200 mUidToNetworkRequestCount.put(uid, newRequestCount);
1201 }
1202
Daniel Brightf9e945b2020-06-15 16:10:01 -07001203 /**
1204 * Decrements the request count of the given uid.
1205 *
1206 * @param uid the uid that the request was made under
1207 */
1208 public void decrementCount(final int uid) {
1209 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001210 decrementCount(uid, 1 /* numToDecrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001211 }
1212 }
James Mattis20a4a8b2021-03-28 17:41:09 -07001213
1214 private void decrementCount(final int uid, final int numToDecrement) {
1215 final int newRequestCount =
1216 mUidToNetworkRequestCount.get(uid, 0) - numToDecrement;
1217 if (newRequestCount < 0) {
1218 logwtf("BUG: too small request count " + newRequestCount + " for UID " + uid);
1219 } else if (newRequestCount == 0) {
1220 mUidToNetworkRequestCount.delete(uid);
1221 } else {
1222 mUidToNetworkRequestCount.put(uid, newRequestCount);
1223 }
1224 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07001225 }
1226
1227 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001228 * Dependencies of ConnectivityService, for injection in tests.
1229 */
1230 @VisibleForTesting
1231 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001232 public int getCallingUid() {
1233 return Binder.getCallingUid();
1234 }
1235
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001236 /**
1237 * Get system properties to use in ConnectivityService.
1238 */
1239 public MockableSystemProperties getSystemProperties() {
1240 return new MockableSystemProperties();
1241 }
1242
1243 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001244 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1245 */
1246 public ConnectivityResources getResources(@NonNull Context ctx) {
1247 return new ConnectivityResources(ctx);
1248 }
1249
1250 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001251 * Create a HandlerThread to use in ConnectivityService.
1252 */
1253 public HandlerThread makeHandlerThread() {
1254 return new HandlerThread("ConnectivityServiceThread");
1255 }
1256
1257 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001258 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001259 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001260 public NetworkStackClientBase getNetworkStack() {
1261 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001262 }
1263
1264 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001265 * @see ProxyTracker
1266 */
1267 public ProxyTracker makeProxyTracker(@NonNull Context context,
1268 @NonNull Handler connServiceHandler) {
1269 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1270 }
1271
1272 /**
1273 * @see NetIdManager
1274 */
1275 public NetIdManager makeNetIdManager() {
1276 return new NetIdManager();
1277 }
1278
1279 /**
1280 * @see NetworkUtils#queryUserAccess(int, int)
1281 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001282 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1283 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001284 }
1285
1286 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001287 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1288 * requires CAP_NET_ADMIN, which the unit tests do not have.
1289 */
1290 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1291 InetSocketAddress remote) {
1292 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1293 }
1294
1295 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001296 * @see MultinetworkPolicyTracker
1297 */
1298 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1299 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1300 return new MultinetworkPolicyTracker(c, h, r);
1301 }
1302
Aaron Huang330a4c02020-10-27 03:36:19 +08001303 /**
1304 * @see BatteryStatsManager
1305 */
1306 public void reportNetworkInterfaceForTransports(Context context, String iface,
1307 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001308 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001309 context.getSystemService(BatteryStatsManager.class);
1310 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1311 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001312
1313 public boolean getCellular464XlatEnabled() {
1314 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1315 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001316
1317 /**
1318 * @see PendingIntent#intentFilterEquals
1319 */
1320 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1321 return a.intentFilterEquals(b);
1322 }
1323
1324 /**
1325 * @see LocationPermissionChecker
1326 */
1327 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1328 return new LocationPermissionChecker(context);
1329 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001330
1331 /**
1332 * @see DeviceConfigUtils#isFeatureEnabled
1333 */
1334 public boolean isFeatureEnabled(Context context, String name, boolean defaultEnabled) {
1335 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, name,
1336 TETHERING_MODULE_NAME, defaultEnabled);
1337 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001338 }
1339
junyulaie7c7d2a2021-01-26 15:29:15 +08001340 public ConnectivityService(Context context) {
1341 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001342 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1343 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001344 }
1345
1346 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001347 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1348 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001349 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001350
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001351 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001352 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001353 mSystemProperties = mDeps.getSystemProperties();
1354 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001355 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001356 mResources = deps.getResources(mContext);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001357 mNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_UID);
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09001358 mSystemNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001359
Hugo Benichi208c0102016-07-28 17:53:06 +09001360 mMetricsLog = logger;
Chalard Jean96a4f4b2019-12-10 22:16:53 +09001361 mNetworkRanker = new NetworkRanker();
James Mattis45d81842021-01-10 14:24:24 -08001362 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1363 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001364 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001365 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001366 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001367 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1368 mDefaultNetworkRequests.add(mDefaultRequest);
1369 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001370
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001371 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001372 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001373
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001374 // The default WiFi request is a background request so that apps using WiFi are
1375 // migrated to a better network (typically ethernet) when one comes up, instead
1376 // of staying on WiFi forever.
1377 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1378 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1379
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001380 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1381 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1382 NetworkRequest.Type.BACKGROUND_REQUEST);
1383
Chalard Jean0702f982021-09-16 21:50:07 +09001384 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1385 // TODO: Consider making the timer customizable.
1386 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1387 mCellularRadioTimesharingCapable =
1388 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1389
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001390 mHandlerThread = mDeps.makeHandlerThread();
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001391 mHandlerThread.start();
1392 mHandler = new InternalHandler(mHandlerThread.getLooper());
1393 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001394 mConnectivityDiagnosticsHandler =
1395 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001396
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001397 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001398 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001399
junyulaie7c7d2a2021-01-26 15:29:15 +08001400 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001401 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001402 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001403 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001404
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001405 mNetd = netd;
Wink Saville32506bc2013-06-29 21:10:57 -07001406 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001407 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001408 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001409
Sudheer Shanka9967d462021-03-18 19:09:25 +00001410 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001411 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1412 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001413 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001414
1415 final PowerManager powerManager = (PowerManager) context.getSystemService(
1416 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001417 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001418 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001419
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001420 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1421 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001422 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001423 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001424 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001425 mProtectedNetworks.add(p);
1426 } else {
1427 if (DBG) loge("Ignoring protectedNetwork " + p);
1428 }
1429 }
1430
soma, kawata29444ae2019-05-23 09:30:40 +09001431 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1432
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001433 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -07001434
James Mattis02220e22021-03-13 19:27:21 -08001435 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001436 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001437 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001438 final IntentFilter userIntentFilter = new IntentFilter();
1439 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1440 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1441 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1442 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001443
James Mattis02220e22021-03-13 19:27:21 -08001444 // Listen to package add/removes for netd
1445 final IntentFilter packageIntentFilter = new IntentFilter();
1446 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1447 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1448 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1449 packageIntentFilter.addDataScheme("package");
1450 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001451 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001452
lucaslind5c2d072021-02-20 18:59:47 +08001453 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001454
lucaslin66f44212021-02-23 01:12:55 +08001455 mNetdCallback = new NetdCallback();
1456 try {
1457 mNetd.registerUnsolicitedEventListener(mNetdCallback);
1458 } catch (RemoteException | ServiceSpecificException e) {
1459 loge("Error registering event listener :" + e);
1460 }
1461
Erik Kline05f2b402015-04-30 12:58:40 +09001462 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1463 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001464
junyulai7e06ad42019-03-04 22:45:36 +08001465 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001466 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001467 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001468
1469 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001470 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001471 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1472 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001473 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001474 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1475 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001476
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001477 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001478 mContext, mHandler, () -> updateAvoidBadWifi());
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001479 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001480
Chiachang Wangc1215d32020-10-20 15:38:58 +08001481 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001482 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001483
Chalard Jean28018572020-12-21 18:36:52 +09001484 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1485 // request that doesn't allow fallback to the default network. It should never be visible
1486 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1487 // arguments like the handler or the DnsResolver.
1488 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001489 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001490 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001491 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001492 new LinkProperties(), new NetworkCapabilities(),
1493 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001494 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1495 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001496
1497 try {
1498 mDscpPolicyTracker = new DscpPolicyTracker();
1499 } catch (ErrnoException e) {
1500 loge("Unable to create DscpPolicyTracker");
1501 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001502 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001503
Chalard Jean46adcf32018-04-18 20:18:38 +09001504 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001505 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1506 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001507 }
1508
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001509 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1510 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001511 final NetworkCapabilities netCap = new NetworkCapabilities();
1512 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001513 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001514 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001515 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001516 return netCap;
1517 }
1518
James Mattis45d81842021-01-10 14:24:24 -08001519 private NetworkRequest createDefaultRequest() {
1520 return createDefaultInternetRequestForTransport(
1521 TYPE_NONE, NetworkRequest.Type.REQUEST);
1522 }
1523
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001524 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001525 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001526 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001527 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001528 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001529 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001530 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001531 netCap.addTransportType(transportType);
1532 }
James Mattis45d81842021-01-10 14:24:24 -08001533 return createNetworkRequest(type, netCap);
1534 }
1535
1536 private NetworkRequest createNetworkRequest(
1537 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001538 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001539 }
1540
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001541 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1542 NetworkRequest.Type type) {
1543 final NetworkCapabilities netCap = new NetworkCapabilities();
1544 netCap.clearAll();
1545 netCap.addCapability(capability);
1546 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1547 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1548 }
1549
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001550 // Used only for testing.
1551 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001552 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001553 // changing ContentResolver to make registerContentObserver non-final).
1554 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1555 // by subclassing SettingsObserver.
1556 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001557 void updateAlwaysOnNetworks() {
1558 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001559 }
1560
Erik Kline9a62f012018-03-21 07:18:33 -07001561 // See FakeSettingsProvider comment above.
1562 @VisibleForTesting
1563 void updatePrivateDnsSettings() {
1564 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1565 }
1566
paulhu51f77dc2021-06-07 02:34:20 +00001567 @VisibleForTesting
1568 void updateMobileDataPreferredUids() {
1569 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1570 }
1571
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09001572 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, int id) {
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001573 final boolean enable = mContext.getResources().getBoolean(id);
1574 handleAlwaysOnNetworkRequest(networkRequest, enable);
1575 }
1576
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001577 private void handleAlwaysOnNetworkRequest(
1578 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001579 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001580 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001581 handleAlwaysOnNetworkRequest(networkRequest, enable);
1582 }
1583
1584 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001585 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001586 if (enable == isEnabled) {
1587 return; // Nothing to do.
1588 }
1589
1590 if (enable) {
1591 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001592 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001593 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001594 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001595 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001596 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1597 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001598 }
1599 }
1600
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001601 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001602 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1603 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1604 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1605 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001606 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1607 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001608 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001609 }
1610
paulhu51f77dc2021-06-07 02:34:20 +00001611 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001612 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001613 private void registerSettingsCallbacks() {
1614 // Watch for global HTTP proxy changes.
1615 mSettingsObserver.observe(
1616 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1617 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1618
1619 // Watch for whether or not to keep mobile data always on.
1620 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001621 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001622 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1623
1624 // Watch for whether or not to keep wifi always on.
1625 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001626 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001627 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001628
1629 // Watch for mobile data preferred uids changes.
1630 mSettingsObserver.observe(
1631 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1632 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001633 }
1634
Erik Kline31b4a9e2018-01-11 21:07:29 +09001635 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001636 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1637 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001638 }
1639 }
1640
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001641 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001642 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1643 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001644 return mNextNetworkRequestId++;
1645 }
1646
junyulai74f9a8b2018-06-13 15:00:37 +08001647 @VisibleForTesting
1648 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001649 if (network == null) {
1650 return null;
1651 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001652 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001653 }
1654
1655 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001656 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001657 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001658 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001659 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001660
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001661 // TODO: determine what to do when more than one VPN applies to |uid|.
1662 private NetworkAgentInfo getVpnForUid(int uid) {
1663 synchronized (mNetworkForNetId) {
1664 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1665 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
1666 if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) {
1667 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001668 }
1669 }
1670 }
1671 return null;
1672 }
1673
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001674 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001675 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001676 final NetworkAgentInfo nai = getVpnForUid(uid);
1677 if (nai != null) return nai.declaredUnderlyingNetworks;
1678 return null;
1679 }
1680
Lorenzo Colittia7574052021-01-19 01:33:05 +09001681 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001682 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001683
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001684 final Network[] networks = getVpnUnderlyingNetworks(uid);
1685 if (networks != null) {
1686 // getUnderlyingNetworks() returns:
1687 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1688 // empty array => the VPN explicitly said "no default network".
1689 // non-empty array => the VPN specified one or more default networks; we use the
1690 // first one.
1691 if (networks.length > 0) {
1692 nai = getNetworkAgentInfoForNetwork(networks[0]);
1693 } else {
1694 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001695 }
1696 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001697 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001698 }
1699
1700 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001701 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001702 */
paulhu7aeba372020-12-30 00:42:19 +08001703 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1704 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001705 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001706 if (ignoreBlocked) {
1707 return false;
1708 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001709 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001710 final long ident = Binder.clearCallingIdentity();
1711 try {
1712 final boolean metered = nc == null ? true : nc.isMetered();
1713 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1714 } finally {
1715 Binder.restoreCallingIdentity(ident);
1716 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001717 }
1718
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001719 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001720 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1721 return;
1722 }
Hugo Benichi47011212017-03-30 10:46:05 +09001723 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001724 synchronized (mBlockedAppUids) {
1725 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001726 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001727 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001728 blocked = false;
1729 } else {
1730 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001731 }
1732 }
Hugo Benichi47011212017-03-30 10:46:05 +09001733 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1734 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1735 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001736 }
1737
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001738 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001739 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1740 return;
1741 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001742 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001743 final int requestId = nri.getActiveRequest() != null
1744 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001745 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001746 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001747 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001748 }
1749
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001750 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001751 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001752 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001753 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001754 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001755 @NonNull
1756 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1757 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001758 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1759 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1760 // but only exists if an app asks about them or requests them. Ensure the requesting app
1761 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001762 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001763 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1764 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1765 null /* extraInfo */);
1766 }
1767 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001768 return filtered;
1769 }
1770
1771 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1772 boolean ignoreBlocked) {
1773 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1774 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001775 }
1776
1777 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001778 * Return NetworkInfo for the active (i.e., connected) network interface.
1779 * It is assumed that at most one network is active at a time. If more
1780 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001781 * @return the info for the active network, or {@code null} if none is
1782 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001783 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001784 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001785 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001786 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001787 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001788 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1789 if (nai == null) return null;
1790 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1791 maybeLogBlockedNetworkInfo(networkInfo, uid);
1792 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001793 }
1794
Paul Jensen1f567382015-02-13 14:18:39 -05001795 @Override
1796 public Network getActiveNetwork() {
1797 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001798 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00001799 }
1800
1801 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001802 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001803 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001804 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001805 }
1806
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001807 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001808 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1809 if (vpnNai != null) {
1810 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1811 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1812 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09001813 }
Paul Jensen1f567382015-02-13 14:18:39 -05001814 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001815
James Mattis2516da32021-01-31 17:06:19 -08001816 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001817 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1818 ignoreBlocked)) {
1819 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001820 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001821 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05001822 }
1823
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001824 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001825 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001826 PermissionUtils.enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001827 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1828 if (nai == null) return null;
1829 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001830 }
1831
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001832 /** Returns a NetworkInfo object for a network that doesn't exist. */
1833 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1834 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1835 getNetworkTypeName(networkType), "" /* subtypeName */);
1836 info.setIsAvailable(true);
1837 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1838 // background data is restricted.
1839 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1840 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1841 ? DetailedState.BLOCKED
1842 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001843 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1844 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001845 return info;
1846 }
1847
Lorenzo Colittia7574052021-01-19 01:33:05 +09001848 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001849 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1850 return null;
1851 }
1852 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001853 if (nai == null) {
1854 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001855 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001856 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1857 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001858 }
1859
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001860 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001861 public NetworkInfo getNetworkInfo(int networkType) {
1862 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001863 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001864 if (getVpnUnderlyingNetworks(uid) != null) {
1865 // A VPN is active, so we may need to return one of its underlying networks. This
1866 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09001867 // getNetworkAgentInfoForUid.
1868 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1869 if (nai == null) return null;
1870 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1871 if (networkInfo.getType() == networkType) {
1872 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001873 }
1874 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001875 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001876 }
1877
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001878 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001879 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001880 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001881 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001882 if (nai == null) return null;
1883 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001884 }
1885
1886 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001887 public NetworkInfo[] getAllNetworkInfo() {
1888 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08001889 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04001890 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1891 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001892 NetworkInfo info = getNetworkInfo(networkType);
1893 if (info != null) {
1894 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001895 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001896 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001897 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001898 }
1899
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001900 @Override
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001901 public Network getNetworkForType(int networkType) {
1902 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001903 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1904 return null;
1905 }
1906 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1907 if (nai == null) {
1908 return null;
1909 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001910 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001911 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
1912 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001913 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001914 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001915 }
1916
1917 @Override
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001918 public Network[] getAllNetworks() {
1919 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001920 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04001921 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001922 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04001923 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001924 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04001925 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001926 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001927 }
1928
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001929 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08001930 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001931 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001932 // The basic principle is: if an app's traffic could possibly go over a
1933 // network, without the app doing anything multinetwork-specific,
1934 // (hence, by "default"), then include that network's capabilities in
1935 // the array.
1936 //
1937 // In the normal case, app traffic only goes over the system's default
1938 // network connection, so that's the only network returned.
1939 //
1940 // With a VPN in force, some app traffic may go into the VPN, and thus
1941 // over whatever underlying networks the VPN specifies, while other app
1942 // traffic may go over the system default network (e.g.: a split-tunnel
1943 // VPN, or an app disallowed by the VPN), so the set of networks
1944 // returned includes the VPN's underlying networks and the system
1945 // default.
1946 enforceAccessPermission();
1947
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001948 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001949
James Mattis2516da32021-01-31 17:06:19 -08001950 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
1951 if (!nri.isBeingSatisfied()) {
1952 continue;
1953 }
1954 final NetworkAgentInfo nai = nri.getSatisfier();
1955 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
1956 if (null != nc
1957 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
1958 && !result.containsKey(nai.network)) {
1959 result.put(
1960 nai.network,
1961 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08001962 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08001963 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
1964 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08001965 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001966 }
1967
Lorenzo Colittidfab3032020-12-15 00:49:41 +09001968 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09001969 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08001970 if (null != networks) {
1971 for (final Network network : networks) {
1972 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
1973 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08001974 result.put(
1975 network,
1976 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08001977 nc,
1978 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08001979 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08001980 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001981 }
1982 }
1983 }
1984
1985 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1986 out = result.values().toArray(out);
1987 return out;
1988 }
1989
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001990 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001991 public boolean isNetworkSupported(int networkType) {
1992 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001993 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001994 }
1995
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001996 /**
1997 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08001998 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07001999 * @return the ip properties for the active network, or {@code null} if
2000 * none is active
2001 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002002 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002003 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002004 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002005 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002006 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2007 if (nai == null) return null;
2008 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002009 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002010 }
2011
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002012 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002013 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002014 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002015 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002016 final LinkProperties lp = getLinkProperties(nai);
2017 if (lp == null) return null;
2018 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002019 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002020 }
2021
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002022 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002023 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002024 public LinkProperties getLinkProperties(Network network) {
2025 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002026 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2027 if (lp == null) return null;
2028 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002029 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002030 }
2031
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002032 @Nullable
2033 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002034 if (nai == null) {
2035 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002036 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002037 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002038 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002039 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002040 }
2041
Qingxi Lib2748102020-01-08 12:51:49 -08002042 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2043 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2044 }
2045
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002046 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002047 if (nai == null) return null;
2048 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002049 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002050 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002051 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002052 }
2053
2054 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002055 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2056 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002057 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002058 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002059 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002060 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002061 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002062 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002063 }
2064
Qingxi Libb8da982020-01-17 17:54:27 -08002065 @VisibleForTesting
2066 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002067 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002068 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002069 if (!checkSettingsPermission(callerPid, callerUid)) {
2070 newNc.setUids(null);
2071 newNc.setSSID(null);
lucaslin6adf5ac2021-10-19 15:04:56 +08002072 newNc.setUnderlyingNetworks(null);
Chalard Jean46adcf32018-04-18 20:18:38 +09002073 }
Etan Cohen107ae952018-12-30 17:59:59 -08002074 if (newNc.getNetworkSpecifier() != null) {
2075 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2076 }
Cody Kesting5ab1f552020-03-16 18:15:28 -07002077 newNc.setAdministratorUids(new int[0]);
Benedict Wong53de25f2021-03-24 14:01:51 -07002078 if (!checkAnyPermissionOf(
2079 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
junyulai2217bec2021-04-14 23:33:31 +08002080 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002081 }
Qingxi Libb8da982020-01-17 17:54:27 -08002082
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002083 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002084 }
2085
Roshan Pius98f59ec2021-02-23 08:47:39 -08002086 /**
2087 * Wrapper used to cache the permission check results performed for the corresponding
2088 * app. This avoid performing multiple permission checks for different fields in
2089 * NetworkCapabilities.
2090 * Note: This wrapper does not support any sort of invalidation and thus must not be
2091 * persistent or long-lived. It may only be used for the time necessary to
2092 * compute the redactions required by one particular NetworkCallback or
2093 * synchronous call.
2094 */
2095 private class RedactionPermissionChecker {
2096 private final int mCallingPid;
2097 private final int mCallingUid;
2098 @NonNull private final String mCallingPackageName;
2099 @Nullable private final String mCallingAttributionTag;
2100
2101 private Boolean mHasLocationPermission = null;
2102 private Boolean mHasLocalMacAddressPermission = null;
2103 private Boolean mHasSettingsPermission = null;
2104
2105 RedactionPermissionChecker(int callingPid, int callingUid,
2106 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2107 mCallingPid = callingPid;
2108 mCallingUid = callingUid;
2109 mCallingPackageName = callingPackageName;
2110 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002111 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002112
2113 private boolean hasLocationPermissionInternal() {
2114 final long token = Binder.clearCallingIdentity();
2115 try {
2116 return mLocationPermissionChecker.checkLocationPermission(
2117 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2118 null /* message */);
2119 } finally {
2120 Binder.restoreCallingIdentity(token);
2121 }
2122 }
2123
2124 /**
2125 * Returns whether the app holds location permission or not (might return cached result
2126 * if the permission was already checked before).
2127 */
2128 public boolean hasLocationPermission() {
2129 if (mHasLocationPermission == null) {
2130 // If there is no cached result, perform the check now.
2131 mHasLocationPermission = hasLocationPermissionInternal();
2132 }
2133 return mHasLocationPermission;
2134 }
2135
2136 /**
2137 * Returns whether the app holds local mac address permission or not (might return cached
2138 * result if the permission was already checked before).
2139 */
2140 public boolean hasLocalMacAddressPermission() {
2141 if (mHasLocalMacAddressPermission == null) {
2142 // If there is no cached result, perform the check now.
2143 mHasLocalMacAddressPermission =
2144 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2145 }
2146 return mHasLocalMacAddressPermission;
2147 }
2148
2149 /**
2150 * Returns whether the app holds settings permission or not (might return cached
2151 * result if the permission was already checked before).
2152 */
2153 public boolean hasSettingsPermission() {
2154 if (mHasSettingsPermission == null) {
2155 // If there is no cached result, perform the check now.
2156 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2157 }
2158 return mHasSettingsPermission;
2159 }
2160 }
2161
2162 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2163 @NetworkCapabilities.NetCapability long redaction) {
2164 return (redactions & redaction) != 0;
2165 }
2166
2167 /**
2168 * Use the provided |applicableRedactions| to check the receiving app's
2169 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2170 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2171 * before being sent to the corresponding app.
2172 */
2173 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2174 @NetworkCapabilities.RedactionType long applicableRedactions,
2175 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2176 boolean includeLocationSensitiveInfo) {
2177 long redactions = applicableRedactions;
2178 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2179 if (includeLocationSensitiveInfo
2180 && redactionPermissionChecker.hasLocationPermission()) {
2181 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2182 }
2183 }
2184 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2185 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2186 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2187 }
2188 }
2189 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2190 if (redactionPermissionChecker.hasSettingsPermission()) {
2191 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2192 }
2193 }
2194 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002195 }
2196
Qingxi Lib2748102020-01-08 12:51:49 -08002197 @VisibleForTesting
2198 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002199 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002200 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002201 int callingPid, int callingUid, @NonNull String callingPkgName,
2202 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002203 if (nc == null) {
2204 return null;
2205 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002206 // Avoid doing location permission check if the transport info has no location sensitive
2207 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002208 final RedactionPermissionChecker redactionPermissionChecker =
2209 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2210 callingAttributionTag);
2211 final long redactions = retrieveRequiredRedactions(
2212 nc.getApplicableRedactions(), redactionPermissionChecker,
2213 includeLocationSensitiveInfo);
2214 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002215 // Reset owner uid if not destined for the owner app.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002216 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002217 newNc.setOwnerUid(INVALID_UID);
2218 return newNc;
2219 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002220 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2221 if (nc.hasTransport(TRANSPORT_VPN)) {
2222 // Owner UIDs already checked above. No need to re-check.
2223 return newNc;
2224 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002225 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2226 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002227 // compatibility for older apps.
2228 if (!includeLocationSensitiveInfo
2229 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002230 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002231 newNc.setOwnerUid(INVALID_UID);
2232 return newNc;
2233 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002234 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002235 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002236 newNc.setOwnerUid(INVALID_UID);
2237 }
Qingxi Lib2748102020-01-08 12:51:49 -08002238 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002239 }
2240
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002241 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2242 LinkProperties lp, int callerPid, int callerUid) {
2243 if (lp == null) return new LinkProperties();
2244
2245 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2246 final boolean needsSanitization =
2247 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2248 if (!needsSanitization) {
2249 return new LinkProperties(lp);
2250 }
2251
2252 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002253 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002254 }
2255
2256 final LinkProperties newLp = new LinkProperties(lp);
2257 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2258 // object gets parceled.
2259 newLp.setCaptivePortalApiUrl(null);
2260 newLp.setCaptivePortalData(null);
2261 return newLp;
2262 }
2263
Roshan Pius08c94fb2020-01-16 12:17:17 -08002264 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2265 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002266 // There is no need to track the effective UID of the request here. If the caller
2267 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002268 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002269 // Unprivileged apps can only pass in null or their own UID.
2270 if (nc.getUids() == null) {
2271 // If the caller passes in null, the callback will also match networks that do not
2272 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2273 // In this case, redact everything in the request immediately. This ensures that the
2274 // app is not able to get any redacted information by filing an unredacted request
2275 // and observing whether the request matches something.
2276 if (nc.getNetworkSpecifier() != null) {
2277 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2278 }
2279 } else {
2280 nc.setSingleUid(callerUid);
2281 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002282 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002283 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002284 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002285
2286 // Clear owner UID; this can never come from an app.
2287 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002288 }
2289
Chalard Jean38354d12018-03-20 19:13:57 +09002290 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002291 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002292 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2293 }
2294 }
2295
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002296 @Override
2297 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2298 enforceAccessPermission();
2299 final int callerUid = Binder.getCallingUid();
2300 final long token = Binder.clearCallingIdentity();
2301 try {
2302 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2303 } finally {
2304 Binder.restoreCallingIdentity(token);
2305 }
2306 }
2307
junyulaiebd15162021-03-03 12:09:05 +08002308 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002309 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002310 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002311 // This contains IMSI details, so make sure the caller is privileged.
paulhudf23d662021-01-25 18:53:17 +08002312 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002313
Serik Beketayev05130302021-01-15 16:47:25 -08002314 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002315 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002316 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2317 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002318 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002319 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002320 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002321 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2322 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002323 }
2324 }
2325 return result.toArray(new NetworkState[result.size()]);
2326 }
2327
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002328 @Override
junyulaiebd15162021-03-03 12:09:05 +08002329 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002330 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002331 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002332 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002333
2334 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2335 for (Network network : getAllNetworks()) {
2336 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Junyu Laiddecb662021-08-17 08:44:36 +00002337 if (nai != null && nai.everConnected) {
junyulaiebd15162021-03-03 12:09:05 +08002338 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2339 // NetworkCapabilities, which may contain UIDs of apps to which the
2340 // network applies. Should the UIDs be cleared so as not to leak or
2341 // interfere ?
2342 result.add(nai.getNetworkStateSnapshot());
2343 }
2344 }
2345 return result;
2346 }
2347
2348 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002349 public boolean isActiveNetworkMetered() {
2350 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002351
Qingxi Lib2748102020-01-08 12:51:49 -08002352 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002353 if (caps != null) {
2354 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2355 } else {
2356 // Always return the most conservative value
2357 return true;
2358 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002359 }
2360
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002361 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002362 * Ensures that the system cannot call a particular method.
2363 */
2364 private boolean disallowedBecauseSystemCaller() {
2365 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002366 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2367 // for devices launched with Q and above. However, existing devices upgrading to Q and
2368 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002369 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002370 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002371 log("This method exists only for app backwards compatibility"
2372 + " and must not be called by system services.");
2373 return true;
2374 }
2375 return false;
2376 }
2377
paulhub2c28682021-08-18 18:35:54 +08002378 private int getAppUid(final String app, final UserHandle user) {
2379 final PackageManager pm =
2380 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2381 final long token = Binder.clearCallingIdentity();
2382 try {
2383 return pm.getPackageUid(app, 0 /* flags */);
2384 } catch (PackageManager.NameNotFoundException e) {
2385 return -1;
2386 } finally {
2387 Binder.restoreCallingIdentity(token);
2388 }
2389 }
2390
2391 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2392 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2393 if (getAppUid(packageName, user) != callingUid) {
2394 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2395 }
2396 }
2397
Lorenzo Colitti23862912018-09-28 11:31:55 +09002398 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002399 * Ensure that a network route exists to deliver traffic to the specified
2400 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002401 * @param networkType the type of the network over which traffic to the
2402 * specified host is to be routed
2403 * @param hostAddress the IP address of the host to which the route is
2404 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002405 * @return {@code true} on success, {@code false} on failure
2406 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002407 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002408 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2409 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002410 if (disallowedBecauseSystemCaller()) {
2411 return false;
2412 }
paulhub2c28682021-08-18 18:35:54 +08002413 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002414 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002415 if (mProtectedNetworks.contains(networkType)) {
paulhu8e96a752019-08-12 16:25:11 +08002416 enforceConnectivityRestrictedNetworksPermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002417 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002418
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002419 InetAddress addr;
2420 try {
2421 addr = InetAddress.getByAddress(hostAddress);
2422 } catch (UnknownHostException e) {
2423 if (DBG) log("requestRouteToHostAddress got " + e.toString());
2424 return false;
2425 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002426
The Android Open Source Project28527d22009-03-03 19:31:44 -08002427 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002428 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002429 return false;
2430 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002431
2432 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2433 if (nai == null) {
2434 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
2435 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2436 } else {
2437 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2438 }
2439 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002440 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002441
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002442 DetailedState netState;
2443 synchronized (nai) {
2444 netState = nai.networkInfo.getDetailedState();
2445 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002446
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002447 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002448 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002449 log("requestRouteToHostAddress on down network "
2450 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002451 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002452 }
2453 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002454 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002455
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002456 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002457 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002458 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002459 LinkProperties lp;
2460 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002461 synchronized (nai) {
2462 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002463 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002464 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002465 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002466 if (DBG) {
2467 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2468 }
Wink Saville32506bc2013-06-29 21:10:57 -07002469 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002470 } finally {
2471 Binder.restoreCallingIdentity(token);
2472 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002473 }
2474
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002475 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002476 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002477 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002478 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002479 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002480 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002481 if (bestRoute.getGateway().equals(addr)) {
2482 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002483 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002484 } else {
2485 // if we will connect to this through another route, add a direct route
2486 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002487 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002488 }
2489 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002490 if (DBG) log("Adding legacy route " + bestRoute +
2491 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002492
2493 final String dst = bestRoute.getDestinationLinkAddress().toString();
2494 final String nextHop = bestRoute.hasGateway()
2495 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002496 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002497 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2498 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002499 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002500 return false;
2501 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002502 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002503 }
2504
paulhu7c0a2e62021-01-08 00:51:49 +08002505 class DnsResolverUnsolicitedEventCallback extends
2506 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002507 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002508 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002509 try {
2510 mHandler.sendMessage(mHandler.obtainMessage(
2511 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002512 new PrivateDnsValidationUpdate(event.netId,
2513 InetAddresses.parseNumericAddress(event.ipAddress),
2514 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002515 } catch (IllegalArgumentException e) {
2516 loge("Error parsing ip address in validation event");
2517 }
2518 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002519
2520 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002521 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2522 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002523 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2524 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2525 // event callback for certain nai. e.g. cellular. Register here to pass to
2526 // NetworkMonitor instead.
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002527 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allow one
2528 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2529 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002530 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002531 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002532 }
2533 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002534
2535 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002536 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2537 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2538 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002539 }
dalyk1720e542018-03-05 12:42:22 -05002540
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002541 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002542 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002543 return this.VERSION;
2544 }
2545
2546 @Override
2547 public String getInterfaceHash() {
2548 return this.HASH;
2549 }
paulhu7c0a2e62021-01-08 00:51:49 +08002550 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002551
2552 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002553 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2554 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002555
paulhu7c0a2e62021-01-08 00:51:49 +08002556 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002557 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002558 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002559 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002560 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002561 }
2562 }
2563
Sudheer Shanka9967d462021-03-18 19:09:25 +00002564 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002565 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002566 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002567 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2568 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002569 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002570 };
2571
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002572 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002573 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002574 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002575 }
2576
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002577 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002578 for (String permission : permissions) {
2579 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002580 return true;
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002581 }
2582 }
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002583 return false;
2584 }
2585
paulhu1a407652019-03-22 16:35:06 +08002586 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2587 for (String permission : permissions) {
2588 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2589 return true;
2590 }
2591 }
2592 return false;
2593 }
2594
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002595 private void enforceAnyPermissionOf(String... permissions) {
2596 if (!checkAnyPermissionOf(permissions)) {
2597 throw new SecurityException("Requires one of the following permissions: "
2598 + String.join(", ", permissions) + ".");
2599 }
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002600 }
2601
Paul Jensen83f5d572014-08-29 09:54:01 -04002602 private void enforceInternetPermission() {
2603 mContext.enforceCallingOrSelfPermission(
2604 android.Manifest.permission.INTERNET,
2605 "ConnectivityService");
2606 }
2607
The Android Open Source Project28527d22009-03-03 19:31:44 -08002608 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002609 mContext.enforceCallingOrSelfPermission(
2610 android.Manifest.permission.ACCESS_NETWORK_STATE,
2611 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002612 }
2613
paulhua6ee2122021-02-22 15:40:43 +08002614 /**
2615 * Performs a strict and comprehensive check of whether a calling package is allowed to
2616 * change the state of network, as the condition differs for pre-M, M+, and
2617 * privileged/preinstalled apps. The caller is expected to have either the
2618 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2619 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2620 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2621 * permission and cannot be revoked. See http://b/23597341
2622 *
2623 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2624 * of this app will be updated to the current time.
2625 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002626 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002627 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2628 == PackageManager.PERMISSION_GRANTED) {
2629 return;
2630 }
2631
2632 if (callingPkg == null) {
2633 throw new SecurityException("Calling package name is null.");
2634 }
2635
2636 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2637 final int uid = mDeps.getCallingUid();
2638 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2639 callingPkg, callingAttributionTag, null /* message */);
2640
2641 if (mode == AppOpsManager.MODE_ALLOWED) {
2642 return;
2643 }
2644
2645 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2646 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2647 return;
2648 }
2649
2650 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2651 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2652 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002653 }
2654
Charles He9369e612017-05-15 17:07:18 +01002655 private void enforceSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002656 enforceAnyPermissionOf(
Charles He9369e612017-05-15 17:07:18 +01002657 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002658 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002659 }
2660
paulhu8e96a752019-08-12 16:25:11 +08002661 private void enforceNetworkFactoryPermission() {
paulhub6ba8e82020-03-04 09:43:41 +08002662 enforceAnyPermissionOf(
paulhu8e96a752019-08-12 16:25:11 +08002663 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002664 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002665 }
2666
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002667 private void enforceNetworkFactoryOrSettingsPermission() {
2668 enforceAnyPermissionOf(
2669 android.Manifest.permission.NETWORK_SETTINGS,
2670 android.Manifest.permission.NETWORK_FACTORY,
2671 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2672 }
2673
2674 private void enforceNetworkFactoryOrTestNetworksPermission() {
2675 enforceAnyPermissionOf(
2676 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2677 android.Manifest.permission.NETWORK_FACTORY,
2678 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2679 }
2680
Chalard Jean9a396cc2018-02-21 18:43:54 +09002681 private boolean checkSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002682 return checkAnyPermissionOf(
2683 android.Manifest.permission.NETWORK_SETTINGS,
2684 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002685 }
2686
2687 private boolean checkSettingsPermission(int pid, int uid) {
2688 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002689 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2690 || PERMISSION_GRANTED == mContext.checkPermission(
2691 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002692 }
2693
paulhu8e96a752019-08-12 16:25:11 +08002694 private void enforceNetworkStackOrSettingsPermission() {
2695 enforceAnyPermissionOf(
2696 android.Manifest.permission.NETWORK_SETTINGS,
2697 android.Manifest.permission.NETWORK_STACK,
2698 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2699 }
2700
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002701 private void enforceNetworkStackSettingsOrSetup() {
2702 enforceAnyPermissionOf(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002703 android.Manifest.permission.NETWORK_SETTINGS,
2704 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002705 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002706 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002707 }
2708
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002709 private void enforceAirplaneModePermission() {
2710 enforceAnyPermissionOf(
2711 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2712 android.Manifest.permission.NETWORK_SETTINGS,
2713 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2714 android.Manifest.permission.NETWORK_STACK,
2715 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2716 }
2717
James Mattis8378aec2021-01-26 14:05:36 -08002718 private void enforceOemNetworkPreferencesPermission() {
2719 mContext.enforceCallingOrSelfPermission(
2720 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2721 "ConnectivityService");
2722 }
2723
James Mattisfa270db2021-05-31 17:11:10 -07002724 private void enforceManageTestNetworksPermission() {
2725 mContext.enforceCallingOrSelfPermission(
2726 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2727 "ConnectivityService");
2728 }
2729
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002730 private boolean checkNetworkStackPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002731 return checkAnyPermissionOf(
2732 android.Manifest.permission.NETWORK_STACK,
2733 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002734 }
2735
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002736 private boolean checkNetworkStackPermission(int pid, int uid) {
2737 return checkAnyPermissionOf(pid, uid,
2738 android.Manifest.permission.NETWORK_STACK,
2739 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2740 }
2741
paulhu1a407652019-03-22 16:35:06 +08002742 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2743 return checkAnyPermissionOf(pid, uid,
2744 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002745 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2746 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002747 }
2748
Hugo Benichibd0cc762016-07-19 15:59:27 +09002749 private void enforceConnectivityRestrictedNetworksPermission() {
2750 try {
2751 mContext.enforceCallingOrSelfPermission(
2752 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2753 "ConnectivityService");
2754 return;
2755 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
paulhu8e96a752019-08-12 16:25:11 +08002756 // TODO: Remove this fallback check after all apps have declared
2757 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2758 mContext.enforceCallingOrSelfPermission(
2759 android.Manifest.permission.CONNECTIVITY_INTERNAL,
2760 "ConnectivityService");
Hugo Benichibd0cc762016-07-19 15:59:27 +09002761 }
2762
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002763 private void enforceKeepalivePermission() {
Lorenzo Colittif25beee2015-09-08 13:21:48 +09002764 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002765 }
2766
Roshan Pius98f59ec2021-02-23 08:47:39 -08002767 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2768 return PERMISSION_GRANTED == mContext.checkPermission(
2769 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2770 }
2771
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002772 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002773 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002774 }
2775
2776 private void sendInetConditionBroadcast(NetworkInfo info) {
2777 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2778 }
2779
Wink Saville4f0de1e2011-08-04 15:01:58 -07002780 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002781 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002782 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002783 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002784 if (info.isFailover()) {
2785 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2786 info.setFailover(false);
2787 }
2788 if (info.getReason() != null) {
2789 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2790 }
2791 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002792 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2793 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002794 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002795 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002796 return intent;
2797 }
2798
2799 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2800 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2801 }
2802
Chiachang Wang3bc52762021-11-25 14:17:57 +08002803 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
2804 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002805 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09002806 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09002807 if (!mSystemReady
2808 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002809 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002810 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002811 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002812 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002813 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002814 }
2815
Dianne Hackborn66dd0332015-12-09 17:22:26 -08002816 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07002817 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002818 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07002819 final NetworkInfo ni = intent.getParcelableExtra(
2820 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08002821 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2822 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2823 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08002824 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002825 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07002826 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00002827 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002828 } finally {
2829 Binder.restoreCallingIdentity(ident);
2830 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002831 }
2832 }
2833
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002834 /**
Aaron Huang96011892020-06-27 07:18:23 +08002835 * Called by SystemServer through ConnectivityManager when the system is ready.
2836 */
2837 @Override
2838 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002839 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08002840 throw new SecurityException("Calling Uid is not system uid.");
2841 }
2842 systemReadyInternal();
2843 }
2844
2845 /**
2846 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002847 */
2848 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08002849 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09002850 // Load flags after PackageManager is ready to query module version
2851 mFlags.loadFlags(mDeps, mContext);
2852
Aaron Huang9a57acf2020-12-08 10:03:29 +08002853 // Since mApps in PermissionMonitor needs to be populated first to ensure that
2854 // listening network request which is sent by MultipathPolicyTracker won't be added
2855 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
2856 // be called after PermissionMonitor#startMonitoring().
2857 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
2858 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
2859 // to ensure the tracking will be initialized correctly.
paulhuc62d3c22019-11-19 17:55:31 +08002860 mPermissionMonitor.startMonitoring();
Chalard Jeane4f9bd92018-06-08 12:47:42 +09002861 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08002862 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002863
Hugo Benichie5220992017-04-26 14:53:28 +09002864 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002865 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002866 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07002867 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002868 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002869 }
2870 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002871
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002872 // Create network requests for always-on networks.
2873 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00002874
2875 // Update mobile data preference if necessary.
2876 // Note that empty uid list can be skip here only because no uid rules applied before system
2877 // ready. Normally, the empty uid list means to clear the uids rules on netd.
2878 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
2879 updateMobileDataPreferredUids();
2880 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002881 }
2882
The Android Open Source Project28527d22009-03-03 19:31:44 -08002883 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002884 * Start listening for default data network activity state changes.
2885 */
2886 @Override
2887 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08002888 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002889 }
2890
2891 /**
2892 * Stop listening for default data network activity state changes.
2893 */
2894 @Override
2895 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08002896 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002897 }
2898
2899 /**
2900 * Check whether the default network radio is currently active.
2901 */
2902 @Override
2903 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08002904 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002905 }
2906
2907 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09002908 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09002909 * and set it on it's iface.
2910 */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002911 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2912 final String iface = newLp.getInterfaceName();
2913 final int mtu = newLp.getMtu();
Pierre Imai07c53a32016-02-08 16:01:40 +09002914 if (oldLp == null && mtu == 0) {
2915 // Silently ignore unset MTU value.
2916 return;
2917 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002918 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2919 if (VDBG) log("identical MTU - not setting");
2920 return;
2921 }
paulhucbbc3db2019-03-08 16:35:20 +08002922 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002923 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002924 return;
2925 }
sy.yun4aa73922013-09-02 05:24:09 +09002926
w19976e714f1d2014-08-05 15:18:11 -07002927 // Cannot set MTU without interface name
2928 if (TextUtils.isEmpty(iface)) {
2929 loge("Setting MTU size with null iface.");
2930 return;
2931 }
2932
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002933 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09002934 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08002935 mNetd.interfaceSetMtu(iface, mtu);
2936 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08002937 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002938 }
2939 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002940
Chenbo Feng15416292018-11-08 17:36:21 -08002941 @VisibleForTesting
2942 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04002943
lucaslin821c9782018-11-28 19:27:52 +08002944 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002945 String[] values = null;
2946 if (tcpBufferSizes != null) {
2947 values = tcpBufferSizes.split(",");
2948 }
2949
2950 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07002951 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002952 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2953 values = tcpBufferSizes.split(",");
2954 }
2955
2956 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2957
2958 try {
Aaron Huang6616df32020-10-30 22:04:25 +08002959 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002960
Chenbo Feng15416292018-11-08 17:36:21 -08002961 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2962 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2963 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002964 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08002965 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002966 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002967 }
2968 }
2969
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07002970 @Override
2971 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09002972 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07002973 NETWORK_RESTORE_DELAY_PROP_NAME);
2974 if(restoreDefaultNetworkDelayStr != null &&
2975 restoreDefaultNetworkDelayStr.length() != 0) {
2976 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01002977 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002978 } catch (NumberFormatException e) {
2979 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002980 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002981 // if the system property isn't set, use the value for the apn type
2982 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2983
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09002984 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
2985 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002986 }
2987 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002988 }
2989
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002990 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2991 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2992 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09002993 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08002994 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002995 // Start gathering diagnostic information.
2996 netDiags.add(new NetworkDiagnostics(
2997 nai.network,
2998 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08002999 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003000 DIAG_TIME_MS));
3001 }
3002
3003 for (NetworkDiagnostics netDiag : netDiags) {
3004 pw.println();
3005 netDiag.waitForMeasurements();
3006 netDiag.dump(pw);
3007 }
3008 }
3009
The Android Open Source Project28527d22009-03-03 19:31:44 -08003010 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003011 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3012 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003013 if (!checkDumpPermission(mContext, TAG, writer)) return;
3014
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003015 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003016 }
3017
lucaslin99473f62020-12-10 15:10:54 +08003018 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3019 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3020 != PackageManager.PERMISSION_GRANTED) {
3021 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003022 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003023 + " due to missing android.permission.DUMP permission");
3024 return false;
3025 } else {
3026 return true;
3027 }
3028 }
3029
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003030 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003031 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003032
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003033 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003034 dumpNetworkDiagnostics(pw);
3035 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003036 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003037 dumpNetworks(pw);
3038 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003039 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003040 dumpNetworkRequests(pw);
3041 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003042 }
Erik Kline9647f382015-06-05 17:47:34 +09003043
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003044 pw.print("NetworkProviders for:");
3045 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
3046 pw.print(" " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003047 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09003048 pw.println();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003049 pw.println();
3050
Chalard Jean5b409c72021-02-04 13:12:59 +09003051 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003052 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003053 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003054 pw.println("none");
3055 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003056 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003057 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003058 pw.println();
3059
James Mattis8b298a02021-06-01 22:34:04 -07003060 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003061 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003062 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003063 pw.decreaseIndent();
3064 pw.println();
3065
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003066 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003067 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003068 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003069 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003070 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003071
junyulaif2c67e42018-08-07 19:50:45 +08003072 pw.println("Status for known UIDs:");
3073 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003074 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003075 for (int i = 0; i < size; i++) {
3076 // Don't crash if the array is modified while dumping in bugreports.
3077 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003078 final int uid = mUidBlockedReasons.keyAt(i);
3079 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3080 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003081 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003082 } catch (ArrayIndexOutOfBoundsException e) {
3083 pw.println(" ArrayIndexOutOfBoundsException");
3084 } catch (ConcurrentModificationException e) {
3085 pw.println(" ConcurrentModificationException");
3086 }
3087 }
3088 pw.println();
3089 pw.decreaseIndent();
3090
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003091 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003092 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003093 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003094 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003095 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003096
Robert Greenwalt94e22142014-07-30 16:31:24 -07003097 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003098
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003099 pw.println();
markchien5e866652019-09-30 14:40:57 +08003100 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003101
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003102 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003103 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003104
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003105 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003106
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003107 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003108 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003109 pw.println("mNetworkRequestInfoLogs (most recent first):");
3110 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003111 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003112 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003113
3114 pw.println();
3115 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3116 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003117 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003118 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003119
3120 pw.println();
3121 pw.println("NetTransition WakeLock activity (most recent first):");
3122 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003123 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3124 pw.println("total releases: " + mTotalWakelockReleases);
3125 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3126 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3127 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3128 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3129 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3130 }
James Mattiscb1e0362021-04-06 17:07:42 -07003131 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003132
3133 pw.println();
3134 pw.println("bandwidth update requests (by uid):");
3135 pw.increaseIndent();
3136 synchronized (mBandwidthRequests) {
3137 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3138 pw.println("[" + mBandwidthRequests.keyAt(i)
3139 + "]: " + mBandwidthRequests.valueAt(i));
3140 }
3141 }
3142 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003143 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003144
James Mattiscb1e0362021-04-06 17:07:42 -07003145 pw.println();
3146 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3147 pw.increaseIndent();
3148 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003149 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003150 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003151
3152 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003153
3154 pw.println();
3155 pw.println("Permission Monitor:");
3156 pw.increaseIndent();
3157 mPermissionMonitor.dump(pw);
3158 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003159
3160 pw.println();
3161 pw.println("Legacy network activity:");
3162 pw.increaseIndent();
3163 mNetworkActivityTracker.dump(pw);
3164 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003165 }
3166
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003167 private void dumpNetworks(IndentingPrintWriter pw) {
3168 for (NetworkAgentInfo nai : networksSortedById()) {
3169 pw.println(nai.toString());
3170 pw.increaseIndent();
3171 pw.println(String.format(
3172 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3173 nai.numForegroundNetworkRequests(),
3174 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3175 nai.numBackgroundNetworkRequests(),
3176 nai.numNetworkRequests()));
3177 pw.increaseIndent();
3178 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3179 pw.println(nai.requestAt(i).toString());
3180 }
3181 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003182 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003183 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003184 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003185 pw.decreaseIndent();
3186 pw.decreaseIndent();
3187 }
3188 }
3189
James Mattis8b298a02021-06-01 22:34:04 -07003190 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3191 if (!mProfileNetworkPreferences.isEmpty()) {
3192 pw.println("Profile preferences:");
3193 pw.increaseIndent();
3194 pw.println(mProfileNetworkPreferences.preferences);
3195 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003196 }
James Mattis8b298a02021-06-01 22:34:04 -07003197 if (!mOemNetworkPreferences.isEmpty()) {
3198 pw.println("OEM preferences:");
3199 pw.increaseIndent();
3200 pw.println(mOemNetworkPreferences);
3201 pw.decreaseIndent();
3202 }
3203 if (!mMobileDataPreferredUids.isEmpty()) {
3204 pw.println("Mobile data preferred UIDs:");
3205 pw.increaseIndent();
3206 pw.println(mMobileDataPreferredUids);
3207 pw.decreaseIndent();
3208 }
James Mattis45d81842021-01-10 14:24:24 -08003209
James Mattis8b298a02021-06-01 22:34:04 -07003210 pw.println("Default requests:");
3211 pw.increaseIndent();
3212 dumpPerAppDefaultRequests(pw);
3213 pw.decreaseIndent();
3214 }
3215
3216 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003217 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3218 if (mDefaultRequest == defaultRequest) {
3219 continue;
3220 }
3221
James Mattis8b298a02021-06-01 22:34:04 -07003222 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3223 final String networkOutput;
3224 if (null == satisfier) {
3225 networkOutput = "null";
3226 } else if (mNoServiceNetwork.equals(satisfier)) {
3227 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003228 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003229 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003230 }
James Mattis8b298a02021-06-01 22:34:04 -07003231 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3232 ? "" : " asUid: " + defaultRequest.mAsUid;
3233 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3234 + defaultRequest.mPid + asUidString + "]";
3235 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3236 + " Preference order: " + defaultRequest.mPreferenceOrder
3237 + " Tracked UIDs: " + defaultRequest.getUids();
3238 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003239 }
3240 }
3241
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003242 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003243 NetworkRequestInfo[] infos = null;
3244 while (infos == null) {
3245 try {
3246 infos = requestsSortedById();
3247 } catch (ConcurrentModificationException e) {
3248 // mNetworkRequests should only be accessed from handler thread, except dump().
3249 // As dump() is never called in normal usage, it would be needlessly expensive
3250 // to lock the collection only for its benefit. Instead, retry getting the
3251 // requests if ConcurrentModificationException is thrown during dump().
3252 }
3253 }
3254 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003255 pw.println(nri.toString());
3256 }
3257 }
3258
Chalard Jean524f0b12021-10-25 21:11:56 +09003259 private void dumpAllRequestInfoLogsToLogcat() {
3260 try (PrintWriter logPw = new PrintWriter(new Writer() {
3261 @Override
3262 public void write(final char[] cbuf, final int off, final int len) {
3263 // This method is called with 0-length and 1-length arrays for empty strings
3264 // or strings containing only the DEL character.
3265 if (len <= 1) return;
3266 Log.e(TAG, new String(cbuf, off, len));
3267 }
3268 @Override public void flush() {}
3269 @Override public void close() {}
3270 })) {
3271 mNetworkRequestInfoLogs.dump(logPw);
3272 }
3273 }
3274
Hugo Benichia480ba52018-09-03 08:19:02 +09003275 /**
3276 * Return an array of all current NetworkAgentInfos sorted by network id.
3277 */
3278 private NetworkAgentInfo[] networksSortedById() {
3279 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003280 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003281 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003282 return networks;
3283 }
3284
3285 /**
3286 * Return an array of all current NetworkRequest sorted by request id.
3287 */
James Mattis258ea3c2020-11-15 15:04:40 -08003288 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003289 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003290 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003291 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003292 // Sort the array based off the NRI containing the min requestId in its requests.
3293 Arrays.sort(requests,
3294 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3295 Comparator.comparingInt(req -> req.requestId)).requestId
3296 )
3297 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003298 return requests;
3299 }
3300
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003301 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003302 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003303 if (officialNai != null && officialNai.equals(nai)) return true;
3304 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003305 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003306 " - " + nai);
3307 }
3308 return false;
3309 }
3310
Robert Greenwalt2034b912009-08-12 16:08:25 -07003311 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003312 private class NetworkStateTrackerHandler extends Handler {
3313 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003314 super(looper);
3315 }
3316
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003317 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003318 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3319 final NetworkAgentInfo nai = arg.first;
3320 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003321 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003322 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003323 }
3324 return;
3325 }
3326
3327 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003328 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003329 NetworkCapabilities networkCapabilities = (NetworkCapabilities) arg.second;
lucaslin2240ef62019-03-12 13:08:03 +08003330 if (networkCapabilities.hasConnectivityManagedCapability()) {
Aaron Huang6616df32020-10-30 22:04:25 +08003331 Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003332 }
Chalard Jean5b639762020-03-09 21:25:37 +09003333 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
3334 // Make sure the original object is not mutated. NetworkAgent normally
3335 // makes a copy of the capabilities when sending the message through
3336 // the Messenger, but if this ever changes, not making a defensive copy
3337 // here will give attack vectors to clients using this code path.
3338 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Chiachang Wangc07315a2021-08-10 15:13:39 +08003339 networkCapabilities.restrictCapabilitiesForTestNetwork(nai.creatorUid);
Chalard Jean5b639762020-03-09 21:25:37 +09003340 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003341 processCapabilitiesFromAgent(nai, networkCapabilities);
Hugo Benichibbc15192016-09-15 18:18:48 +09003342 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003343 break;
3344 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003345 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003346 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003347 processLinkPropertiesFromAgent(nai, newLp);
3348 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003349 break;
3350 }
3351 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003352 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003353 updateNetworkInfo(nai, info);
3354 break;
3355 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003356 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003357 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003358 break;
3359 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003360 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003361 if (nai.everConnected) {
3362 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003363 // Note that if the NAI had been connected, this would affect the
3364 // score, and therefore would require re-mixing the score and performing
3365 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003366 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003367 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3368 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003369 // Mark the network as temporarily accepting partial connectivity so that it
3370 // will be validated (and possibly become default) even if it only provides
3371 // partial internet access. Note that if user connects to partial connectivity
3372 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3373 // out of wifi coverage) and if the same wifi is available again, the device
3374 // will auto connect to this wifi even though the wifi has "no internet".
3375 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003376 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003377 break;
3378 }
junyulai011b1f12019-01-03 18:50:15 +08003379 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003380 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003381 break;
3382 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003383 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003384 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003385 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003386
3387 if (isLegacyLockdownNai(nai)
3388 && (underlying == null || underlying.size() != 1)) {
3389 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3390 + " must have exactly one underlying network: " + underlying);
3391 }
3392
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003393 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3394 nai.declaredUnderlyingNetworks = (underlying != null)
3395 ? underlying.toArray(new Network[0]) : null;
3396
3397 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3398 if (DBG) {
3399 log(nai.toShortString() + " changed underlying networks to "
3400 + Arrays.toString(nai.declaredUnderlyingNetworks));
3401 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003402 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003403 notifyIfacesChangedForNetworkStats();
3404 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003405 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003406 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003407 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3408 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3409 nai.teardownDelayMs = msg.arg1;
3410 } else {
3411 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3412 }
Chalard Jean550b5212021-03-05 23:07:53 +09003413 break;
3414 }
3415 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3416 nai.setLingerDuration((int) arg.second);
3417 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003418 }
Tyler Wear72388212021-09-09 14:49:02 -07003419 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3420 DscpPolicy policy = (DscpPolicy) arg.second;
3421 if (mDscpPolicyTracker != null) {
3422 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3423 }
3424 break;
3425 }
3426 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3427 if (mDscpPolicyTracker != null) {
3428 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3429 }
3430 break;
3431 }
3432 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3433 if (mDscpPolicyTracker != null) {
3434 mDscpPolicyTracker.removeAllDscpPolicies(nai);
3435 }
3436 break;
3437 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003438 }
3439 }
3440
3441 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
3442 switch (msg.what) {
3443 default:
3444 return false;
lucasline117e2e2019-10-22 18:27:33 +08003445 case EVENT_PROBE_STATUS_CHANGED: {
3446 final Integer netId = (Integer) msg.obj;
3447 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3448 if (nai == null) {
3449 break;
3450 }
3451 final boolean probePrivateDnsCompleted =
3452 ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
3453 final boolean privateDnsBroken =
3454 ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
3455 if (probePrivateDnsCompleted) {
3456 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3457 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003458 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003459 }
3460 // Only show the notification when the private DNS is broken and the
3461 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003462 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003463 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3464 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003465 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003466 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3467 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3468 // private DNS is broken, it means this network is being reevaluated.
3469 // Either probing private DNS is not necessary any more or it hasn't been
3470 // done yet. In either case, the networkCapabilities should be updated to
3471 // reflect the new status.
3472 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003473 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003474 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003475 }
3476 break;
3477 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003478 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003479 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3480
3481 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(results.mNetId);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003482 if (nai == null) break;
3483
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003484 handleNetworkTested(nai, results.mTestResult,
3485 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003486 break;
3487 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003488 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09003489 final int netId = msg.arg2;
Hugo Benichif4210292017-04-21 15:07:12 +09003490 final boolean visible = toBool(msg.arg1);
Erik Kline9a62f012018-03-21 07:18:33 -07003491 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Ondada1452016-10-11 15:10:46 -07003492 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04003493 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3494 nai.lastCaptivePortalDetected = visible;
3495 nai.everCaptivePortalDetected |= visible;
Calvin Ondada1452016-10-11 15:10:46 -07003496 if (nai.lastCaptivePortalDetected &&
paulhu56e09df2021-03-17 20:30:33 +08003497 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3498 == getCaptivePortalMode()) {
Chalard Jean49707572019-12-10 21:07:02 +09003499 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003500 nai.onPreventAutomaticReconnect();
Calvin Ondada1452016-10-11 15:10:46 -07003501 teardownUnneededNetwork(nai);
3502 break;
3503 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003504 updateCapabilitiesForNetwork(nai);
Paul Jensen53f08952015-06-16 14:27:36 -04003505 }
3506 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003507 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003508 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003509 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3510 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003511 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003512 if (nai == null) {
3513 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3514 break;
3515 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003516 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003517 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003518 (PendingIntent) msg.obj,
3519 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003520 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003521 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003522 break;
3523 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003524 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline9a62f012018-03-21 07:18:33 -07003525 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003526 if (nai == null) break;
3527
Erik Kline9a62f012018-03-21 07:18:33 -07003528 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003529 break;
3530 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003531 case EVENT_CAPPORT_DATA_CHANGED: {
3532 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3533 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003534 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003535 break;
3536 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003537 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003538 return true;
3539 }
3540
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003541 private void handleNetworkTested(
3542 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
3543 final boolean wasPartial = nai.partialConnectivity;
3544 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3545 final boolean partialConnectivityChanged =
3546 (wasPartial != nai.partialConnectivity);
3547
3548 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3549 final boolean wasValidated = nai.lastValidated;
Chalard Jean5b409c72021-02-04 13:12:59 +09003550 final boolean wasDefault = isDefaultNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003551
3552 if (DBG) {
3553 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3554 ? " with redirect to " + redirectUrl
3555 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003556 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003557 }
3558 if (valid != nai.lastValidated) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003559 final int oldScore = nai.getCurrentScore();
3560 nai.lastValidated = valid;
3561 nai.everValidated |= valid;
3562 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003563 if (valid) {
3564 handleFreshlyValidatedNetwork(nai);
3565 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3566 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003567 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003568 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003569 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003570 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003571 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003572 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003573 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003574 NotificationType.PRIVATE_DNS_BROKEN);
3575 // If network becomes valid, the hasShownBroken should be reset for
3576 // that network so that the notification will be fired when the private
3577 // DNS is broken again.
3578 nai.networkAgentConfig.hasShownBroken = false;
3579 }
3580 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003581 updateCapabilitiesForNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003582 }
3583 updateInetCondition(nai);
3584 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003585 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003586 nai.onValidationStatusChanged(
3587 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3588 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003589
3590 // If NetworkMonitor detects partial connectivity before
3591 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3592 // immediately. Re-notify partial connectivity silently if no internet
3593 // notification already there.
3594 if (!wasPartial && nai.partialConnectivity) {
3595 // Remove delayed message if there is a pending message.
3596 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3597 handlePromptUnvalidated(nai.network);
3598 }
3599
3600 if (wasValidated && !nai.lastValidated) {
3601 handleNetworkUnvalidated(nai);
3602 }
3603 }
3604
Calvin Ondada1452016-10-11 15:10:46 -07003605 private int getCaptivePortalMode() {
3606 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08003607 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3608 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07003609 }
3610
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003611 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3612 switch (msg.what) {
3613 default:
3614 return false;
3615 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3616 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3617 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3618 handleLingerComplete(nai);
3619 }
3620 break;
3621 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003622 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3623 handleNetworkAgentRegistered(msg);
3624 break;
3625 }
3626 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3627 handleNetworkAgentDisconnected(msg);
3628 break;
3629 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003630 }
3631 return true;
3632 }
3633
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003634 @Override
3635 public void handleMessage(Message msg) {
lifraf3a3492021-03-10 13:58:14 +08003636 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09003637 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003638 maybeHandleNetworkAgentMessage(msg);
3639 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003640 }
3641 }
3642
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003643 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09003644 private final int mNetId;
3645 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003646
3647 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003648 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003649 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003650 }
3651
3652 @Override
3653 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3654 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09003655 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003656 }
3657
3658 @Override
3659 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003660 // Legacy version of notifyNetworkTestedWithExtras.
3661 // Would only be called if the system has a NetworkStack module older than the
3662 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08003663 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003664 }
3665
3666 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003667 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09003668 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3669 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003670 final Message msg = mTrackerHandler.obtainMessage(
3671 EVENT_NETWORK_TESTED,
3672 new NetworkTestedResults(
3673 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003674 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003675
3676 // Invoke ConnectivityReport generation for this Network test event.
3677 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3678 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003679
Cody Kestingf1120be2020-08-03 18:01:40 -07003680 // NetworkMonitor reports the network validation result as a bitmask while
3681 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
3682 // logical value for ConnectivityDiagnostics.
3683 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
3684 p.result);
3685
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003686 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07003687 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003688 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3689 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3690
Aaron Huang959d3642021-01-21 15:47:41 +08003691 ConnectivityReportEvent reportEvent =
3692 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3693 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
3694 ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003695 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003696 }
3697
3698 @Override
3699 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3700 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3701 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09003702 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003703 }
3704
3705 @Override
lucasline117e2e2019-10-22 18:27:33 +08003706 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3707 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3708 EVENT_PROBE_STATUS_CHANGED,
3709 probesCompleted, probesSucceeded, new Integer(mNetId)));
3710 }
3711
3712 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003713 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3714 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3715 EVENT_CAPPORT_DATA_CHANGED,
3716 0, mNetId, data));
3717 }
3718
3719 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003720 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003721 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003722 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003723
3724 final PendingIntent pendingIntent;
3725 // Only the system server can register notifications with package "android"
3726 final long token = Binder.clearCallingIdentity();
3727 try {
paulhu7746e4e2020-06-09 19:07:03 +08003728 pendingIntent = PendingIntent.getBroadcast(
3729 mContext,
3730 0 /* requestCode */,
3731 intent,
3732 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003733 } finally {
3734 Binder.restoreCallingIdentity(token);
3735 }
3736 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3737 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09003738 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003739 }
3740
3741 @Override
3742 public void hideProvisioningNotification() {
3743 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09003744 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003745 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003746
3747 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003748 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003749 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08003750 }
3751
3752 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003753 public int getInterfaceVersion() {
3754 return this.VERSION;
3755 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09003756
3757 @Override
3758 public String getInterfaceHash() {
3759 return this.HASH;
3760 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003761 }
3762
Cody Kestingf1120be2020-08-03 18:01:40 -07003763 /**
3764 * Converts the given NetworkMonitor-specific validation result bitmask to a
3765 * ConnectivityDiagnostics-specific validation result int.
3766 */
3767 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
3768 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
3769 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
3770 }
3771 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
3772 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
3773 }
3774 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
3775 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
3776 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
3777 }
3778
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003779 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07003780 log("Data stall detected with methods: " + p.detectionMethod);
3781
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003782 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07003783 int detectionMethod = 0;
3784 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
3785 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
3786 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
3787 }
3788 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
3789 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
3790 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
3791 p.tcpMetricsCollectionPeriodMillis);
3792 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003793 }
3794
Cody Kestingf53a0752020-04-15 12:33:28 -07003795 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003796 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08003797 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07003798
3799 // NetworkStateTrackerHandler currently doesn't take any actions based on data
3800 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
3801 // the cost of going through two handlers.
3802 mConnectivityDiagnosticsHandler.sendMessage(msg);
3803 }
3804
Cody Kestingb37958e2020-05-15 10:36:01 -07003805 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
3806 return (p.detectionMethod & detectionMethod) != 0;
3807 }
3808
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003809 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
3810 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07003811 }
3812
Erik Klinea73af002018-06-26 18:53:43 +09003813 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
3814 if (nai == null) return;
3815 // If the Private DNS mode is opportunistic, reprogram the DNS servers
3816 // in order to restart a validation pass from within netd.
3817 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3818 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003819 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09003820 }
3821 }
3822
Erik Kline31b4a9e2018-01-11 21:07:29 +09003823 private void handlePrivateDnsSettingsChanged() {
3824 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3825
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003826 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07003827 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003828 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05003829 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3830 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09003831 }
3832 }
3833
Erik Kline9a62f012018-03-21 07:18:33 -07003834 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
3835 // Private DNS only ever applies to networks that might provide
3836 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003837 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09003838
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003839 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07003840 // schedule DNS resolutions. If a DNS resolution is required the
3841 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09003842 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07003843
3844 // With Private DNS bypass support, we can proceed to update the
3845 // Private DNS config immediately, even if we're in strict mode
3846 // and have not yet resolved the provider name into a set of IPs.
3847 updatePrivateDns(nai, cfg);
3848 }
3849
3850 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
3851 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003852 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09003853 }
3854
dalyk1720e542018-03-05 12:42:22 -05003855 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
3856 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
3857 if (nai == null) {
3858 return;
3859 }
3860 mDnsManager.updatePrivateDnsValidation(update);
3861 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3862 }
3863
paulhu7c0a2e62021-01-08 00:51:49 +08003864 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003865 int prefixLength) {
3866 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
3867 if (nai == null) return;
3868
paulhu7c0a2e62021-01-08 00:51:49 +08003869 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
3870 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003871
3872 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08003873 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003874 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003875 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003876 prefixLength);
3877 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003878 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003879 return;
3880 }
3881 }
3882
Lorenzo Colittid523d142020-04-01 20:16:30 +09003883 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003884 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3885 }
3886
Hai Shalome58bdc62021-01-11 18:45:34 -08003887 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003888 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08003889 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003890 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
3891 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3892 }
3893
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003894 /**
junyulai2b6f0c22021-02-03 20:15:30 +08003895 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003896 * @param nai the agent info to update
3897 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08003898 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003899 */
junyulai2b6f0c22021-02-03 20:15:30 +08003900 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
3901 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
3902 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003903 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08003904 // one lingered request, set inactive.
3905 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08003906 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08003907 if (DBG) log("Unsetting inactive " + nai.toShortString());
3908 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003909 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08003910 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003911 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08003912 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
3913 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003914 }
junyulai2b6f0c22021-02-03 20:15:30 +08003915 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003916 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003917 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003918 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003919 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05003920 }
3921
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003922 private void handleNetworkAgentRegistered(Message msg) {
3923 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3924 if (!mNetworkAgentInfos.contains(nai)) {
3925 return;
3926 }
3927
3928 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
3929 if (VDBG) log("NetworkAgent registered");
3930 } else {
3931 loge("Error connecting NetworkAgent");
3932 mNetworkAgentInfos.remove(nai);
3933 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09003934 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003935 synchronized (mNetworkForNetId) {
3936 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003937 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003938 mNetIdManager.releaseNetId(nai.network.getNetId());
3939 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09003940 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003941 }
3942 }
3943 }
Paul Jensend5f53392014-11-25 15:26:53 -05003944
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003945 private void handleNetworkAgentDisconnected(Message msg) {
3946 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07003947 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003948 }
3949
Chalard Jeand9fffc32018-05-11 20:19:20 +09003950 // Destroys a network, remove references to it from the internal state managed by
3951 // ConnectivityService, free its interfaces and clean up.
3952 // Must be called on the Handler thread.
3953 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09003954 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07003955
3956 if (!mNetworkAgentInfos.contains(nai)) return;
3957
Chalard Jeand9fffc32018-05-11 20:19:20 +09003958 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09003959 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003960 }
lucaslinb25c9a62019-02-12 15:30:13 +08003961 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003962 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003963 // A network agent has disconnected.
3964 // TODO - if we move the logic to the network agent (have them disconnect
3965 // because they lost all their requests or because their score isn't good)
3966 // then they would disconnect organically, report their new state and then
3967 // disconnect the channel.
3968 if (nai.networkInfo.isConnected()) {
3969 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3970 null, null);
3971 }
Chalard Jean5b409c72021-02-04 13:12:59 +09003972 final boolean wasDefault = isDefaultNetwork(nai);
3973 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09003974 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09003975 }
3976 notifyIfacesChangedForNetworkStats();
3977 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
3978 // by other networks that are already connected. Perhaps that can be done by
3979 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
3980 // of rematchAllNetworksAndRequests
3981 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08003982 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07003983
3984 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09003985 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
3986 // Disable wakeup packet monitoring for each interface.
3987 wakeupModifyInterface(iface, nai.networkCapabilities, false);
3988 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09003989 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003990 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09003991 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09003992 synchronized (mNetworkForNetId) {
3993 // Remove the NetworkAgent, but don't mark the netId as
3994 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003995 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003996 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09003997 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09003998 // Remove all previously satisfied requests.
3999 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004000 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004001 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004002 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004003 if (currentNetwork != null
4004 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004005 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004006 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4007 // rematch not to keep disconnected agents instead of setting it here ; this
4008 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004009 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004010 for (final NetworkOfferInfo noi : mNetworkOffers) {
4011 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004012 }
James Mattise3ef1912020-12-20 11:09:58 -08004013
Chalard Jean5b409c72021-02-04 13:12:59 +09004014 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004015 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004016 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004017 // network, because while incorrect this is the closest to the old (also
4018 // incorrect) behavior.
4019 mNetworkActivityTracker.updateDataActivityTracking(
4020 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004021 ensureNetworkTransitionWakelock(nai.toShortString());
4022 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004023 }
4024 }
junyulai2b6f0c22021-02-03 20:15:30 +08004025 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004026 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004027 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004028 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004029 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004030 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004031 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004032
4033 // Immediate teardown.
4034 if (nai.teardownDelayMs == 0) {
4035 destroyNetwork(nai);
4036 return;
4037 }
4038
4039 // Delayed teardown.
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304040 if (nai.created) {
4041 try {
4042 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4043 } catch (RemoteException e) {
4044 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4045 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004046 }
4047 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4048 }
4049
4050 private void destroyNetwork(NetworkAgentInfo nai) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004051 if (nai.created) {
4052 // Tell netd to clean up the configuration for this network
4053 // (routing rules, DNS, etc).
4054 // This may be slow as it requires a lot of netd shelling out to ip and
4055 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004056 // after we've rematched networks with requests (which might change the default
4057 // network or service a new request from an app), so network traffic isn't interrupted
4058 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004059 destroyNativeNetwork(nai);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004060 mDnsManager.removeNetwork(nai.network);
4061 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004062 mNetIdManager.releaseNetId(nai.network.getNetId());
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004063 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004064 }
4065
Ken Chen6df7a902021-04-09 15:08:42 +08004066 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004067 try {
4068 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004069 final NativeNetworkConfig config;
4070 if (nai.isVPN()) {
4071 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004072 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004073 return false;
4074 }
4075 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4076 INetd.PERMISSION_NONE,
4077 (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass),
Chiachang Wang9164c102022-01-13 10:54:32 +08004078 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004079 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004080 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
4081 getNetworkPermission(nai.networkCapabilities), /*secure=*/ false,
Chiachang Wangbf6b8792022-01-11 10:48:07 +08004082 VpnManager.TYPE_VPN_NONE, /*excludeLocalRoutes=*/ false);
Luke Huangfdd11f82019-04-09 18:41:49 +08004083 }
Ken Chen6df7a902021-04-09 15:08:42 +08004084 mNetd.networkCreate(config);
4085 mDnsResolver.createNetworkCache(nai.network.getNetId());
4086 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4087 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004088 return true;
4089 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004090 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004091 return false;
4092 }
4093 }
4094
Ken Chen6df7a902021-04-09 15:08:42 +08004095 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004096 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004097 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004098 } catch (RemoteException | ServiceSpecificException e) {
4099 loge("Exception destroying network(networkDestroy): " + e);
4100 }
4101 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004102 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004103 } catch (RemoteException | ServiceSpecificException e) {
4104 loge("Exception destroying network: " + e);
4105 }
4106 }
4107
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004108 // If this method proves to be too slow then we can maintain a separate
4109 // pendingIntent => NetworkRequestInfo map.
4110 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4111 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004112 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4113 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4114 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004115 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004116 return entry.getValue();
4117 }
4118 }
4119 return null;
4120 }
4121
Chalard Jean524f0b12021-10-25 21:11:56 +09004122 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4123 if (SdkLevel.isAtLeastT()) {
4124 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4125 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4126 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4127 // bug is fixed.
4128 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004129 throw new IllegalStateException("This NRI is already registered. New : " + nri
4130 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004131 }
4132 }
4133 }
4134 }
4135
James Mattisf7027322020-12-13 16:28:14 -08004136 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004137 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004138 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4139 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4140 final NetworkRequestInfo existingRequest =
4141 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004142 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004143 if (DBG) {
4144 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4145 + nri.mRequests.get(0) + " because their intents matched.");
4146 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004147 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004148 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004149 }
Erik Kline05f2b402015-04-30 12:58:40 +09004150 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004151 }
4152
James Mattisf7027322020-12-13 16:28:14 -08004153 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004154 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004155 }
4156
James Mattis3ce3d3c2021-02-09 18:18:28 -08004157 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004158 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004159 for (final NetworkRequestInfo nri : nris) {
4160 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004161 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004162 for (final NetworkRequest req : nri.mRequests) {
4163 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004164 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004165 if (req.isListen()) {
4166 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4167 if (req.networkCapabilities.hasSignalStrength()
4168 && network.satisfiesImmutableCapabilitiesOf(req)) {
4169 updateSignalStrengthThresholds(network, "REGISTER", req);
4170 }
James Mattisf7027322020-12-13 16:28:14 -08004171 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004172 }
4173 }
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004174 // If this NRI has a satisfier already, it is replacing an older request that
4175 // has been removed. Track it.
4176 final NetworkRequest activeRequest = nri.getActiveRequest();
4177 if (null != activeRequest) {
4178 // If there is an active request, then for sure there is a satisfier.
4179 nri.getSatisfier().addRequest(activeRequest);
4180 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004181 }
James Mattisf7027322020-12-13 16:28:14 -08004182
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004183 if (mFlags.noRematchAllRequestsOnRegister()) {
4184 rematchNetworksAndRequests(nris);
4185 } else {
4186 rematchAllNetworksAndRequests();
4187 }
James Mattis45d81842021-01-10 14:24:24 -08004188
Chalard Jean0354d8c2021-01-12 10:58:56 +09004189 // Requests that have not been matched to a network will not have been sent to the
4190 // providers, because the old satisfier and the new satisfier are the same (null in this
4191 // case). Send these requests to the providers.
4192 for (final NetworkRequestInfo nri : nris) {
4193 for (final NetworkOfferInfo noi : mNetworkOffers) {
4194 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004195 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004196 }
4197 }
4198
James Mattisf7027322020-12-13 16:28:14 -08004199 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4200 final int callingUid) {
4201 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004202 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004203 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4204 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4205 handleReleaseNetworkRequest(
4206 nri.mRequests.get(0),
4207 callingUid,
4208 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004209 }
4210 }
4211
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004212 // Determines whether the network is the best (or could become the best, if it validated), for
4213 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4214 // on the value of reason:
4215 //
4216 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4217 // then it should be torn down.
4218 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4219 // then it should be lingered.
4220 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004221 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004222
4223 if (!nai.everConnected || nai.isVPN() || nai.isInactive()
4224 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4225 return false;
4226 }
4227
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004228 final int numRequests;
4229 switch (reason) {
4230 case TEARDOWN:
4231 numRequests = nai.numRequestNetworkRequests();
4232 break;
4233 case LINGER:
4234 numRequests = nai.numForegroundNetworkRequests();
4235 break;
4236 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004237 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004238 return true;
4239 }
4240
Chalard Jean947acd42021-03-08 22:29:27 +09004241 if (numRequests > 0) return false;
4242
Paul Jensende49eb12015-06-25 15:30:08 -04004243 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004244 if (reason == UnneededFor.LINGER
4245 && !nri.isMultilayerRequest()
4246 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004247 // Background requests don't affect lingering.
4248 continue;
4249 }
4250
James Mattis3d229892020-11-16 16:46:28 -08004251 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004252 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004253 }
4254 }
Paul Jensende49eb12015-06-25 15:30:08 -04004255 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004256 }
4257
James Mattis3d229892020-11-16 16:46:28 -08004258 private boolean isNetworkPotentialSatisfier(
4259 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4260 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004261 // request, return immediately. For multilayer requests, check to see if any of the
4262 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004263 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4264 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004265 return false;
4266 }
4267 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004268 // This multilayer listen request is satisfied therefore no further requests need to be
4269 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004270 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004271 return false;
4272 }
James Mattis3d229892020-11-16 16:46:28 -08004273 // As non-multilayer listen requests have already returned, the below would only happen
4274 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004275 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004276 continue;
4277 }
4278 // If this Network is already the highest scoring Network for a request, or if
4279 // there is hope for it to become one if it validated, then it is needed.
4280 if (candidate.satisfies(req)) {
4281 // As soon as a network is found that satisfies a request, return. Specifically for
4282 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4283 // is important so as to not evaluate lower priority requests further in
4284 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004285 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4286 ? nri.getSatisfier() : null;
4287 // Note that this catches two important cases:
4288 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4289 // is currently satisfying the request. This is desirable when
4290 // cellular ends up validating but WiFi does not.
4291 // 2. Unvalidated WiFi will not be reaped when validated cellular
4292 // is currently satisfying the request. This is desirable when
4293 // WiFi ends up validating and out scoring cellular.
4294 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004295 }
4296 }
4297
4298 return false;
4299 }
4300
Erik Kline0c04b742016-07-07 16:50:58 +09004301 private NetworkRequestInfo getNriForAppRequest(
4302 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004303 // Looking up the app passed param request in mRequests isn't possible since it may return
4304 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4305 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004306 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4307 // to avoid potential race conditions when validating a package->uid mapping when sending
4308 // the callback on the very low-chance that an application shuts down prior to the callback
4309 // being sent.
4310 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4311 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004312
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004313 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004314 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004315 log(String.format("UID %d attempted to %s for unowned request %s",
4316 callingUid, requestedOperation, nri));
4317 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004318 }
Erik Kline0c04b742016-07-07 16:50:58 +09004319 }
4320
4321 return nri;
4322 }
4323
James Mattisf7027322020-12-13 16:28:14 -08004324 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4325 final String callingMethod) {
4326 if (nri.isMultilayerRequest()) {
4327 throw new IllegalStateException(
4328 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004329 }
4330 }
4331
James Mattisf7027322020-12-13 16:28:14 -08004332 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004333 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004334 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4335 // single NetworkRequest and thus does not apply to multilayer requests.
4336 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4337 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004338 return;
4339 }
James Mattis2516da32021-01-31 17:06:19 -08004340 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004341 return;
4342 }
James Mattisf7027322020-12-13 16:28:14 -08004343 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4344 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004345 }
4346 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004347 callCallbackForRequest(
4348 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004349 }
4350
James Mattisf7027322020-12-13 16:28:14 -08004351 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4352 final int callingUid,
4353 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004354 final NetworkRequestInfo nri =
4355 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4356 if (nri == null) {
4357 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004358 }
James Mattisf7027322020-12-13 16:28:14 -08004359 if (VDBG || (DBG && request.isRequest())) {
4360 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004361 }
4362 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004363 if (callOnUnavailable) {
4364 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4365 }
Erik Kline155a59a2015-11-25 12:49:38 +09004366 }
Erik Kline0c04b742016-07-07 16:50:58 +09004367
James Mattisa076c532020-12-02 14:12:41 -08004368 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004369 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004370 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004371 if (null == mNetworkRequests.remove(req)) {
4372 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4373 continue;
4374 }
James Mattisa076c532020-12-02 14:12:41 -08004375 if (req.isListen()) {
4376 removeListenRequestFromNetworks(req);
4377 }
4378 }
James Mattis8f036802021-06-20 16:26:01 -07004379 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004380 if (mDefaultNetworkRequests.remove(nri)) {
4381 // If this request was one of the defaults, then the UID rules need to be updated
4382 // WARNING : if the app(s) for which this network request is the default are doing
4383 // traffic, this will kill their connected sockets, even if an equivalent request
4384 // is going to be reinstated right away ; unconnected traffic will go on the default
4385 // until the new default is set, which will happen very soon.
4386 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4387 // remove ranges for those requests that won't have a replacement
4388 final NetworkAgentInfo satisfier = nri.getSatisfier();
4389 if (null != satisfier) {
4390 try {
paulhu0e79d952021-06-09 16:11:35 +08004391 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4392 satisfier.network.getNetId(),
4393 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004394 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004395 } catch (RemoteException e) {
4396 loge("Exception setting network preference default network", e);
4397 }
4398 }
4399 }
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09004400 nri.decrementRequestCount();
Erik Kline0c04b742016-07-07 16:50:58 +09004401 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004402 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004403
4404 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004405 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004406 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004407 }
4408 }
4409
Chalard Jean0354d8c2021-01-12 10:58:56 +09004410 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4411 // needed for this offer.
4412 for (final NetworkOfferInfo noi : mNetworkOffers) {
4413 for (final NetworkRequest req : nri.mRequests) {
4414 if (req.isRequest() && noi.offer.neededFor(req)) {
4415 noi.offer.onNetworkUnneeded(req);
4416 }
4417 }
4418 }
James Mattisa076c532020-12-02 14:12:41 -08004419 }
4420
James Mattis3ce3d3c2021-02-09 18:18:28 -08004421 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4422 for (final NetworkRequestInfo nri : nris) {
4423 if (mDefaultRequest == nri) {
4424 // Make sure we never remove the default request.
4425 continue;
4426 }
4427 handleRemoveNetworkRequest(nri);
4428 }
4429 }
4430
James Mattisa076c532020-12-02 14:12:41 -08004431 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4432 // listens don't have a singular affected Network. Check all networks to see
4433 // if this listen request applies and remove it.
4434 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4435 nai.removeRequest(req.requestId);
4436 if (req.networkCapabilities.hasSignalStrength()
4437 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4438 updateSignalStrengthThresholds(nai, "RELEASE", req);
4439 }
4440 }
4441 }
4442
4443 /**
4444 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4445 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4446 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4447 */
4448 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4449 boolean wasKept = false;
4450 final NetworkAgentInfo nai = nri.getSatisfier();
4451 if (nai != null) {
4452 final int requestLegacyType = nri.getActiveRequest().legacyType;
4453 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4454 nai.removeRequest(nri.getActiveRequest().requestId);
4455 if (VDBG || DDBG) {
4456 log(" Removing from current network " + nai.toShortString()
4457 + ", leaving " + nai.numNetworkRequests() + " requests.");
4458 }
4459 // If there are still lingered requests on this network, don't tear it down,
4460 // but resume lingering instead.
4461 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004462 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004463 notifyNetworkLosing(nai, now);
4464 }
4465 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4466 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4467 teardownUnneededNetwork(nai);
4468 } else {
4469 wasKept = true;
4470 }
James Mattisa076c532020-12-02 14:12:41 -08004471 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4472 // Went from foreground to background.
4473 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004474 }
4475
Erik Kline0c04b742016-07-07 16:50:58 +09004476 // Maintain the illusion. When this request arrived, we might have pretended
4477 // that a network connected to serve it, even though the network was already
4478 // connected. Now that this request has gone away, we might have to pretend
4479 // that the network disconnected. LegacyTypeTracker will generate that
4480 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004481 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004482 boolean doRemove = true;
4483 if (wasKept) {
4484 // check if any of the remaining requests for this network are for the
4485 // same legacy type - if so, don't remove the nai
4486 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4487 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004488 if (otherRequest.legacyType == requestLegacyType
4489 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004490 if (DBG) log(" still have other legacy request - leaving");
4491 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004492 }
4493 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004494 }
4495
Erik Kline0c04b742016-07-07 16:50:58 +09004496 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004497 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004498 }
4499 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004500 }
4501 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004502
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004503 private PerUidCounter getRequestCounter(NetworkRequestInfo nri) {
4504 return checkAnyPermissionOf(
4505 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4506 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4507 }
4508
Lorenzo Colittid6459092016-07-04 12:55:44 +09004509 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004510 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004511 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004512 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004513 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004514 }
4515
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004516 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004517 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4518 enforceNetworkStackSettingsOrSetup();
4519 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4520 encodeBool(accept), encodeBool(always), network));
4521 }
4522
4523 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004524 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004525 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004526 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4527 }
4528
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004529 @Override
4530 public void setTestAllowBadWifiUntil(long timeMs) {
4531 enforceSettingsPermission();
4532 if (!Build.isDebuggable()) {
4533 throw new IllegalStateException("Does not support in non-debuggable build");
4534 }
4535
4536 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4537 throw new IllegalArgumentException("It should not exceed "
4538 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4539 }
4540
4541 mHandler.sendMessage(
4542 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
4543 }
4544
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004545 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4546 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4547 " accept=" + accept + " always=" + always);
4548
4549 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4550 if (nai == null) {
4551 // Nothing to do.
4552 return;
4553 }
4554
4555 if (nai.everValidated) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004556 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004557 return;
4558 }
4559
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004560 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08004561 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004562 }
4563
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004564 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4565 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004566 // If network becomes partial connectivity and user already accepted to use this
4567 // network, we should respect the user's option and don't need to popup the
4568 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004569 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004570 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004571 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004572 }
4573
4574 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004575 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004576 }
4577
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004578 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04004579 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004580 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09004581 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04004582 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004583 }
4584
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004585 }
4586
lucaslin2240ef62019-03-12 13:08:03 +08004587 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4588 boolean always) {
4589 if (DBG) {
4590 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4591 + " always=" + always);
4592 }
4593
4594 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4595 if (nai == null) {
4596 // Nothing to do.
4597 return;
4598 }
4599
4600 if (nai.lastValidated) {
4601 // The network validated while the dialog box was up. Take no action.
4602 return;
4603 }
4604
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004605 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4606 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004607 }
4608
4609 // TODO: Use the current design or save the user choice into IpMemoryStore.
4610 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004611 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08004612 }
4613
4614 if (!accept) {
4615 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004616 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08004617 // Tear down the network.
4618 teardownUnneededNetwork(nai);
4619 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08004620 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4621 // result in a partial connectivity result which will be processed by
4622 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08004623 //
4624 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4625 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004626 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08004627 }
4628 }
4629
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004630 private void handleSetAvoidUnvalidated(Network network) {
4631 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4632 if (nai == null || nai.lastValidated) {
4633 // Nothing to do. The network either disconnected or revalidated.
4634 return;
4635 }
4636 if (!nai.avoidUnvalidated) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004637 nai.avoidUnvalidated = true;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004638 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004639 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004640 }
4641 }
4642
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004643 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09004644 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004645 mHandler.sendMessageDelayed(
4646 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4647 PROMPT_UNVALIDATED_DELAY_MS);
4648 }
4649
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004650 @Override
4651 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08004652 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004653 mHandler.post(() -> {
4654 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4655 if (nai == null) return;
4656 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004657 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004658 });
4659 }
4660
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004661 /**
4662 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4663 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004664 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004665 * @param appExtras Bundle to use as intent extras for the captive portal application.
4666 * Must be treated as opaque to avoid preventing the captive portal app to
4667 * update its arguments.
4668 */
4669 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004670 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08004671 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4672 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004673
4674 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4675 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004676 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4677 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004678 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4679
lucaslin75ff7022020-12-17 04:14:35 +08004680 final long token = Binder.clearCallingIdentity();
4681 try {
4682 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4683 } finally {
4684 Binder.restoreCallingIdentity(token);
4685 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004686 }
4687
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004688 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4689 private final Network mNetwork;
4690
4691 private CaptivePortalImpl(Network network) {
4692 mNetwork = network;
4693 }
4694
4695 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004696 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004697 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
4698 enforceSettingsPermission();
4699 }
4700
Chiachang Wang938bfba2020-01-09 13:50:55 +08004701 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004702 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004703 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004704 }
4705
4706 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08004707 public void appRequest(final int request) {
4708 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4709 if (nm == null) return;
4710
4711 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08004712 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09004713 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08004714 }
4715 }
4716
4717 @Nullable
4718 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
4719 // getNetworkAgentInfoForNetwork is thread-safe
4720 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4721 if (nai == null) return null;
4722
4723 // nai.networkMonitor() is thread-safe
4724 return nai.networkMonitor();
4725 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004726 }
4727
Hugo Benichic9048bc2016-09-14 23:23:08 +00004728 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004729 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09004730 }
4731
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004732 /**
4733 * Return whether the device should maintain continuous, working connectivity by switching away
4734 * from WiFi networks having no connectivity.
4735 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
4736 */
4737 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004738 if (!checkNetworkStackPermission()) {
4739 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
4740 }
4741 return avoidBadWifi();
4742 }
4743
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004744 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09004745 ensureRunningOnConnectivityServiceThread();
4746 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004747 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09004748 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004749 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09004750 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
4751 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
4752 for (final NetworkOfferInfo noi : offersToUpdate) {
4753 updateOfferScore(noi.offer);
4754 }
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004755 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004756 }
4757
Erik Kline95ecfee2016-10-02 18:02:14 +09004758 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004759 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004760 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004761 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004762 if (!configRestrict) {
4763 pw.println("Bad Wi-Fi avoidance: unrestricted");
4764 return;
4765 }
4766
4767 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
4768 pw.increaseIndent();
4769 pw.println("Config restrict: " + configRestrict);
4770
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004771 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004772 String description;
4773 // Can't use a switch statement because strings are legal case labels, but null is not.
4774 if ("0".equals(value)) {
4775 description = "get stuck";
4776 } else if (value == null) {
4777 description = "prompt";
4778 } else if ("1".equals(value)) {
4779 description = "avoid";
4780 } else {
4781 description = value + " (?)";
4782 }
4783 pw.println("User setting: " + description);
4784 pw.println("Network overrides:");
4785 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09004786 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004787 if (nai.avoidUnvalidated) {
Chalard Jean49707572019-12-10 21:07:02 +09004788 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004789 }
4790 }
4791 pw.decreaseIndent();
4792 pw.decreaseIndent();
4793 }
4794
paulhu7746e4e2020-06-09 19:07:03 +08004795 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
4796 // unify the method.
4797 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
4798 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
4799 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
4800 return settingsComponent != null
4801 ? settingsComponent.getPackageName() : "com.android.settings";
4802 }
4803
lucaslinb1e8e382019-01-24 15:55:30 +08004804 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004805 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004806 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004807 switch (type) {
4808 case NO_INTERNET:
4809 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004810 // High priority because it is only displayed for explicitly selected networks.
4811 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004812 break;
lucasline117e2e2019-10-22 18:27:33 +08004813 case PRIVATE_DNS_BROKEN:
4814 action = Settings.ACTION_WIRELESS_SETTINGS;
4815 // High priority because we should let user know why there is no internet.
4816 highPriority = true;
4817 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004818 case LOST_INTERNET:
4819 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004820 // High priority because it could help the user avoid unexpected data usage.
4821 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004822 break;
lucaslin2240ef62019-03-12 13:08:03 +08004823 case PARTIAL_CONNECTIVITY:
4824 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004825 // Don't bother the user with a high-priority notification if the network was not
4826 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004827 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08004828 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004829 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004830 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004831 return;
4832 }
4833
4834 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08004835 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08004836 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08004837 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08004838 // Some OEMs have their own Settings package. Thus, need to get the current using
4839 // Settings package name instead of just use default name "com.android.settings".
4840 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
4841 intent.setClassName(settingsPkgName,
4842 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08004843 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004844
paulhu2af50222020-10-11 22:52:27 +08004845 PendingIntent pendingIntent = PendingIntent.getActivity(
4846 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08004847 0 /* requestCode */,
4848 intent,
paulhu2af50222020-10-11 22:52:27 +08004849 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004850
Serik Beketayevec8ad212020-12-07 22:43:07 -08004851 mNotifier.showNotification(
4852 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004853 }
4854
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004855 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
4856 // Don't prompt if the network is validated, and don't prompt on captive portals
4857 // because we're already prompting the user to sign in.
4858 if (nai.everValidated || nai.everCaptivePortalDetected) {
4859 return false;
4860 }
4861
4862 // If a network has partial connectivity, always prompt unless the user has already accepted
4863 // partial connectivity and selected don't ask again. This ensures that if the device
4864 // automatically connects to a network that has partial Internet access, the user will
4865 // always be able to use it, either because they've already chosen "don't ask again" or
4866 // because we have prompt them.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004867 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004868 return true;
4869 }
4870
4871 // If a network has no Internet access, only prompt if the network was explicitly selected
4872 // and if the user has not already told us to use the network regardless of whether it
4873 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004874 if (nai.networkAgentConfig.explicitlySelected
4875 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004876 return true;
4877 }
4878
4879 return false;
4880 }
4881
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004882 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09004883 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004884 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4885
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004886 if (nai == null || !shouldPromptUnvalidated(nai)) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004887 return;
4888 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09004889
4890 // Stop automatically reconnecting to this network in the future. Automatically connecting
4891 // to a network that provides no or limited connectivity is not useful, because the user
4892 // cannot use that network except through the notification shown by this method, and the
4893 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004894 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09004895
lucaslin2240ef62019-03-12 13:08:03 +08004896 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
4897 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
4898 // popup the notification immediately when the network is partial connectivity.
4899 if (nai.partialConnectivity) {
lucasline0118ab2019-03-21 11:59:22 +08004900 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08004901 } else {
4902 showNetworkNotification(nai, NotificationType.NO_INTERNET);
4903 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004904 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004905
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004906 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
4907 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09004908 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07004909
lucaslin2240ef62019-03-12 13:08:03 +08004910 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4911 return;
4912 }
4913
4914 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08004915 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004916 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004917 }
4918
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004919 @Override
4920 public int getMultipathPreference(Network network) {
4921 enforceAccessPermission();
4922
4923 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06004924 if (nai != null && nai.networkCapabilities
4925 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004926 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
4927 }
4928
Aaron Huang9a57acf2020-12-08 10:03:29 +08004929 final NetworkPolicyManager netPolicyManager =
4930 mContext.getSystemService(NetworkPolicyManager.class);
4931
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09004932 final long token = Binder.clearCallingIdentity();
4933 final int networkPreference;
4934 try {
4935 networkPreference = netPolicyManager.getMultipathPreference(network);
4936 } finally {
4937 Binder.restoreCallingIdentity(token);
4938 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08004939 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09004940 return networkPreference;
4941 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004942 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
4943 }
4944
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004945 @Override
4946 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09004947 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004948 }
4949
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004950 private class InternalHandler extends Handler {
4951 public InternalHandler(Looper looper) {
4952 super(looper);
4953 }
4954
4955 @Override
4956 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004957 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07004958 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004959 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09004960 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07004961 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004962 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004963 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09004964 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07004965 break;
4966 }
Jason Monka69f1b02013-10-10 14:02:51 -04004967 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08004968 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
4969 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04004970 break;
4971 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09004972 case EVENT_REGISTER_NETWORK_PROVIDER: {
4973 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07004974 break;
4975 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09004976 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
4977 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004978 break;
4979 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09004980 case EVENT_REGISTER_NETWORK_OFFER: {
4981 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
4982 break;
4983 }
4984 case EVENT_UNREGISTER_NETWORK_OFFER: {
4985 final NetworkOfferInfo offer =
4986 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
4987 if (null != offer) {
4988 handleUnregisterNetworkOffer(offer);
4989 }
4990 break;
4991 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004992 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004993 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
4994 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
4995 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004996 break;
4997 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004998 case EVENT_REGISTER_NETWORK_REQUEST:
4999 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005000 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005001 break;
5002 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005003 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5004 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005005 handleRegisterNetworkRequestWithIntent(msg);
5006 break;
5007 }
Erik Kline155a59a2015-11-25 12:49:38 +09005008 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5009 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5010 handleTimedOutNetworkRequest(nri);
5011 break;
5012 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005013 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5014 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5015 break;
5016 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005017 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005018 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5019 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005020 break;
5021 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005022 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005023 Network network = (Network) msg.obj;
5024 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005025 break;
5026 }
lucaslin2240ef62019-03-12 13:08:03 +08005027 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5028 Network network = (Network) msg.obj;
5029 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5030 toBool(msg.arg2));
5031 break;
5032 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005033 case EVENT_SET_AVOID_UNVALIDATED: {
5034 handleSetAvoidUnvalidated((Network) msg.obj);
5035 break;
5036 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005037 case EVENT_PROMPT_UNVALIDATED: {
5038 handlePromptUnvalidated((Network) msg.obj);
5039 break;
5040 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005041 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5042 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005043 break;
5044 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005045 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005046 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005047 mKeepaliveTracker.handleStartKeepalive(msg);
5048 break;
5049 }
5050 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005051 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005052 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5053 int slot = msg.arg1;
5054 int reason = msg.arg2;
5055 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
5056 break;
5057 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005058 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5059 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5060 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005061 break;
5062 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005063 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5064 handlePrivateDnsSettingsChanged();
5065 break;
dalyk1720e542018-03-05 12:42:22 -05005066 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5067 handlePrivateDnsValidationUpdate(
5068 (PrivateDnsValidationUpdate) msg.obj);
5069 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005070 case EVENT_UID_BLOCKED_REASON_CHANGED:
5071 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005072 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005073 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5074 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5075 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005076 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005077 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5078 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005079 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005080 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005081 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005082 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005083 final Pair<List<ProfileNetworkPreferenceList.Preference>,
5084 IOnCompleteListener> arg =
5085 (Pair<List<ProfileNetworkPreferenceList.Preference>,
5086 IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005087 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005088 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005089 }
lucaslin1193a5d2021-01-21 02:04:15 +08005090 case EVENT_REPORT_NETWORK_ACTIVITY:
5091 mNetworkActivityTracker.handleReportNetworkActivity();
5092 break;
paulhu51f77dc2021-06-07 02:34:20 +00005093 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5094 handleMobileDataPreferredUidsChanged();
5095 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005096 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5097 final long timeMs = ((Long) msg.obj).longValue();
5098 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5099 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005100 }
5101 }
5102 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005103
Lorenzo Colittid6459092016-07-04 12:55:44 +09005104 @Override
markchien5776f962019-12-16 20:15:20 +08005105 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005106 public int getLastTetherError(String iface) {
markchien5776f962019-12-16 20:15:20 +08005107 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5108 Context.TETHERING_SERVICE);
5109 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005110 }
5111
Lorenzo Colittid6459092016-07-04 12:55:44 +09005112 @Override
markchien5776f962019-12-16 20:15:20 +08005113 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005114 public String[] getTetherableIfaces() {
markchien5776f962019-12-16 20:15:20 +08005115 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5116 Context.TETHERING_SERVICE);
5117 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005118 }
5119
Lorenzo Colittid6459092016-07-04 12:55:44 +09005120 @Override
markchien5776f962019-12-16 20:15:20 +08005121 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005122 public String[] getTetheredIfaces() {
markchien5776f962019-12-16 20:15:20 +08005123 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5124 Context.TETHERING_SERVICE);
5125 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005126 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005127
markchien5776f962019-12-16 20:15:20 +08005128
Lorenzo Colittid6459092016-07-04 12:55:44 +09005129 @Override
markchien5776f962019-12-16 20:15:20 +08005130 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005131 public String[] getTetheringErroredIfaces() {
markchien5776f962019-12-16 20:15:20 +08005132 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5133 Context.TETHERING_SERVICE);
5134
5135 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005136 }
5137
Lorenzo Colittid6459092016-07-04 12:55:44 +09005138 @Override
markchien5776f962019-12-16 20:15:20 +08005139 @Deprecated
5140 public String[] getTetherableUsbRegexs() {
5141 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5142 Context.TETHERING_SERVICE);
5143
5144 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005145 }
5146
Udam Saini8f7d6a72017-06-07 12:06:28 -07005147 @Override
markchien5776f962019-12-16 20:15:20 +08005148 @Deprecated
5149 public String[] getTetherableWifiRegexs() {
5150 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5151 Context.TETHERING_SERVICE);
5152 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005153 }
5154
Robert Greenwalte0b00512014-07-02 09:59:16 -07005155 // Called when we lose the default network and have no replacement yet.
5156 // This will automatically be cleared after X seconds or a new default network
5157 // becomes CONNECTED, whichever happens first. The timer is started by the
5158 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005159 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005160 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005161 if (mNetTransitionWakeLock.isHeld()) {
5162 return;
5163 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005164 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005165 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5166 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005167 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005168 mWakelockLogs.log("ACQUIRE for " + forWhom);
5169 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005170 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005171 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005172 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005173 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005174
Hugo Benichi471b62a2017-03-30 23:18:10 +09005175 // Called when we gain a new default network to release the network transition wakelock in a
5176 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5177 // message is cancelled.
5178 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005179 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005180 if (!mNetTransitionWakeLock.isHeld()) {
5181 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005182 }
5183 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005184 // Cancel self timeout on wakelock hold.
5185 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5186 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5187 mHandler.sendMessageDelayed(msg, 1000);
5188 }
5189
5190 // Called when either message of ensureNetworkTransitionWakelock or
5191 // scheduleReleaseNetworkTransitionWakelock is processed.
5192 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5193 String event = eventName(eventId);
5194 synchronized (this) {
5195 if (!mNetTransitionWakeLock.isHeld()) {
5196 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005197 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005198 return;
5199 }
5200 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005201 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5202 mTotalWakelockDurationMs += lockDuration;
5203 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5204 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005205 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005206 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005207 }
5208
Robert Greenwalt986c7412010-09-08 15:24:47 -07005209 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005210 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005211 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005212 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005213 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005214 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005215 }
5216
Lorenzo Colittid6459092016-07-04 12:55:44 +09005217 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005218 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005219 enforceAccessPermission();
5220 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005221 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005222 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005223
5224 final NetworkAgentInfo nai;
5225 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005226 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005227 } else {
5228 nai = getNetworkAgentInfoForNetwork(network);
5229 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005230
5231 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005232 mHandler.obtainMessage(
5233 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005234 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005235
Hugo Benichid6b510a2017-04-06 17:22:18 +09005236 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005237 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005238 if (nai == null
5239 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005240 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005241 return;
5242 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005243 // Revalidate if the app report does not match our current validated state.
Hugo Benichie9d321b2017-04-06 16:01:44 +09005244 if (hasConnectivity == nai.lastValidated) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005245 mConnectivityDiagnosticsHandler.sendMessage(
5246 mConnectivityDiagnosticsHandler.obtainMessage(
5247 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5248 new ReportedNetworkConnectivityInfo(
5249 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005250 return;
5251 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005252 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005253 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005254 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005255 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005256 // Validating a network that has not yet connected could result in a call to
5257 // rematchNetworkAndRequests() which is not meant to work on such networks.
5258 if (!nai.everConnected) {
5259 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005260 }
paulhu7aeba372020-12-30 00:42:19 +08005261 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5262 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005263 return;
5264 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005265
5266 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5267 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5268 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5269 // completed.
5270 mConnectivityDiagnosticsHandler.sendMessage(
5271 mConnectivityDiagnosticsHandler.obtainMessage(
5272 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5273 new ReportedNetworkConnectivityInfo(
5274 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005275 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005276 }
5277
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005278 // TODO: call into netd.
5279 private boolean queryUserAccess(int uid, Network network) {
5280 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5281 if (nai == null) return false;
5282
5283 // Any UID can use its default network.
5284 if (nai == getDefaultNetworkForUid(uid)) return true;
5285
5286 // Privileged apps can use any network.
5287 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5288 return true;
5289 }
5290
5291 // An unprivileged UID can use a VPN iff the VPN applies to it.
5292 if (nai.isVPN()) {
5293 return nai.networkCapabilities.appliesToUid(uid);
5294 }
5295
5296 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5297 // sockets, i.e., if it is the owner.
5298 final NetworkAgentInfo vpn = getVpnForUid(uid);
5299 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5300 && uid != vpn.networkCapabilities.getOwnerUid()) {
5301 return false;
5302 }
5303
5304 // The UID's permission must be at least sufficient for the network. Since the restricted
5305 // permission was already checked above, that just leaves background networks.
5306 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5307 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5308 }
5309
5310 // Unrestricted network. Anyone gets to use it.
5311 return true;
5312 }
5313
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005314 /**
5315 * Returns information about the proxy a certain network is using. If given a null network, it
5316 * it will return the proxy for the bound network for the caller app or the default proxy if
5317 * none.
5318 *
5319 * @param network the network we want to get the proxy information for.
5320 * @return Proxy information if a network has a proxy configured, or otherwise null.
5321 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005322 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005323 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005324 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005325 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005326 if (network == null) {
5327 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005328 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005329 true);
5330 if (activeNetwork == null) {
5331 return null;
5332 }
5333 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005334 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005335 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5336 // caller may not have.
5337 return getLinkPropertiesProxyInfo(network);
5338 }
5339 // No proxy info available if the calling UID does not have network access.
5340 return null;
5341 }
5342
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005343
5344 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005345 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5346 if (nai == null) return null;
5347 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005348 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5349 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005350 }
5351 }
5352
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005353 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005354 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhudf23d662021-01-25 18:53:17 +08005355 PermissionUtils.enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005356 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005357 }
5358
Chalard Jean777e2e52018-06-07 18:02:37 +09005359 @Override
5360 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005361 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005362 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005363 }
5364
Jason Monk4d5e20f2014-04-25 15:00:09 -04005365 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005366 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005367 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005368 proxy = null;
5369 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005370 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005371 }
5372
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005373 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5374 // when any network changes proxy.
5375 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5376 // multi-network world where an app might be bound to a non-default network.
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005377 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensenc0618a62014-12-10 15:12:18 -05005378 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5379 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5380
Chalard Jean7d97afc2018-06-07 17:41:29 +09005381 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005382 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005383 }
5384 }
5385
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005386 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005387 final private HashMap<Uri, Integer> mUriEventMap;
5388 final private Context mContext;
5389 final private Handler mHandler;
5390
5391 SettingsObserver(Context context, Handler handler) {
5392 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005393 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005394 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005395 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005396 }
5397
Erik Kline05f2b402015-04-30 12:58:40 +09005398 void observe(Uri uri, int what) {
5399 mUriEventMap.put(uri, what);
5400 final ContentResolver resolver = mContext.getContentResolver();
5401 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005402 }
5403
5404 @Override
5405 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005406 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005407 }
5408
5409 @Override
5410 public void onChange(boolean selfChange, Uri uri) {
5411 final Integer what = mUriEventMap.get(uri);
5412 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005413 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005414 } else {
5415 loge("No matching event to send for URI=" + uri);
5416 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005417 }
5418 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005419
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005420 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005421 Log.d(TAG, s);
5422 }
5423
5424 private static void logw(String s) {
5425 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005426 }
5427
Daniel Brightf9e945b2020-06-15 16:10:01 -07005428 private static void logwtf(String s) {
5429 Log.wtf(TAG, s);
5430 }
5431
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005432 private static void logwtf(String s, Throwable t) {
5433 Log.wtf(TAG, s, t);
5434 }
5435
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005436 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005437 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005438 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005439
Hugo Benichi39621362017-02-11 17:04:43 +09005440 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005441 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005442 }
5443
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005444 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005445 * Return the information of all ongoing VPNs.
5446 *
5447 * <p>This method is used to update NetworkStatsService.
5448 *
5449 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08005450 */
junyulai2050bed2021-01-23 09:46:34 +08005451 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005452 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09005453 if (mLockdownEnabled) {
5454 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08005455 }
junyulai2050bed2021-01-23 09:46:34 +08005456 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005457 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08005458 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005459 if (info != null) {
5460 infoList.add(info);
5461 }
5462 }
junyulai2050bed2021-01-23 09:46:34 +08005463 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08005464 }
5465
5466 /**
5467 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00005468 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08005469 */
junyulai2050bed2021-01-23 09:46:34 +08005470 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005471 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08005472 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5473 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09005474 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5475 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5476 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08005477 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5478 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00005479 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00005480 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08005481 }
5482 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005483
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005484 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005485
5486 List<String> interfaces = new ArrayList<>();
5487 for (Network network : underlyingNetworks) {
5488 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5489 if (underlyingNai == null) continue;
5490 LinkProperties lp = underlyingNai.linkProperties;
5491 for (String iface : lp.getAllInterfaceNames()) {
5492 if (!TextUtils.isEmpty(iface)) {
5493 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00005494 }
5495 }
Benedict Wong34857f82019-06-12 17:46:15 +00005496 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005497
5498 if (interfaces.isEmpty()) return null;
5499
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005500 // Must be non-null or NetworkStatsService will crash.
5501 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5502 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08005503 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08005504 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005505
junyulai2050bed2021-01-23 09:46:34 +08005506 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5507 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08005508 }
5509
James Mattisd31bdfa2020-12-23 16:37:26 -08005510 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08005511 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5512 Network[] underlyingNetworks) {
5513 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005514 if (underlyingNetworks == null && defaultNetwork != null) {
5515 // null underlying networks means to track the default.
5516 underlyingNetworks = new Network[] { defaultNetwork };
5517 }
5518 return underlyingNetworks;
5519 }
5520
5521 // Returns true iff |network| is an underlying network of |nai|.
5522 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5523 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5524 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09005525 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08005526 final Network[] underlying = underlyingNetworksOrDefault(
5527 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005528 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005529 }
5530
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005531 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005532 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005533 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005534 * When underlying networks change, such networks may have to update capabilities to reflect
5535 * things like the metered bit, their transports, and so on. The capabilities are calculated
5536 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005537 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005538 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005539 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005540 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005541 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005542 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005543 }
5544 }
5545 }
5546
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005547 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5548 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5549 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5550 // a VPN is not up.
5551 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5552 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5553 for (UidRange range : blockedUidRanges) {
5554 if (range.contains(uid)) return true;
5555 }
5556 return false;
5557 }
5558
5559 @Override
5560 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08005561 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005562 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5563 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5564 }
5565
5566 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5567 if (DBG) {
5568 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5569 + Arrays.toString(ranges));
5570 }
5571 // Cannot use a Set since the list of UID ranges might contain duplicates.
5572 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5573 for (int i = 0; i < ranges.length; i++) {
5574 if (requireVpn) {
5575 newVpnBlockedUidRanges.add(ranges[i]);
5576 } else {
5577 newVpnBlockedUidRanges.remove(ranges[i]);
5578 }
5579 }
5580
5581 try {
5582 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5583 } catch (RemoteException | ServiceSpecificException e) {
5584 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5585 + Arrays.toString(ranges) + "): netd command failed: " + e);
5586 }
5587
5588 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5589 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00005590 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5591 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005592 }
5593
5594 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5595 }
5596
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07005597 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005598 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08005599 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005600 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01005601 }
5602
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005603 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5604 return mLockdownEnabled
5605 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5606 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00005607 }
5608
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005609 private NetworkAgentInfo getLegacyLockdownNai() {
5610 if (!mLockdownEnabled) {
5611 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005612 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005613 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005614 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5615 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005616
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005617 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005618 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5619 // a local variable. There is no need to make a copy because its contents cannot change.
5620 final Network[] underlying = nai.declaredUnderlyingNetworks;
5621 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005622 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005623 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005624
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005625 // The legacy lockdown VPN always uses the default network.
5626 // If the VPN's underlying network is no longer the current default network, it means that
5627 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005628 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5629 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005630 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005631 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005632 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005633 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005634
5635 return nai;
5636 };
5637
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005638 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5639 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5640 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005641 private DetailedState getLegacyLockdownState(DetailedState origState) {
5642 if (origState != DetailedState.CONNECTED) {
5643 return origState;
5644 }
5645 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5646 ? DetailedState.CONNECTING
5647 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005648 }
5649
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005650 private void filterForLegacyLockdown(NetworkInfo ni) {
5651 if (!mLockdownEnabled || !ni.isConnected()) return;
5652 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5653 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5654 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5655 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5656 // network, this time with a state of CONNECTED.
5657 //
5658 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5659 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5660 // is not too far off the truth, since an always-on VPN, when not connected, is always
5661 // trying to reconnect.
5662 if (getLegacyLockdownNai() == null) {
5663 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5664 }
5665 }
5666
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005667 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005668 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04005669 String action) {
paulhu8e96a752019-08-12 16:25:11 +08005670 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09005671 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5672 return;
5673 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04005674 final long ident = Binder.clearCallingIdentity();
5675 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09005676 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09005677 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09005678 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04005679 } finally {
5680 Binder.restoreCallingIdentity(ident);
5681 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005682 }
Wink Savillecb117d32013-08-29 14:57:08 -07005683
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005684 @Override
5685 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01005686 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005687 final long ident = Binder.clearCallingIdentity();
5688 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005689 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09005690 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005691 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5692 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08005693 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005694 } finally {
5695 Binder.restoreCallingIdentity(ident);
5696 }
5697 }
5698
James Mattis02220e22021-03-13 19:27:21 -08005699 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005700 mPermissionMonitor.onUserAdded(user);
James Mattisae9aeb02021-03-01 17:09:11 -08005701 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5702 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5703 }
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005704 }
5705
James Mattis02220e22021-03-13 19:27:21 -08005706 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005707 mPermissionMonitor.onUserRemoved(user);
Chalard Jean0f57a492021-03-09 21:09:20 +09005708 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005709 handleSetProfileNetworkPreference(
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08005710 List.of(new ProfileNetworkPreferenceList.Preference(user, null, true)),
Chalard Jean0f57a492021-03-09 21:09:20 +09005711 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08005712 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5713 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5714 }
junyulaid91e7052020-08-28 13:44:33 +08005715 }
5716
James Mattis02220e22021-03-13 19:27:21 -08005717 private void onPackageChanged(@NonNull final String packageName) {
5718 // This is necessary in case a package is added or removed, but also when it's replaced to
5719 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5720 // as one in the preferences, then it should follow the same routing as that other package,
5721 // which means updating the rules is never to be needed in this case (whether it joins or
5722 // leaves a UID with a preference).
5723 if (isMappedInOemNetworkPreference(packageName)) {
5724 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5725 }
5726 }
5727
5728 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005729 @Override
5730 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09005731 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005732 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005733 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08005734
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005735 // User should be filled for below intents, check the existence.
5736 if (user == null) {
5737 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5738 return;
5739 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005740
Lorenzo Colitticd675292021-02-04 17:32:07 +09005741 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005742 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005743 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005744 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09005745 } else {
junyulaid91e7052020-08-28 13:44:33 +08005746 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005747 }
5748 }
5749 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07005750
James Mattis02220e22021-03-13 19:27:21 -08005751 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5752 @Override
5753 public void onReceive(Context context, Intent intent) {
5754 ensureRunningOnConnectivityServiceThread();
5755 switch (intent.getAction()) {
5756 case Intent.ACTION_PACKAGE_ADDED:
5757 case Intent.ACTION_PACKAGE_REMOVED:
5758 case Intent.ACTION_PACKAGE_REPLACED:
5759 onPackageChanged(intent.getData().getSchemeSpecificPart());
5760 break;
5761 default:
5762 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5763 }
5764 }
5765 };
5766
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005767 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005768 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005769
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005770 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005771 public final String name;
5772 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005773 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005774 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005775
lifraf3a3492021-03-10 13:58:14 +08005776 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5777 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005778 this.name = name;
5779 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005780 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005781 mDeathRecipient = deathRecipient;
5782
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005783 if (mDeathRecipient == null) {
5784 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005785 }
5786 }
5787
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005788 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005789 try {
5790 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5791 } catch (RemoteException e) {
5792 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005793 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005794 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005795 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005796
James Mattis4fce5d12020-11-12 15:53:42 -08005797 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
5798 for (int i = 0; i < requests.size(); i++) {
5799 ensureNetworkRequestHasType(requests.get(i));
5800 }
5801 }
5802
Lorenzo Colitti70964d32016-07-05 01:22:13 +09005803 private void ensureNetworkRequestHasType(NetworkRequest request) {
5804 if (request.type == NetworkRequest.Type.NONE) {
5805 throw new IllegalArgumentException(
5806 "All NetworkRequests in ConnectivityService must have a type");
5807 }
5808 }
5809
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005810 /**
5811 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08005812 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005813 */
James Mattis258ea3c2020-11-15 15:04:40 -08005814 @VisibleForTesting
5815 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08005816 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
5817 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08005818 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08005819
James Mattisa076c532020-12-02 14:12:41 -08005820 // mSatisfier and mActiveRequest rely on one another therefore set them together.
5821 void setSatisfier(
5822 @Nullable final NetworkAgentInfo satisfier,
5823 @Nullable final NetworkRequest activeRequest) {
5824 mSatisfier = satisfier;
5825 mActiveRequest = activeRequest;
5826 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005827
James Mattisd31bdfa2020-12-23 16:37:26 -08005828 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005829 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09005830 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08005831 private NetworkAgentInfo mSatisfier;
5832 NetworkAgentInfo getSatisfier() {
5833 return mSatisfier;
5834 }
5835
5836 // The request in mRequests assigned to a network agent. This is null if none of the
5837 // requests in mRequests can be satisfied. This member has the constraint of only being
5838 // accessible on the handler thread.
5839 @Nullable
5840 private NetworkRequest mActiveRequest;
5841 NetworkRequest getActiveRequest() {
5842 return mActiveRequest;
5843 }
5844
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005845 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08005846 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08005847 @Nullable
5848 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005849
5850 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08005851 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005852 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005853 final int mPid;
5854 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08005855 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005856 @Nullable
5857 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005858
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005859 // Counter keeping track of this NRI.
5860 final PerUidCounter mPerUidCounter;
5861
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005862 // Effective UID of this request. This is different from mUid when a privileged process
5863 // files a request on behalf of another UID. This UID is used to determine blocked status,
5864 // UID matching, and so on. mUid above is used for permission checks and to enforce the
5865 // maximum limit of registered callbacks per UID.
5866 final int mAsUid;
5867
paulhu48291862021-07-14 14:53:57 +08005868 // Preference order of this request.
5869 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08005870
James Mattis3ce3d3c2021-02-09 18:18:28 -08005871 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
5872 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
5873 // maintained for keying off of. This is only a concern when the original nri
5874 // mNetworkRequests changes which happens currently for apps that register callbacks to
5875 // track the default network. In those cases, the nri is updated to have mNetworkRequests
5876 // that match the per-app default nri that currently tracks the calling app's uid so that
5877 // callbacks are fired at the appropriate time. When the callbacks fire,
5878 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
5879 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
5880 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
5881 @NonNull
5882 private final NetworkRequest mNetworkRequestForCallback;
5883 NetworkRequest getNetworkRequestForCallback() {
5884 return mNetworkRequestForCallback;
5885 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005886
James Mattisd31bdfa2020-12-23 16:37:26 -08005887 /**
5888 * Get the list of UIDs this nri applies to.
5889 */
5890 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00005891 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08005892 // networkCapabilities.getUids() returns a defensive copy.
5893 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00005894 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
5895 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08005896 }
5897
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005898 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
5899 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08005900 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08005901 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08005902 }
5903
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005904 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08005905 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08005906 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005907 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08005908 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08005909 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005910 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08005911 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005912 mBinder = null;
5913 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005914 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005915 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005916 mPerUidCounter = getRequestCounter(this);
5917 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005918 /**
5919 * Location sensitive data not included in pending intent. Only included in
5920 * {@link NetworkCallback}.
5921 */
5922 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005923 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08005924 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005925 }
5926
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005927 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08005928 @Nullable final IBinder binder,
5929 @NetworkCallback.Flag int callbackFlags,
5930 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005931 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
5932 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08005933 }
5934
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005935 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08005936 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08005937 @Nullable final IBinder binder,
5938 @NetworkCallback.Flag int callbackFlags,
5939 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005940 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08005941 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08005942 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08005943 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08005944 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005945 mBinder = binder;
5946 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005947 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005948 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005949 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005950 mPerUidCounter = getRequestCounter(this);
5951 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005952 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005953 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08005954 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07005955 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005956 }
5957
James Mattis3ce3d3c2021-02-09 18:18:28 -08005958 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
5959 @NonNull final List<NetworkRequest> r) {
5960 super();
5961 ensureAllNetworkRequestsHaveType(r);
5962 mRequests = initializeRequests(r);
5963 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005964 final NetworkAgentInfo satisfier = nri.getSatisfier();
5965 if (null != satisfier) {
5966 // If the old NRI was satisfied by an NAI, then it may have had an active request.
5967 // The active request is necessary to figure out what callbacks to send, in
5968 // particular then a network updates its capabilities.
5969 // As this code creates a new NRI with a new set of requests, figure out which of
5970 // the list of requests should be the active request. It is always the first
5971 // request of the list that can be satisfied by the satisfier since the order of
5972 // requests is a priority order.
5973 // Note even in the presence of a satisfier there may not be an active request,
5974 // when the satisfier is the no-service network.
5975 NetworkRequest activeRequest = null;
5976 for (final NetworkRequest candidate : r) {
5977 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
5978 activeRequest = candidate;
5979 break;
5980 }
5981 }
5982 setSatisfier(satisfier, activeRequest);
5983 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08005984 mMessenger = nri.mMessenger;
5985 mBinder = nri.mBinder;
5986 mPid = nri.mPid;
5987 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005988 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08005989 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09005990 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005991 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005992 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08005993 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08005994 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07005995 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08005996 }
5997
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005998 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08005999 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006000 }
6001
paulhue9913722021-05-26 15:19:20 +08006002 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006003 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006004 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006005 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006006 }
6007
James Mattis2516da32021-01-31 17:06:19 -08006008 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6009 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6010 // false.
6011 boolean isBeingSatisfied() {
6012 return (null != mSatisfier && null != mActiveRequest);
6013 }
6014
James Mattis3d229892020-11-16 16:46:28 -08006015 boolean isMultilayerRequest() {
6016 return mRequests.size() > 1;
6017 }
6018
James Mattis45d81842021-01-10 14:24:24 -08006019 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6020 // Creating a defensive copy to prevent the sender from modifying the list being
6021 // reflected in the return value of this method.
6022 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006023 return Collections.unmodifiableList(tempRequests);
6024 }
6025
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006026 void decrementRequestCount() {
6027 mPerUidCounter.decrementCount(mUid);
6028 }
6029
James Mattisb1392002021-03-31 13:57:52 -07006030 void linkDeathRecipient() {
6031 if (null != mBinder) {
6032 try {
6033 mBinder.linkToDeath(this, 0);
6034 } catch (RemoteException e) {
6035 binderDied();
6036 }
6037 }
6038 }
6039
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006040 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006041 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006042 try {
6043 mBinder.unlinkToDeath(this, 0);
6044 } catch (NoSuchElementException e) {
6045 // Temporary workaround for b/194394697 pending analysis of additional logs
6046 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6047 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006048 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006049 }
6050
paulhu48291862021-07-14 14:53:57 +08006051 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6052 // Compare two preference orders.
6053 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006054 }
6055
paulhu48291862021-07-14 14:53:57 +08006056 int getPreferenceOrderForNetd() {
6057 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6058 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6059 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006060 }
paulhu48291862021-07-14 14:53:57 +08006061 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006062 }
6063
James Mattis4fce5d12020-11-12 15:53:42 -08006064 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006065 public void binderDied() {
6066 log("ConnectivityService NetworkRequestInfo binderDied(" +
Chalard Jean524f0b12021-10-25 21:11:56 +09006067 "uid/pid:" + mUid + "/" + mPid + ", " + mRequests + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09006068 // As an immutable collection, mRequests cannot change by the time the
6069 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6070 // is acceptable. Use handleReleaseNetworkRequest and not directly
6071 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6072 // the app already unregistered the request.
6073 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6074 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006075 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006076
James Mattis4fce5d12020-11-12 15:53:42 -08006077 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006078 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006079 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6080 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006081 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006082 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006083 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006084 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006085 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006086 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006087 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006088 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006089 }
6090
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006091 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
6092 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
6093 if (badCapability != null) {
6094 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenee52d232015-06-16 15:11:58 -04006095 }
6096 }
6097
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006098 // This checks that the passed capabilities either do not request a
6099 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006100 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006101 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006102 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006103 throw new SecurityException("Insufficient permissions to request a specific SSID");
6104 }
paulhu1a407652019-03-22 16:35:06 +08006105
6106 if (nc.hasSignalStrength()
6107 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6108 throw new SecurityException(
6109 "Insufficient permissions to request a specific signal strength");
6110 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006111 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006112
junyulai2217bec2021-04-14 23:33:31 +08006113 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006114 enforceNetworkFactoryPermission();
6115 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006116 }
6117
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006118 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006119 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006120 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006121 // mNetworkRequests may contain the same value multiple times in case of
6122 // multilayer requests. It won't matter in this case because the thresholds
6123 // will then be the same and be deduplicated as they enter the `thresholds` set.
6124 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006125 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6126 for (final NetworkRequest req : nri.mRequests) {
6127 if (req.networkCapabilities.hasSignalStrength()
6128 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6129 thresholds.add(req.networkCapabilities.getSignalStrength());
6130 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006131 }
6132 }
6133 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006134 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006135 }
6136
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006137 private void updateSignalStrengthThresholds(
6138 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006139 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006140
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006141 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006142 String detail;
6143 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6144 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6145 } else {
6146 detail = reason;
6147 }
6148 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006149 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006150 }
6151
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006152 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006153 }
6154
Etan Cohen1b6d4182017-04-03 17:42:34 -07006155 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
6156 if (nc == null) {
6157 return;
6158 }
6159 NetworkSpecifier ns = nc.getNetworkSpecifier();
6160 if (ns == null) {
6161 return;
6162 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006163 if (ns instanceof MatchAllNetworkSpecifier) {
6164 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6165 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006166 }
6167
lucasline117e2e2019-10-22 18:27:33 +08006168 private void ensureValid(NetworkCapabilities nc) {
6169 ensureValidNetworkSpecifier(nc);
6170 if (nc.isPrivateDnsBroken()) {
6171 throw new IllegalArgumentException("Can't request broken private DNS");
6172 }
6173 }
6174
Chiachang Wang3bc52762021-11-25 14:17:57 +08006175 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6176 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006177 private boolean isTargetSdkAtleast(int version, int callingUid,
6178 @NonNull String callingPackageName) {
6179 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006180 final PackageManager pm =
6181 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006182 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006183 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006184 if (callingVersion < version) return false;
6185 } catch (PackageManager.NameNotFoundException e) { }
6186 return true;
6187 }
6188
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006189 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006190 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006191 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006192 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006193 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006194 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006195 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6196 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006197 throw new SecurityException("Insufficient permissions to specify legacy type");
6198 }
markchienfac84a22020-03-18 21:16:15 +08006199 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006200 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006201 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006202 // Privileged callers can track the default network of another UID by passing in a UID.
6203 if (asUid != Process.INVALID_UID) {
6204 enforceSettingsPermission();
6205 } else {
6206 asUid = callingUid;
6207 }
junyulaiad010792021-01-11 16:53:38 +08006208 final NetworkRequest.Type reqType;
6209 try {
6210 reqType = NetworkRequest.Type.values()[reqTypeInt];
6211 } catch (ArrayIndexOutOfBoundsException e) {
6212 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6213 }
6214 switch (reqType) {
6215 case TRACK_DEFAULT:
6216 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006217 // is unused and will be replaced by ones appropriate for the UID (usually, the
6218 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006219 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006220 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006221 enforceAccessPermission();
6222 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006223 case TRACK_SYSTEM_DEFAULT:
6224 enforceSettingsPermission();
6225 networkCapabilities = new NetworkCapabilities(defaultNc);
6226 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006227 case BACKGROUND_REQUEST:
6228 enforceNetworkStackOrSettingsPermission();
6229 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006230 case REQUEST:
6231 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6232 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6233 callingAttributionTag);
6234 // TODO: this is incorrect. We mark the request as metered or not depending on
6235 // the state of the app when the request is filed, but we never change the
6236 // request if the app changes network state. http://b/29964605
6237 enforceMeteredApnPolicy(networkCapabilities);
6238 break;
junyulai1b1c8742021-03-12 20:05:08 +08006239 case LISTEN_FOR_BEST:
6240 enforceAccessPermission();
6241 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6242 break;
junyulaiad010792021-01-11 16:53:38 +08006243 default:
6244 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006245 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006246 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006247 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006248 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006249
junyulai1b1c8742021-03-12 20:05:08 +08006250 // Enforce FOREGROUND if the caller does not have permission to use background network.
6251 if (reqType == LISTEN_FOR_BEST) {
6252 restrictBackgroundRequestForCaller(networkCapabilities);
6253 }
6254
6255 // Set the UID range for this request to the single UID of the requester, unless the
6256 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006257 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6258 // are no visible methods to set the UIDs, an app could use reflection to try and get
6259 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006260 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006261 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6262 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006263
Etan Cohen85000162017-02-05 10:42:27 -08006264 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006265 throw new IllegalArgumentException("Bad timeout specified");
6266 }
lucasline117e2e2019-10-22 18:27:33 +08006267 ensureValid(networkCapabilities);
Etan Cohen9786d922015-11-18 10:56:15 -08006268
James Mattis3ce3d3c2021-02-09 18:18:28 -08006269 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006270 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006271 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006272 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006273 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006274 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006275
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006276 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6277 // copied from the default request above. (This is necessary to ensure, for example, that
6278 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6279 // changes don't alter request matching.
6280 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6281 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006282 throw new IllegalStateException(
6283 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006284 + networkCapabilities + " vs. " + defaultNc);
6285 }
6286
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006287 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006288 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006289 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006290 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006291 }
6292 return networkRequest;
6293 }
6294
James Mattis3ce3d3c2021-02-09 18:18:28 -08006295 /**
6296 * Return the nri to be used when registering a network request. Specifically, this is used with
6297 * requests registered to track the default request. If there is currently a per-app default
6298 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6299 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006300 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6301 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006302 * @param nr the network request for the nri.
6303 * @param msgr the messenger for the nri.
6304 * @param binder the binder for the nri.
6305 * @param callingAttributionTag the calling attribution tag for the nri.
6306 * @return the nri to register.
6307 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006308 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006309 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006310 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006311 @Nullable String callingAttributionTag) {
6312 final List<NetworkRequest> requests;
6313 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6314 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006315 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006316 } else {
6317 requests = Collections.singletonList(nr);
6318 }
Roshan Pius951c0032020-12-22 15:10:42 -08006319 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006320 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006321 }
6322
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006323 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
6324 String callingPackageName, String callingAttributionTag) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006325 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichibd0cc762016-07-19 15:59:27 +09006326 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006327 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006328 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006329 }
6330 }
6331
fenglu3f357402015-03-20 11:29:56 -07006332 @Override
fenglub00f4882015-04-21 17:12:05 -07006333 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006334 enforceAccessPermission();
6335 NetworkAgentInfo nai = null;
6336 if (network == null) {
6337 return false;
6338 }
6339 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006340 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006341 }
6342 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006343 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006344 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006345 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006346 Integer uidReqs = mBandwidthRequests.get(uid);
6347 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006348 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006349 }
6350 mBandwidthRequests.put(uid, ++uidReqs);
6351 }
fenglu3f357402015-03-20 11:29:56 -07006352 return true;
6353 }
6354 return false;
6355 }
6356
Felipe Leme0a5ae422016-06-20 16:36:29 -07006357 private boolean isSystem(int uid) {
6358 return uid < Process.FIRST_APPLICATION_UID;
6359 }
fenglu3f357402015-03-20 11:29:56 -07006360
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006361 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006362 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006363 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006364 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006365 return;
6366 }
Hugo Benichi39621362017-02-11 17:04:43 +09006367 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6368 // Policy already enforced.
6369 return;
6370 }
paulhuaf50d7d2020-12-24 19:47:34 +08006371 final long ident = Binder.clearCallingIdentity();
6372 try {
6373 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6374 // If UID is restricted, don't allow them to bring up metered APNs.
6375 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6376 }
6377 } finally {
6378 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006379 }
6380 }
6381
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006382 @Override
6383 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006384 PendingIntent operation, @NonNull String callingPackageName,
6385 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006386 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006387 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006388 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006389 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6390 callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006391 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006392 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006393 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006394 Binder.getCallingPid(), callingUid, callingPackageName);
Etan Cohen1b6d4182017-04-03 17:42:34 -07006395 ensureValidNetworkSpecifier(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006396 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6397 callingUid, callingPackageName);
Etan Cohen89134542017-04-03 12:17:51 -07006398
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006399 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006400 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006401 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6402 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006403 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006404 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6405 nri));
6406 return networkRequest;
6407 }
6408
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006409 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6410 mHandler.sendMessageDelayed(
6411 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006412 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006413 }
6414
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006415 @Override
6416 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006417 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006418 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006419 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006420 }
6421
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006422 // In order to implement the compatibility measure for pre-M apps that call
6423 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6424 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6425 // This ensures it has permission to do so.
6426 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6427 if (nc == null) {
6428 return false;
6429 }
6430 int[] transportTypes = nc.getTransportTypes();
6431 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6432 return false;
6433 }
6434 try {
6435 mContext.enforceCallingOrSelfPermission(
6436 android.Manifest.permission.ACCESS_WIFI_STATE,
6437 "ConnectivityService");
6438 } catch (SecurityException e) {
6439 return false;
6440 }
6441 return true;
6442 }
6443
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006444 @Override
6445 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08006446 Messenger messenger, IBinder binder,
6447 @NetworkCallback.Flag int callbackFlags,
6448 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006449 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006450 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6451 enforceAccessPermission();
6452 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006453
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006454 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006455 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006456 Binder.getCallingPid(), callingUid, callingPackageName);
6457 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09006458 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6459 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6460 // onLost and onAvailable callbacks when networks move in and out of the background.
6461 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6462 // can't request networks.
6463 restrictBackgroundRequestForCaller(nc);
lucasline117e2e2019-10-22 18:27:33 +08006464 ensureValid(nc);
Etan Cohen89134542017-04-03 12:17:51 -07006465
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006466 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006467 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08006468 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006469 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08006470 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006471 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006472
6473 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6474 return networkRequest;
6475 }
6476
6477 @Override
6478 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08006479 PendingIntent operation, @NonNull String callingPackageName,
6480 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006481 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006482 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04006483 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6484 enforceAccessPermission();
6485 }
lucasline117e2e2019-10-22 18:27:33 +08006486 ensureValid(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006487 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006488 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006489 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006490 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006491
6492 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006493 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006494 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6495 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006496 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04006497
WeiZhang1cc3f172021-06-03 19:02:04 -05006498 mHandler.sendMessage(mHandler.obtainMessage(
6499 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006500 }
6501
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006502 /** Returns the next Network provider ID. */
6503 public final int nextNetworkProviderId() {
6504 return mNextNetworkProviderId.getAndIncrement();
6505 }
6506
Erik Kline0c04b742016-07-07 16:50:58 +09006507 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006508 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006509 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09006510 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006511 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006512 }
6513
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006514 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6515 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006516 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6517 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6518 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08006519 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006520 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006521 return;
6522 }
6523
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006524 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6525 mNetworkProviderInfos.put(npi.messenger, npi);
6526 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006527 }
6528
6529 @Override
6530 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006531 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08006532 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006533 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08006534 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006535 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6536 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006537 }
6538
6539 @Override
6540 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006541 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006542 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006543 }
6544
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006545 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09006546 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006547 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6548 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09006549 Objects.requireNonNull(score);
6550 Objects.requireNonNull(caps);
6551 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09006552 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006553 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09006554 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
6555 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006556 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6557 }
6558
Chalard Jeanbb902a52021-08-18 01:35:19 +09006559 private void updateOfferScore(final NetworkOffer offer) {
6560 final boolean yieldToBadWiFi =
6561 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
6562 final NetworkOffer newOffer = new NetworkOffer(
6563 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
6564 offer.caps, offer.callback, offer.providerId);
6565 if (offer.equals(newOffer)) return;
6566 handleRegisterNetworkOffer(newOffer);
6567 }
6568
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006569 @Override
6570 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6571 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6572 }
6573
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006574 private void handleUnregisterNetworkProvider(Messenger messenger) {
6575 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6576 if (npi == null) {
6577 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006578 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006579 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006580 // Unregister all the offers from this provider
6581 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6582 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09006583 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006584 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6585 toRemove.add(noi);
6586 }
6587 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09006588 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006589 handleUnregisterNetworkOffer(noi);
6590 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006591 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006592 }
6593
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006594 @Override
James Mattisf7027322020-12-13 16:28:14 -08006595 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006596 if (request.hasTransport(TRANSPORT_TEST)) {
6597 enforceNetworkFactoryOrTestNetworksPermission();
6598 } else {
6599 enforceNetworkFactoryPermission();
6600 }
James Mattisf7027322020-12-13 16:28:14 -08006601 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6602 if (nri != null) {
6603 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6604 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6605 mHandler.post(() -> handleReleaseNetworkRequest(
6606 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6607 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006608 }
6609
Paul Jensen1f567382015-02-13 14:18:39 -05006610 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6611 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006612 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05006613 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006614 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05006615 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006616 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006617
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09006618 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05006619 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006620 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006621
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006622 // UID ranges for users that are currently blocked by VPNs.
6623 // This array is accessed and iterated on multiple threads without holding locks, so its
6624 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6625 // (on the handler thread).
6626 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6627
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006628 // Must only be accessed on the handler thread
6629 @NonNull
6630 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6631
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006632 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006633 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006634
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006635 // Current OEM network preferences. This object must only be written to on the handler thread.
6636 // Since it is immutable and always non-null, other threads may read it if they only care
6637 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08006638 @NonNull
6639 private OemNetworkPreferences mOemNetworkPreferences =
6640 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006641 // Current per-profile network preferences. This object follows the same threading rules as
6642 // the OEM network preferences above.
6643 @NonNull
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006644 private ProfileNetworkPreferenceList mProfileNetworkPreferences =
6645 new ProfileNetworkPreferenceList();
James Mattis45d81842021-01-10 14:24:24 -08006646
paulhu51f77dc2021-06-07 02:34:20 +00006647 // A set of UIDs that should use mobile data preferentially if available. This object follows
6648 // the same threading rules as the OEM network preferences above.
6649 @NonNull
6650 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
6651
James Mattiscb1e0362021-04-06 17:07:42 -07006652 // OemNetworkPreferences activity String log entries.
6653 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6654 @NonNull
6655 private final LocalLog mOemNetworkPreferencesLogs =
6656 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6657
James Mattis02220e22021-03-13 19:27:21 -08006658 /**
6659 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6660 * @param packageName the package name to check existence of a mapping for.
6661 * @return true if a mapping exists, false otherwise
6662 */
6663 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6664 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6665 }
6666
James Mattise3ef1912020-12-20 11:09:58 -08006667 // The always-on request for an Internet-capable network that apps without a specific default
6668 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08006669 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09006670 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006671 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08006672 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08006673 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08006674 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006675 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006676
James Mattisd31bdfa2020-12-23 16:37:26 -08006677 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6678 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6679 }
6680
6681 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08006682 * Return the default network request currently tracking the given uid.
6683 * @param uid the uid to check.
6684 * @return the NetworkRequestInfo tracking the given uid.
6685 */
6686 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08006687 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08006688 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006689 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006690 // Checking the first request is sufficient as only multilayer requests will have more
6691 // than one request and for multilayer, all requests will track the same uids.
6692 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08006693 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08006694 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08006695 highestPriorityNri = nri;
6696 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006697 }
6698 }
paulhuaa0743d2021-05-26 21:56:03 +08006699 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006700 }
6701
6702 /**
6703 * Get a copy of the network requests of the default request that is currently tracking the
6704 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006705 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6706 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006707 * @param requestorUid the uid to check the default for.
6708 * @param requestorPackageName the requestor's package name.
6709 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6710 */
6711 @NonNull
6712 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006713 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006714 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006715 getDefaultRequestTrackingUid(asUid).mRequests,
6716 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006717 }
6718
6719 /**
6720 * Copy the given nri's NetworkRequest collection.
6721 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006722 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6723 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006724 * @param requestorUid the uid to set on the copied collection.
6725 * @param requestorPackageName the package name to set on the copied collection.
6726 * @return the copied NetworkRequest collection.
6727 */
6728 @NonNull
6729 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006730 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6731 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006732 final List<NetworkRequest> requests = new ArrayList<>();
6733 for (final NetworkRequest nr : requestsToCopy) {
6734 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006735 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08006736 nr.legacyType, nextNetworkRequestId(), nr.type));
6737 }
6738 return requests;
6739 }
6740
6741 @NonNull
6742 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006743 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6744 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09006745 // These capabilities are for a TRACK_DEFAULT callback, so:
6746 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6747 // mDefaultRequest and a per-UID default request.
6748 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006749 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09006750 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006751 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6752 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006753 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006754 restrictRequestUidsForCallerAndSetRequestorInfo(
6755 netCap, requestorUid, requestorPackageName);
6756 return netCap;
6757 }
6758
6759 /**
6760 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6761 * @param nr the network request to check for equality against.
6762 * @return the nri if one exists, null otherwise.
6763 */
6764 @Nullable
6765 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6766 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6767 if (nri.getNetworkRequestForCallback().equals(nr)) {
6768 return nri;
6769 }
6770 }
6771 return null;
6772 }
6773
6774 /**
6775 * Check if an nri is currently being managed by per-app default networking.
6776 * @param nri the nri to check.
6777 * @return true if this nri is currently being managed by per-app default networking.
6778 */
6779 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
6780 // nri.mRequests.get(0) is only different from the original request filed in
6781 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
6782 // functionality therefore if these two don't match, it means this particular nri is
6783 // currently being managed by a per-app default.
6784 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
6785 }
6786
6787 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08006788 * Determine if an nri is a managed default request that disallows default networking.
6789 * @param nri the request to evaluate
6790 * @return true if device-default networking is disallowed
6791 */
6792 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
6793 // Check if this nri is a managed default that supports the default network at its
6794 // lowest priority request.
6795 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
6796 final NetworkCapabilities lowestPriorityNetCap =
6797 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
6798 return isPerAppDefaultRequest(nri)
6799 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
6800 lowestPriorityNetCap));
6801 }
6802
Erik Kline05f2b402015-04-30 12:58:40 +09006803 // Request used to optionally keep mobile data active even when higher
6804 // priority networks like Wi-Fi are active.
6805 private final NetworkRequest mDefaultMobileDataRequest;
6806
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006807 // Request used to optionally keep wifi data active even when higher
6808 // priority networks like ethernet are active.
6809 private final NetworkRequest mDefaultWifiRequest;
6810
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08006811 // Request used to optionally keep vehicle internal network always active
6812 private final NetworkRequest mDefaultVehicleRequest;
6813
James Mattisd31bdfa2020-12-23 16:37:26 -08006814 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
6815 // network with no service. This NAI should never be matched against, nor should any public API
6816 // ever return the associated network. For this reason, this NAI is not in the list of available
6817 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
6818 // default requests that don't support using the device default network which will ultimately
6819 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
6820 @VisibleForTesting
6821 final NetworkAgentInfo mNoServiceNetwork;
6822
Chalard Jean5b409c72021-02-04 13:12:59 +09006823 // The NetworkAgentInfo currently satisfying the default request, if any.
6824 private NetworkAgentInfo getDefaultNetwork() {
6825 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09006826 }
6827
James Mattis2516da32021-01-31 17:06:19 -08006828 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08006829 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08006830 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6831 // Currently, all network requests will have the same uids therefore checking the first
6832 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006833 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08006834 if (null == uids) {
6835 continue;
6836 }
6837 for (final UidRange range : uids) {
6838 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08006839 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08006840 highestPriorityNri = nri;
6841 }
James Mattis2516da32021-01-31 17:06:19 -08006842 }
6843 }
6844 }
paulhuaa0743d2021-05-26 21:56:03 +08006845 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08006846 }
6847
Varun Ananddf569952019-02-06 10:13:38 -08006848 @Nullable
6849 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
6850 return nai != null ? nai.network : null;
6851 }
6852
6853 private void ensureRunningOnConnectivityServiceThread() {
6854 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
6855 throw new IllegalStateException(
6856 "Not running on ConnectivityService thread: "
6857 + Thread.currentThread().getName());
6858 }
6859 }
6860
Chalard Jean3a3f5f22019-04-10 23:07:55 +09006861 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09006862 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
6863 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006864 }
6865
Chalard Jean29d06db2018-05-02 21:14:54 +09006866 /**
6867 * Register a new agent with ConnectivityService to handle a network.
6868 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006869 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09006870 * @param networkInfo the initial info associated with this network. It can be updated later :
6871 * see {@link #updateNetworkInfo}.
6872 * @param linkProperties the initial link properties of this network. They can be updated
6873 * later : see {@link #updateLinkProperties}.
6874 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09006875 * later : see {@link #updateCapabilities}.
Chalard Jean28018572020-12-21 18:36:52 +09006876 * @param initialScore the initial score of the network. See
Chalard Jean29d06db2018-05-02 21:14:54 +09006877 * {@link NetworkAgentInfo#getCurrentScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006878 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006879 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09006880 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09006881 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006882 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09006883 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09006884 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
6885 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09006886 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
6887 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
6888 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09006889 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09006890 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09006891 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6892 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006893 } else {
6894 enforceNetworkFactoryPermission();
6895 }
6896
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006897 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006898 final long token = Binder.clearCallingIdentity();
6899 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006900 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09006901 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006902 } finally {
6903 Binder.restoreCallingIdentity(token);
6904 }
6905 }
6906
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006907 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006908 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09006909 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
6910 int uid) {
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006911 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
Chalard Jean5b639762020-03-09 21:25:37 +09006912 // Strictly, sanitizing here is unnecessary as the capabilities will be sanitized in
6913 // the call to mixInCapabilities below anyway, but sanitizing here means the NAI never
6914 // sees capabilities that may be malicious, which might prevent mistakes in the future.
6915 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Chiachang Wangc07315a2021-08-10 15:13:39 +08006916 networkCapabilities.restrictCapabilitiesForTestNetwork(uid);
Chalard Jean5b639762020-03-09 21:25:37 +09006917 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006918
Rubin Xuffd77d82017-09-05 18:40:49 +01006919 LinkProperties lp = new LinkProperties(linkProperties);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006920
Chalard Jeana23bc9e2018-01-30 22:41:41 +09006921 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006922 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006923 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo), lp, nc,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09006924 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09006925 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
6926 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006927
6928 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006929 processCapabilitiesFromAgent(nai, nc);
Chalard Jean05edd052019-11-22 22:39:56 +09006930 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006931 processLinkPropertiesFromAgent(nai, nai.linkProperties);
6932
Chalard Jeanf2da1772018-04-26 16:16:10 +09006933 final String extraInfo = networkInfo.getExtraInfo();
6934 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09006935 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07006936 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006937 mDeps.getNetworkStack().makeNetworkMonitor(
6938 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006939 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
6940 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006941 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006942 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09006943 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006944 }
6945
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006946 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
6947 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006948 if (VDBG) log("Got NetworkAgent Messenger");
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006949 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05006950 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006951 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05006952 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006953
6954 try {
6955 networkMonitor.start();
6956 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08006957 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006958 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006959 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09006960 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09006961 updateNetworkInfo(nai, networkInfo);
6962 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006963 }
6964
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006965 private class NetworkOfferInfo implements IBinder.DeathRecipient {
6966 @NonNull public final NetworkOffer offer;
6967
6968 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
6969 this.offer = offer;
6970 }
6971
6972 @Override
6973 public void binderDied() {
6974 mHandler.post(() -> handleUnregisterNetworkOffer(this));
6975 }
6976 }
6977
Chalard Jeandd35f2d2021-03-24 14:31:38 +09006978 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
6979 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
6980 if (npi.providerId == providerId) return true;
6981 }
6982 return false;
6983 }
6984
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006985 /**
6986 * Register or update a network offer.
6987 * @param newOffer The new offer. If the callback member is the same as an existing
6988 * offer, it is an update of that offer.
6989 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09006990 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006991 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
6992 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09006993 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006994 // This may actually happen if a provider updates its score or registers and then
6995 // immediately unregisters. The offer would still be in the handler queue, but the
6996 // provider would have been removed.
6997 if (DBG) log("Received offer from an unregistered provider");
6998 return;
6999 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007000 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7001 if (null != existingOffer) {
7002 handleUnregisterNetworkOffer(existingOffer);
7003 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007004 if (DBG) {
7005 // handleUnregisterNetworkOffer has already logged the old offer
7006 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7007 }
7008 } else {
7009 if (DBG) {
7010 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7011 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007012 }
7013 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7014 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007015 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007016 } catch (RemoteException e) {
7017 noi.binderDied();
7018 return;
7019 }
7020 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007021 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007022 }
7023
7024 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7025 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007026 if (DBG) {
7027 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7028 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007029
7030 // If the provider removes the offer and dies immediately afterwards this
7031 // function may be called twice in a row, but the array will no longer contain
7032 // the offer.
7033 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007034 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007035 }
7036
7037 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7038 @NonNull final INetworkOfferCallback callback) {
7039 ensureRunningOnConnectivityServiceThread();
7040 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007041 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007042 }
7043 return null;
7044 }
7045
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007046 /**
7047 * Called when receiving LinkProperties directly from a NetworkAgent.
7048 * Stores into |nai| any data coming from the agent that might also be written to the network's
7049 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7050 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007051 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007052 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007053 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7054 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007055 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007056 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007057 }
7058
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007059 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007060 @NonNull LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007061 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007062
Lorenzo Colittid523d142020-04-01 20:16:30 +09007063 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7064 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7065 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007066 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007067
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007068 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007069
7070 // update filtering rules, need to happen after the interface update so netd knows about the
7071 // new interface (the interface name -> index map becomes initialized)
7072 updateVpnFiltering(newLp, oldLp, networkAgent);
7073
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007074 updateMtu(newLp, oldLp);
7075 // TODO - figure out what to do for clat
7076// for (LinkProperties lp : newLp.getStackedLinks()) {
7077// updateMtu(lp, null);
7078// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007079 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007080 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7081 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007082
Erik Klineb9888902016-04-05 13:30:49 +09007083 updateRoutes(newLp, oldLp, netId);
7084 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007085 // Make sure LinkProperties represents the latest private DNS status.
7086 // This does not need to be done before updateDnses because the
7087 // LinkProperties are not the source of the private DNS configuration.
7088 // updateDnses will fetch the private DNS configuration from DnsManager.
7089 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007090
Chalard Jean5b409c72021-02-04 13:12:59 +09007091 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007092 handleApplyDefaultProxy(newLp.getHttpProxy());
7093 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007094 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007095 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007096
7097 updateWakeOnLan(newLp);
7098
Hai Shalome58bdc62021-01-11 18:45:34 -08007099 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7100 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7101 // does, it needs to be merged here.
7102 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7103 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007104
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007105 // TODO - move this check to cover the whole function
7106 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007107 synchronized (networkAgent) {
7108 networkAgent.linkProperties = newLp;
7109 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007110 // Start or stop DNS64 detection and 464xlat according to network state.
7111 networkAgent.clatd.update();
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08007112 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007113 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7114 new LinkProperties(newLp, true /* parcelSensitiveFields */));
lucaslin74fa3972018-11-28 12:51:55 +08007115 if (networkAgent.everConnected) {
7116 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
7117 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007118 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007119
7120 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007121 }
7122
Hai Shalome58bdc62021-01-11 18:45:34 -08007123 /**
7124 * @param naData captive portal data from NetworkAgent
7125 * @param apiData captive portal data from capport API
7126 */
7127 @Nullable
7128 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7129 CaptivePortalData apiData) {
7130 if (naData == null || apiData == null) {
7131 return naData == null ? apiData : naData;
7132 }
7133 final CaptivePortalData.Builder captivePortalBuilder =
7134 new CaptivePortalData.Builder(naData);
7135
7136 if (apiData.isCaptive()) {
7137 captivePortalBuilder.setCaptive(true);
7138 }
7139 if (apiData.isSessionExtendable()) {
7140 captivePortalBuilder.setSessionExtendable(true);
7141 }
7142 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7143 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7144 // otherwise data would be inconsistent. Prefer the capport API info if present,
7145 // as it can generally be refreshed more often.
7146 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7147 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7148 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7149 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7150 // No source has time / bytes remaining information: surface the newest refresh time
7151 // for other fields
7152 captivePortalBuilder.setRefreshTime(
7153 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7154 }
7155
Hai Shalom7c6ab402021-02-04 19:34:06 -08007156 // Prioritize the user portal URL from the network agent if the source is authenticated.
7157 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7158 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7159 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7160 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007161 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007162 // Prioritize the venue information URL from the network agent if the source is
7163 // authenticated.
7164 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7165 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7166 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7167 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007168 }
7169 return captivePortalBuilder.build();
7170 }
7171
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007172 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007173 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007174 // marks on unsupported interfaces is harmless.
7175 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7176 return;
7177 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007178
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007179 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7180 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7181
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007182 // Mask/mark of zero will not detect anything interesting.
7183 // Don't install rules unless both values are nonzero.
7184 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007185 return;
7186 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007187
7188 final String prefix = "iface:" + iface;
7189 try {
7190 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007191 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007192 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007193 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007194 }
7195 } catch (Exception e) {
7196 loge("Exception modifying wakeup packet monitoring: " + e);
7197 }
7198
Joel Scherpelza235a812017-05-22 13:47:41 +09007199 }
7200
Chalard Jean9589e722019-11-19 19:03:53 +09007201 private void updateInterfaces(final @Nullable LinkProperties newLp,
7202 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007203 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09007204 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fa7d9e2017-08-22 16:35:52 +01007205 oldLp != null ? oldLp.getAllInterfaceNames() : null,
7206 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jean9589e722019-11-19 19:03:53 +09007207 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007208 for (final String iface : interfaceDiff.added) {
7209 try {
7210 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007211 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09007212 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007213 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7214 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007215 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007216 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007217 }
Paul Jensenbff73492014-04-28 10:33:11 -04007218 }
7219 }
Chalard Jean9589e722019-11-19 19:03:53 +09007220 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007221 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007222 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007223 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007224 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007225 } catch (Exception e) {
7226 loge("Exception removing interface: " + e);
7227 }
7228 }
7229 }
7230
Tyler Weare4314862019-12-05 14:55:30 -08007231 // TODO: move to frameworks/libs/net.
7232 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7233 final String nextHop;
7234
7235 switch (route.getType()) {
7236 case RouteInfo.RTN_UNICAST:
7237 if (route.hasGateway()) {
7238 nextHop = route.getGateway().getHostAddress();
7239 } else {
7240 nextHop = INetd.NEXTHOP_NONE;
7241 }
7242 break;
7243 case RouteInfo.RTN_UNREACHABLE:
7244 nextHop = INetd.NEXTHOP_UNREACHABLE;
7245 break;
7246 case RouteInfo.RTN_THROW:
7247 nextHop = INetd.NEXTHOP_THROW;
7248 break;
7249 default:
7250 nextHop = INetd.NEXTHOP_NONE;
7251 break;
7252 }
7253
7254 final RouteInfoParcel rip = new RouteInfoParcel();
7255 rip.ifName = route.getInterface();
7256 rip.destination = route.getDestination().toString();
7257 rip.nextHop = nextHop;
7258 rip.mtu = route.getMtu();
7259
7260 return rip;
7261 }
7262
Paul Jensene0fd4a82014-08-06 15:51:33 -04007263 /**
7264 * Have netd update routes from oldLp to newLp.
7265 * @return true if routes changed between oldLp and newLp
7266 */
7267 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007268 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007269 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7270 new CompareOrUpdateResult<>(
7271 oldLp != null ? oldLp.getAllRoutes() : null,
7272 newLp != null ? newLp.getAllRoutes() : null,
7273 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007274
7275 // add routes before removing old in case it helps with continuous connectivity
7276
Chalard Jean9dd11612018-06-04 16:52:49 +09007277 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007278 for (RouteInfo route : routeDiff.added) {
7279 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007280 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007281 try {
Tyler Weare4314862019-12-05 14:55:30 -08007282 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007283 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007284 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007285 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007286 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007287 }
7288 }
7289 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007290 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007291 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007292 try {
Tyler Weare4314862019-12-05 14:55:30 -08007293 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007294 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007295 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007296 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007297 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007298 }
7299 }
7300
7301 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007302 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007303 try {
Tyler Weare4314862019-12-05 14:55:30 -08007304 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007305 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007306 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007307 }
7308 }
Tyler Weare4314862019-12-05 14:55:30 -08007309
7310 for (RouteInfo route : routeDiff.updated) {
7311 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7312 try {
7313 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7314 } catch (Exception e) {
7315 loge("Exception in networkUpdateRouteParcel: " + e);
7316 }
7317 }
7318 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7319 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007320 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007321
Erik Klineb9888902016-04-05 13:30:49 +09007322 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7323 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7324 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007325 }
Erik Klineb9888902016-04-05 13:30:49 +09007326
Erik Kline31b4a9e2018-01-11 21:07:29 +09007327 if (DBG) {
7328 final Collection<InetAddress> dnses = newLp.getDnsServers();
7329 log("Setting DNS servers for network " + netId + " to " + dnses);
7330 }
Erik Klineb9888902016-04-05 13:30:49 +09007331 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007332 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007333 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007334 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007335 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007336 }
Erik Kline54e35c02017-04-07 15:29:29 +09007337 }
7338
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007339 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7340 NetworkAgentInfo nai) {
7341 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
7342 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
7343 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
7344 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
7345
7346 if (!wasFiltering && !needsFiltering) {
7347 // Nothing to do.
7348 return;
7349 }
7350
7351 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7352 // Nothing changed.
7353 return;
7354 }
7355
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007356 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Qingxi Libb8da982020-01-17 17:54:27 -08007357 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007358 // TODO: this create a window of opportunity for apps to receive traffic between the time
7359 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007360 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007361 // old rules are being removed.
7362 if (wasFiltering) {
7363 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7364 }
7365 if (needsFiltering) {
7366 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7367 }
7368 }
7369
Valentin Iftime9fa35092019-09-24 13:32:13 +02007370 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007371 if (mWolSupportedInterfaces == null) {
7372 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007373 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007374 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007375 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7376 }
7377
Luke Huangb913c812018-08-24 20:33:16 +08007378 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007379 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007380 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007381 }
7382 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007383 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007384 }
Luke Huangb913c812018-08-24 20:33:16 +08007385 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007386 }
7387
Chalard Jean62edfd82019-12-02 18:39:29 +09007388 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7389 @NonNull final NetworkCapabilities newNc) {
7390 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7391 final int newPermission = getNetworkPermission(newNc);
7392 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7393 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007394 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08007395 } catch (RemoteException | ServiceSpecificException e) {
7396 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09007397 }
7398 }
7399 }
7400
Paul Jensen53f08952015-06-16 14:27:36 -04007401 /**
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007402 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7403 * Stores into |nai| any data coming from the agent that might also be written to the network's
7404 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7405 * agent is not lost when updateCapabilities is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007406 * This method should never alter the agent's NetworkCapabilities, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007407 */
7408 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007409 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7410 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7411 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7412 // the owner UID here and behave as if the agent had never tried to change it.
Lorenzo Colitti93401342020-12-09 18:30:52 +09007413 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7414 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7415 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7416 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7417 }
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007418 nai.declaredCapabilities = new NetworkCapabilities(nc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007419 }
7420
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007421 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007422 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09007423 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007424 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08007425 underlyingNetworks = underlyingNetworksOrDefault(
7426 agentCaps.getOwnerUid(), underlyingNetworks);
lifrade6c2a2021-03-04 14:08:08 +08007427 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007428 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7429 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007430 // metered if any underlying is metered, or originally declared metered by the agent.
7431 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007432 boolean roaming = false; // roaming if any underlying is roaming
7433 boolean congested = false; // congested if any underlying is congested
7434 boolean suspended = true; // suspended if all underlying are suspended
7435
7436 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08007437 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007438 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08007439 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007440 for (Network underlyingNetwork : underlyingNetworks) {
7441 final NetworkAgentInfo underlying =
7442 getNetworkAgentInfoForNetwork(underlyingNetwork);
7443 if (underlying == null) continue;
7444
7445 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7446 hadUnderlyingNetworks = true;
7447 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007448 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007449 }
7450
7451 // Merge capabilities of this underlying network. For bandwidth, assume the
7452 // worst case.
7453 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7454 underlyingCaps.getLinkDownstreamBandwidthKbps());
7455 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7456 underlyingCaps.getLinkUpstreamBandwidthKbps());
7457 // If this underlying network is metered, the VPN is metered (it may cost money
7458 // to send packets on this network).
7459 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7460 // If this underlying network is roaming, the VPN is roaming (the billing structure
7461 // is different than the usual, local one).
7462 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7463 // If this underlying network is congested, the VPN is congested (the current
7464 // condition of the network affects the performance of this network).
7465 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7466 // If this network is not suspended, the VPN is not suspended (the VPN
7467 // is able to transfer some data).
7468 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08007469 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007470 }
7471 }
7472 if (!hadUnderlyingNetworks) {
7473 // No idea what the underlying networks are; assume reasonable defaults
7474 metered = true;
7475 roaming = false;
7476 congested = false;
7477 suspended = false;
7478 }
7479
lifrade6c2a2021-03-04 14:08:08 +08007480 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007481 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7482 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7483 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7484 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7485 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7486 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08007487 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007488 }
7489
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007490 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007491 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7492 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7493 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04007494 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007495 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007496 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09007497 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007498 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7499 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007500 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007501 // avoid connect/teardown loops.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007502 if (nai.everConnected &&
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007503 !nai.isVPN() &&
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007504 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7505 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09007506 // does not cause any request (that is not a listen) currently matching that agent to
7507 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007508 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09007509 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007510 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09007511 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007512 }
7513
Paul Jensen53f08952015-06-16 14:27:36 -04007514 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007515 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensende49eb12015-06-25 15:30:08 -04007516 if (nai.lastValidated) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007517 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007518 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007519 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007520 }
Paul Jensende49eb12015-06-25 15:30:08 -04007521 if (nai.lastCaptivePortalDetected) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007522 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007523 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007524 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007525 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007526 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007527 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007528 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007529 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007530 }
lucaslin2240ef62019-03-12 13:08:03 +08007531 if (nai.partialConnectivity) {
7532 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7533 } else {
7534 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7535 }
lucasline117e2e2019-10-22 18:27:33 +08007536 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007537
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007538 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09007539 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7540 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007541 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09007542 }
7543
Lorenzo Colittibd079452021-07-02 11:47:57 +09007544 if (nai.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007545 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7546 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007547 }
7548
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007549 return newNc;
7550 }
7551
Lorenzo Colitti44840702021-01-11 22:27:57 +09007552 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7553 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7554 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7555 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7556 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7557 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7558 if (prevSuspended != suspended) {
7559 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7560 // onResumed have been removed.
7561 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7562 : ConnectivityManager.CALLBACK_RESUMED);
7563 }
7564 if (prevSuspended != suspended || prevRoaming != roaming) {
7565 // updateNetworkInfo will mix in the suspended info from the capabilities and
7566 // take appropriate action for the network having possibly changed state.
7567 updateNetworkInfo(nai, nai.networkInfo);
7568 }
7569 }
7570
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007571 /**
7572 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7573 *
7574 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7575 * capabilities we manage and store in {@code nai}, such as validated status and captive
7576 * portal status)
7577 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7578 * potentially triggers rematches.
7579 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7580 * change.)
7581 *
7582 * @param oldScore score of the network before any of the changes that prompted us
7583 * to call this function.
7584 * @param nai the network having its capabilities updated.
7585 * @param nc the new network capabilities.
7586 */
Chalard Jean62edfd82019-12-02 18:39:29 +09007587 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7588 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007589 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007590 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean62edfd82019-12-02 18:39:29 +09007591 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09007592 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007593
Chalard Jeanb2a49912018-01-16 18:43:05 +09007594 updateUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09007595 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007596
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007597 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007598 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7599 // the change we're processing can't affect any requests, it can only affect the listens
7600 // on this network. We might have been called by rematchNetworkAndRequests when a
7601 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09007602 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007603 } else {
7604 // If the requestable capabilities have changed or the score changed, we can't have been
7605 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09007606 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04007607 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07007608 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09007609 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007610
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007611 final boolean oldMetered = prevNc.isMetered();
7612 final boolean newMetered = newNc.isMetered();
7613 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08007614
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007615 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00007616 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7617 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007618 }
junyulaif2c67e42018-08-07 19:50:45 +08007619
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007620 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7621 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08007622
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007623 // Report changes that are interesting for network statistics tracking.
7624 if (meteredChanged || roamingChanged) {
7625 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06007626 }
7627
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007628 // This network might have been underlying another network. Propagate its capabilities.
7629 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08007630
7631 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007632 mDnsManager.updateTransportsForNetwork(
7633 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08007634 }
lucaslin53e8a262021-06-08 01:43:59 +08007635
7636 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007637 }
7638
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007639 /** Convenience method to update the capabilities for a given network. */
7640 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7641 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7642 }
7643
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007644 /**
7645 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7646 * network.
7647 *
7648 * Ingress interface filtering enforces that all apps under the given network can only receive
7649 * packets from the network's interface (and loopback). This is important for VPNs because
7650 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7651 * non-VPN interfaces.
7652 *
7653 * As a result, this method should return true iff
7654 * 1. the network is an app VPN (not legacy VPN)
7655 * 2. the VPN does not allow bypass
7656 * 3. the VPN is fully-routed
7657 * 4. the VPN interface is non-null
7658 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007659 * @see INetd#firewallAddUidInterfaceRules
7660 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007661 */
7662 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7663 LinkProperties lp) {
7664 if (nc == null || lp == null) return false;
7665 return nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007666 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08007667 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007668 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08007669 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7670 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007671 }
7672
Chiachang Wang28afaff2020-12-10 22:24:47 +08007673 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7674 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7675 int index = 0;
7676 for (UidRange range : ranges) {
7677 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7678 index++;
7679 }
7680 return stableRanges;
7681 }
7682
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007683 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7684 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7685 for (int i = 0; i < ranges.length; i++) {
7686 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7687 }
7688 return stableRanges;
7689 }
7690
Ken Chen5e65a852020-12-24 12:59:10 +08007691 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7692 int[] exemptUids) {
7693 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7694 try {
7695 mNetd.socketDestroy(ranges, exemptUids);
7696 } catch (Exception e) {
7697 loge("Exception in socket destroy: ", e);
7698 }
7699 }
7700 }
7701
paulhuaa0743d2021-05-26 21:56:03 +08007702 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08007703 int[] exemptUids = new int[2];
7704 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7705 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7706 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7707 exemptUids[0] = VPN_UID;
7708 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7709 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7710
7711 maybeCloseSockets(nai, ranges, exemptUids);
7712 try {
7713 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08007714 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007715 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08007716 } else {
paulhu0e79d952021-06-09 16:11:35 +08007717 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007718 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08007719 }
7720 } catch (Exception e) {
7721 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7722 " on netId " + nai.network.netId + ". " + e);
7723 }
7724 maybeCloseSockets(nai, ranges, exemptUids);
7725 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007726
lucaslin53e8a262021-06-08 01:43:59 +08007727 private boolean isProxySetOnAnyDefaultNetwork() {
7728 ensureRunningOnConnectivityServiceThread();
7729 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7730 final NetworkAgentInfo nai = nri.getSatisfier();
7731 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
7732 return true;
7733 }
7734 }
7735 return false;
7736 }
7737
7738 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7739 NetworkCapabilities newNc) {
7740 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
7741 // the proxy might be changed since the default network satisfied by the apps might also
7742 // changed.
7743 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
7744 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09007745 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
7746 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
7747 if (nai.isVPN() && nai.everConnected && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08007748 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
7749 mProxyTracker.sendProxyBroadcast();
7750 }
7751 }
7752
Chalard Jeanb2a49912018-01-16 18:43:05 +09007753 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7754 NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007755 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7756 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007757 if (null == prevRanges) prevRanges = new ArraySet<>();
7758 if (null == newRanges) newRanges = new ArraySet<>();
7759 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
7760
7761 prevRanges.removeAll(newRanges);
7762 newRanges.removeAll(prevRangesCopy);
7763
7764 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007765 // When updating the VPN uid routing rules, add the new range first then remove the old
7766 // range. If old range were removed first, there would be a window between the old
7767 // range being removed and the new range being added, during which UIDs contained
7768 // in both ranges are not subject to any VPN routing rules. Adding new range before
7769 // removing old range works because, unlike the filtering rules below, it's possible to
7770 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08007771 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
7772 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
7773 // [1-5] & [1-2],[4-5] == [3]
7774 // Then we can do:
7775 // maybeCloseSockets([3])
7776 // mNetd.networkAddUidRanges([1-2],[4-5])
7777 // mNetd.networkRemoveUidRanges([1-5])
7778 // maybeCloseSockets([3])
7779 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
7780 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09007781 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08007782 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007783 }
7784 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08007785 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007786 }
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007787 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
7788 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
7789 final String iface = nai.linkProperties.getInterfaceName();
7790 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09007791 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007792 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
7793 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
7794 // were added first and then newRanges got removed later, there would be only one uid
7795 // 10013 left. A consequence of removing old ranges before adding new ranges is that
7796 // there is now a window of opportunity when the UIDs are not subject to any filtering.
7797 // Note that this is in contrast with the (more robust) update of VPN routing rules
7798 // above, where the addition of new ranges happens before the removal of old ranges.
7799 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
7800 // to be removed will never overlap with the new range to be added.
7801 if (wasFiltering && !prevRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08007802 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007803 }
7804 if (shouldFilter && !newRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08007805 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007806 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09007807 } catch (Exception e) {
7808 // Never crash!
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007809 loge("Exception in updateUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007810 }
7811 }
7812
Hugo Benichi9d35b752017-09-01 01:23:32 +00007813 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09007814 ensureRunningOnConnectivityServiceThread();
7815
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007816 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00007817 // Ignore updates for disconnected networks
7818 return;
7819 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007820 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09007821 log("Update of LinkProperties for " + nai.toShortString()
7822 + "; created=" + nai.created
7823 + "; everConnected=" + nai.everConnected);
Hugo Benichi9d35b752017-09-01 01:23:32 +00007824 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007825 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
7826 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08007827 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00007828 }
7829
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007830 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
7831 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007832 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007833 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08007834 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08007835 // If apps could file multi-layer requests with PendingIntents, they'd need to know
7836 // which of the layer is satisfied alongside with some ID for the request. Hence, if
7837 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09007838 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
7839 // need to be sent as a separate extra.
7840 final NetworkRequest req = nri.isMultilayerRequest()
7841 ? nri.getActiveRequest()
7842 // Non-multilayer listen requests do not have an active request
7843 : nri.mRequests.get(0);
7844 if (req == null) {
7845 Log.wtf(TAG, "No request in NRI " + nri);
7846 }
7847 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007848 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007849 sendIntent(nri.mPendingIntent, intent);
7850 }
7851 // else not handled
7852 }
7853
7854 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
7855 mPendingIntentWakeLock.acquire();
7856 try {
7857 if (DBG) log("Sending " + pendingIntent);
7858 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
7859 } catch (PendingIntent.CanceledException e) {
7860 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
7861 mPendingIntentWakeLock.release();
7862 releasePendingNetworkRequest(pendingIntent);
7863 }
7864 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
7865 }
7866
7867 @Override
7868 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
7869 String resultData, Bundle resultExtras) {
7870 if (DBG) log("Finished sending " + pendingIntent);
7871 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007872 // Release with a delay so the receiving client has an opportunity to put in its
7873 // own request.
7874 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007875 }
7876
James Mattis212df9e2020-12-03 19:57:41 -08007877 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
7878 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
7879 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08007880 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08007881 // Default request has no msgr. Also prevents callbacks from being invoked for
7882 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
7883 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
7884 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007885 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007886 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08007887 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007888 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007889 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08007890 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007891 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007892 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
7893 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007894 }
Roshan Pius951c0032020-12-22 15:10:42 -08007895 final boolean includeLocationSensitiveInfo =
7896 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007897 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09007898 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08007899 final NetworkCapabilities nc =
7900 networkCapabilitiesRestrictedForCallerPermissions(
7901 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7902 putParcelable(
7903 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08007904 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08007905 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08007906 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08007907 nri.mCallingAttributionTag));
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09007908 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7909 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08007910 // For this notification, arg1 contains the blocked status.
7911 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09007912 break;
7913 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007914 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007915 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007916 break;
7917 }
7918 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09007919 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08007920 final NetworkCapabilities netCap =
7921 networkCapabilitiesRestrictedForCallerPermissions(
7922 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7923 putParcelable(
7924 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08007925 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08007926 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08007927 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08007928 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007929 break;
7930 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007931 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09007932 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7933 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007934 break;
7935 }
junyulaif2c67e42018-08-07 19:50:45 +08007936 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09007937 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08007938 msg.arg1 = arg1;
7939 break;
7940 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007941 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007942 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007943 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007944 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007945 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09007946 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08007947 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007948 }
James Mattis45d81842021-01-10 14:24:24 -08007949 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007950 } catch (RemoteException e) {
7951 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08007952 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007953 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007954 }
7955
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007956 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
7957 bundle.putParcelable(t.getClass().getSimpleName(), t);
7958 }
7959
Chalard Jean0702f982021-09-16 21:50:07 +09007960 /**
7961 * Returns whether reassigning a request from an NAI to another can be done gracefully.
7962 *
7963 * When a request should be assigned to a new network, it is normally lingered to give
7964 * time for apps to gracefully migrate their connections. When both networks are on the same
7965 * radio, but that radio can't do time-sharing efficiently, this may end up being
7966 * counter-productive because any traffic on the old network may drastically reduce the
7967 * performance of the new network.
7968 * The stack supports a configuration to let modem vendors state that their radio can't
7969 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
7970 * from one cell network to another can't be done gracefully.
7971 *
7972 * @param oldNai the old network serving the request
7973 * @param newNai the new network serving the request
7974 * @return whether the switch can be graceful
7975 */
7976 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
7977 @NonNull final NetworkAgentInfo newSatisfier) {
7978 if (mCellularRadioTimesharingCapable) return true;
7979 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
7980 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
7981 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
7982 }
7983
Paul Jensenaf94b982014-09-30 15:37:41 -04007984 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09007985 if (nai.numRequestNetworkRequests() != 0) {
7986 for (int i = 0; i < nai.numNetworkRequests(); i++) {
7987 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007988 // Ignore listening and track default requests.
7989 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09007990 loge("Dead network still had at least " + nr);
7991 break;
7992 }
Paul Jensenaf94b982014-09-30 15:37:41 -04007993 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007994 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04007995 }
7996
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007997 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
7998 if (oldNetwork == null) {
7999 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8000 return;
8001 }
Chalard Jean49707572019-12-10 21:07:02 +09008002 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008003
8004 // If we get here it means that the last linger timeout for this network expired. So there
8005 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008006 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008007
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008008 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008009 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008010 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008011 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008012 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008013 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008014 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008015 }
8016
James Mattise3ef1912020-12-20 11:09:58 -08008017 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8018 boolean isDefaultChanged = false;
8019 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8020 final NetworkReassignment.RequestReassignment reassignment =
8021 changes.getReassignment(defaultRequestInfo);
8022 if (null == reassignment) {
8023 continue;
8024 }
8025 // reassignment only contains those instances where the satisfying network changed.
8026 isDefaultChanged = true;
8027 // Notify system services of the new default.
8028 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8029 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008030
James Mattise3ef1912020-12-20 11:09:58 -08008031 if (isDefaultChanged) {
8032 // Hold a wakelock for a short time to help apps in migrating to a new default.
8033 scheduleReleaseNetworkTransitionWakelock();
8034 }
8035 }
8036
8037 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8038 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8039 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8040 if (DBG) {
8041 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8042 }
Chalard Jean8e382112019-12-03 20:45:30 +09008043
James Mattisd31bdfa2020-12-23 16:37:26 -08008044 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8045 if (newDefaultNetwork != null) {
8046 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008047 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008048
James Mattisd31bdfa2020-12-23 16:37:26 -08008049 // Set an app level managed default and return since further processing only applies to the
8050 // default network.
8051 if (mDefaultRequest != nri) {
8052 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8053 return;
8054 }
8055
8056 makeDefaultNetwork(newDefaultNetwork);
8057
James Mattise3ef1912020-12-20 11:09:58 -08008058 if (oldDefaultNetwork != null) {
8059 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8060 }
8061 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008062 handleApplyDefaultProxy(null != newDefaultNetwork
8063 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8064 updateTcpBufferSizes(null != newDefaultNetwork
8065 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008066 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008067 }
8068
James Mattisd31bdfa2020-12-23 16:37:26 -08008069 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8070 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8071 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8072 try {
8073 if (VDBG) {
8074 log("Setting default network for " + nri
8075 + " using UIDs " + nri.getUids()
8076 + " with old network " + (oldDefaultNetwork != null
8077 ? oldDefaultNetwork.network().getNetId() : "null")
8078 + " and new network " + (newDefaultNetwork != null
8079 ? newDefaultNetwork.network().getNetId() : "null"));
8080 }
8081 if (nri.getUids().isEmpty()) {
8082 throw new IllegalStateException("makeDefaultForApps called without specifying"
8083 + " any applications to set as the default." + nri);
8084 }
8085 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008086 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008087 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008088 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008089 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008090 }
8091 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008092 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008093 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008094 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008095 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008096 }
8097 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008098 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008099 }
8100 }
8101
8102 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8103 try {
8104 if (null != newDefaultNetwork) {
8105 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8106 } else {
8107 mNetd.networkClearDefault();
8108 }
8109 } catch (RemoteException | ServiceSpecificException e) {
8110 loge("Exception setting default network :" + e);
8111 }
8112 }
8113
Chalard Jean05cbe972019-12-09 11:50:38 +09008114 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008115 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09008116 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09008117 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09008118 processNewlySatisfiedListenRequests(nai);
8119 }
8120
8121 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008122 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8123 if (nri.isMultilayerRequest()) {
8124 continue;
8125 }
8126 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008127 if (!nr.isListen()) continue;
8128 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08008129 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008130 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
8131 }
8132 }
Chalard Jeancd397a22019-11-22 22:33:33 +09008133 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008134
Chalard Jeancd397a22019-11-22 22:33:33 +09008135 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008136 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8137 if (nri.isMultilayerRequest()) {
8138 continue;
8139 }
8140 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008141 if (!nr.isListen()) continue;
8142 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
8143 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09008144 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008145 }
8146 }
8147 }
8148
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008149 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008150 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008151 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08008152 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09008153 @Nullable public final NetworkRequest mOldNetworkRequest;
8154 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008155 @Nullable public final NetworkAgentInfo mOldNetwork;
8156 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08008157 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008158 @Nullable final NetworkRequest oldNetworkRequest,
8159 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008160 @Nullable final NetworkAgentInfo oldNetwork,
8161 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008162 mNetworkRequestInfo = networkRequestInfo;
8163 mOldNetworkRequest = oldNetworkRequest;
8164 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008165 mOldNetwork = oldNetwork;
8166 mNewNetwork = newNetwork;
8167 }
Chalard Jean49707572019-12-10 21:07:02 +09008168
8169 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09008170 final NetworkRequest requestToShow = null != mNewNetworkRequest
8171 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
8172 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08008173 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
8174 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09008175 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008176 }
8177
Chalard Jean46a62372019-12-10 21:25:24 +09008178 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008179
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008180 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09008181 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008182 }
8183
8184 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09008185 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09008186 // The code is never supposed to add two reassignments of the same request. Make
8187 // sure this stays true, but without imposing this expensive check on all
8188 // reassignments on all user devices.
8189 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08008190 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09008191 throw new IllegalStateException("Trying to reassign ["
8192 + reassignment + "] but already have ["
8193 + existing + "]");
8194 }
8195 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09008196 }
Chalard Jean46a62372019-12-10 21:25:24 +09008197 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008198 }
8199
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008200 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09008201 // the passed request.
8202 @Nullable
8203 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008204 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008205 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008206 }
8207 return null;
8208 }
Chalard Jean49707572019-12-10 21:07:02 +09008209
8210 public String toString() {
8211 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8212 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09008213 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008214 for (final RequestReassignment rr : getRequestReassignments()) {
8215 sj.add(rr.toString());
8216 }
8217 return sj.toString();
8218 }
8219
8220 public String debugString() {
8221 final StringBuilder sb = new StringBuilder();
8222 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09008223 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008224 for (final RequestReassignment rr : getRequestReassignments()) {
8225 sb.append("\n ").append(rr);
8226 }
8227 return sb.append("\n").toString();
8228 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008229 }
8230
Chalard Jean24344d72019-12-04 13:32:31 +09008231 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008232 @Nullable final NetworkRequest previousRequest,
8233 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09008234 @Nullable final NetworkAgentInfo previousSatisfier,
8235 @Nullable final NetworkAgentInfo newSatisfier,
8236 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08008237 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09008238 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09008239 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008240 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008241 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09008242 }
James Mattisa076c532020-12-02 14:12:41 -08008243 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean0702f982021-09-16 21:50:07 +09008244 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)) {
8245 // If this network switch can't be supported gracefully, the request is not
8246 // lingered. This allows letting go of the network sooner to reclaim some
8247 // performance on the new network, since the radio can't do both at the same
8248 // time while preserving good performance.
8249 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8250 }
Chalard Jean24344d72019-12-04 13:32:31 +09008251 } else {
8252 if (VDBG || DDBG) log(" accepting network in place of null");
8253 }
junyulai0ac374f2020-12-14 18:41:52 +08008254
8255 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8256 // and immediately satisfies a request then remove the timer. This will happen for
8257 // all networks except in the case of an underlying network for a VCN.
8258 if (newSatisfier.isNascent()) {
8259 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08008260 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008261 }
8262
Chalard Jean5d6e23b2021-03-01 22:00:20 +09008263 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08008264 newSatisfier.unlingerRequest(newRequest.requestId);
8265 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008266 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08008267 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008268 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09008269 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008270 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008271 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08008272 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008273 }
James Mattisa076c532020-12-02 14:12:41 -08008274 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008275 }
James Mattisa076c532020-12-02 14:12:41 -08008276 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008277 }
8278
James Mattisa076c532020-12-02 14:12:41 -08008279 /**
8280 * This function is triggered when something can affect what network should satisfy what
8281 * request, and it computes the network reassignment from the passed collection of requests to
8282 * network match to the one that the system should now have. That data is encoded in an
8283 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8284 * satisfier.
8285 *
8286 * After the reassignment is computed, it is applied to the state objects.
8287 *
8288 * @param networkRequests the nri objects to evaluate for possible network reassignment
8289 * @return NetworkReassignment listing of proposed network assignment changes
8290 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008291 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08008292 private NetworkReassignment computeNetworkReassignment(
8293 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09008294 final NetworkReassignment changes = new NetworkReassignment();
8295
Chalard Jeanc81d4c32021-04-07 17:06:19 +09008296 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09008297 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008298 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattisa076c532020-12-02 14:12:41 -08008299 if (!nai.everConnected) {
8300 continue;
8301 }
Chalard Jean857a1712019-12-10 21:08:07 +09008302 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09008303 }
Chalard Jean857a1712019-12-10 21:08:07 +09008304
James Mattisa076c532020-12-02 14:12:41 -08008305 for (final NetworkRequestInfo nri : networkRequests) {
8306 // Non-multilayer listen requests can be ignored.
8307 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8308 continue;
8309 }
8310 NetworkAgentInfo bestNetwork = null;
8311 NetworkRequest bestRequest = null;
8312 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09008313 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08008314 // Stop evaluating as the highest possible priority request is satisfied.
8315 if (null != bestNetwork) {
8316 bestRequest = req;
8317 break;
8318 }
8319 }
James Mattisd31bdfa2020-12-23 16:37:26 -08008320 if (null == bestNetwork && isDefaultBlocked(nri)) {
8321 // Remove default networking if disallowed for managed default requests.
8322 bestNetwork = mNoServiceNetwork;
8323 }
8324 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09008325 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09008326 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08008327 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09008328 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008329 }
8330 return changes;
8331 }
8332
James Mattisa076c532020-12-02 14:12:41 -08008333 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8334 return new HashSet<>(mNetworkRequests.values());
8335 }
8336
Paul Jensenc88b39b2015-06-16 14:27:36 -04008337 /**
James Mattisa076c532020-12-02 14:12:41 -08008338 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04008339 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04008340 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008341 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08008342 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8343 }
8344
8345 /**
8346 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8347 * being disconnected.
8348 */
8349 private void rematchNetworksAndRequests(
8350 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8351 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09008352 // TODO: This may be slow, and should be optimized.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008353 final long now = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08008354 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jean49707572019-12-10 21:07:02 +09008355 if (VDBG || DDBG) {
8356 log(changes.debugString());
8357 } else if (DBG) {
8358 log(changes.toString()); // Shorter form, only one line of log
8359 }
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008360 applyNetworkReassignment(changes, now);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008361 issueNetworkNeeds();
Chalard Jeand7f762d2019-12-10 19:01:29 +09008362 }
Chalard Jean64520dc2019-12-04 19:55:32 +09008363
Chalard Jeand7f762d2019-12-10 19:01:29 +09008364 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008365 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008366 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09008367
8368 // Since most of the time there are only 0 or 1 background networks, it would probably
8369 // be more efficient to just use an ArrayList here. TODO : measure performance
8370 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8371 for (final NetworkAgentInfo nai : nais) {
8372 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8373 }
8374
Chalard Jeand7f762d2019-12-10 19:01:29 +09008375 // First, update the lists of satisfied requests in the network agents. This is necessary
8376 // because some code later depends on this state to be correct, most prominently computing
8377 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09008378 for (final NetworkReassignment.RequestReassignment event :
8379 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008380 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8381 event.mOldNetworkRequest, event.mNewNetworkRequest,
8382 event.mOldNetwork, event.mNewNetwork,
8383 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09008384 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008385
James Mattise3ef1912020-12-20 11:09:58 -08008386 // Process default network changes if applicable.
8387 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008388
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008389 // Notify requested networks are available after the default net is switched, but
8390 // before LegacyTypeTracker sends legacy broadcasts
8391 for (final NetworkReassignment.RequestReassignment event :
8392 changes.getRequestReassignments()) {
8393 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008394 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008395 } else {
James Mattisa076c532020-12-02 14:12:41 -08008396 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008397 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008398 }
8399 }
8400
junyulai0ac374f2020-12-14 18:41:52 +08008401 // Update the inactivity state before processing listen callbacks, because the background
8402 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008403 // just yet though, because they have to be sent after the listens are processed to keep
8404 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08008405 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09008406 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08008407 // Rematching may have altered the inactivity state of some networks, so update all
8408 // inactivity timers. updateInactivityState reads the state from the network agent
8409 // and does nothing if the state has not changed : the source of truth is controlled
8410 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8411 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08008412 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08008413 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008414 }
8415 }
8416
Chalard Jeanb10ab412019-12-11 14:12:30 +09008417 for (final NetworkAgentInfo nai : nais) {
8418 if (!nai.everConnected) continue;
8419 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008420 // Process listen requests and update capabilities if the background state has
8421 // changed for this network. For consistency with previous behavior, send onLost
8422 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09008423 processNewlyLostListenRequests(nai);
8424 if (oldBackground != nai.isBackgroundNetwork()) {
8425 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008426 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09008427 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008428 }
8429
junyulai0ac374f2020-12-14 18:41:52 +08008430 for (final NetworkAgentInfo nai : inactiveNetworks) {
8431 // For nascent networks, if connecting with no foreground request, skip broadcasting
8432 // LOSING for backward compatibility. This is typical when mobile data connected while
8433 // wifi connected with mobile data always-on enabled.
8434 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008435 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008436 }
8437
James Mattise3ef1912020-12-20 11:09:58 -08008438 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09008439
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008440 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008441 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008442 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08008443 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008444 // This network has active linger timers and no requests, but is not
8445 // lingering. Linger it.
8446 //
8447 // One way (the only way?) this can happen if this network is unvalidated
8448 // and became unneeded due to another network improving its score to the
8449 // point where this network will no longer be able to satisfy any requests
8450 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08008451 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008452 notifyNetworkLosing(nai, now);
8453 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09008454 } else {
Chalard Jean49707572019-12-10 21:07:02 +09008455 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09008456 teardownUnneededNetwork(nai);
8457 }
8458 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04008459 }
8460 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008461
Chalard Jean62edfd82019-12-02 18:39:29 +09008462 /**
8463 * Apply a change in background state resulting from rematching networks with requests.
8464 *
8465 * During rematch, a network may change background states by starting to satisfy or stopping
8466 * to satisfy a foreground request. Listens don't count for this. When a network changes
8467 * background states, its capabilities need to be updated and callbacks fired for the
8468 * capability change.
8469 *
8470 * @param nai The network that changed background states
8471 */
8472 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8473 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8474 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8475 updateNetworkPermissions(nai, newNc);
8476 nai.getAndSetNetworkCapabilities(newNc);
8477 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8478 }
8479
Chalard Jeanf0344532019-11-19 19:23:38 +09008480 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08008481 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008482 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09008483 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8484 changes.getReassignment(mDefaultRequest);
8485 final NetworkAgentInfo oldDefaultNetwork =
8486 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8487 final NetworkAgentInfo newDefaultNetwork =
8488 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08008489
Chalard Jean5b409c72021-02-04 13:12:59 +09008490 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008491 // Maintain the illusion : since the legacy API only understands one network at a time,
8492 // if the default network changed, apps should see a disconnected broadcast for the
8493 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09008494 if (oldDefaultNetwork != null) {
8495 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8496 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008497 }
Chalard Jean5b409c72021-02-04 13:12:59 +09008498 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008499 // The new default network can be newly null if and only if the old default
8500 // network doesn't satisfy the default request any more because it lost a
8501 // capability.
Chalard Jean5b409c72021-02-04 13:12:59 +09008502 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08008503 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09008504 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008505 }
8506 }
8507
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008508 // Now that all the callbacks have been sent, send the legacy network broadcasts
8509 // as needed. This is necessary so that legacy requests correctly bind dns
8510 // requests to this network. The legacy users are listening for this broadcast
8511 // and will generally do a dns request so they can ensureRouteToHost and if
8512 // they do that before the callbacks happen they'll use the default network.
8513 //
8514 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8515 // callbacks, but if apps can receive the broadcast before the callback, they still might
8516 // have an inconsistent view of networking.
8517 //
8518 // This *does* introduce a race where if the user uses the new api
8519 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8520 // they may get old info. Reverse this after the old startUsing api is removed.
8521 // This is on top of the multiple intent sequencing referenced in the todo above.
8522 for (NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008523 if (nai.everConnected) {
8524 addNetworkToLegacyTypeTracker(nai);
8525 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08008526 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008527 }
8528
Chalard Jean0354d8c2021-01-12 10:58:56 +09008529 private void issueNetworkNeeds() {
8530 ensureRunningOnConnectivityServiceThread();
8531 for (final NetworkOfferInfo noi : mNetworkOffers) {
8532 issueNetworkNeeds(noi);
8533 }
8534 }
8535
8536 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8537 ensureRunningOnConnectivityServiceThread();
8538 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8539 informOffer(nri, noi.offer, mNetworkRanker);
8540 }
8541 }
8542
8543 /**
8544 * Inform a NetworkOffer about any new situation of a request.
8545 *
8546 * This function handles updates to offers. A number of events may happen that require
8547 * updating the registrant for this offer about the situation :
8548 * • The offer itself was updated. This may lead the offer to no longer being able
8549 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8550 * or conversely being strengthened enough to beat the satisfier (and therefore
8551 * start being needed)
8552 * • The network satisfying a request changed (including cases where the request
8553 * starts or stops being satisfied). The new network may be a stronger or weaker
8554 * match than the old one, possibly affecting whether the offer is needed.
8555 * • The network satisfying a request updated their score. This may lead the offer
8556 * to no longer be able to beat it if the current satisfier got better, or
8557 * conversely start being a good choice if the current satisfier got weaker.
8558 *
8559 * @param nri The request
8560 * @param offer The offer. This may be an updated offer.
8561 */
8562 private static void informOffer(@NonNull NetworkRequestInfo nri,
8563 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
8564 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
8565 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09008566
8567 // Multi-layer requests have a currently active request, the one being satisfied.
8568 // Since the system will try to bring up a better network than is currently satisfying
8569 // the request, NetworkProviders need to be told the offers matching the requests *above*
8570 // the currently satisfied one are needed, that the ones *below* the satisfied one are
8571 // not needed, and the offer is needed for the active request iff the offer can beat
8572 // the satisfier.
8573 // For non-multilayer requests, the logic above gracefully degenerates to only the
8574 // last case.
8575 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
8576 // providers that the offer is needed for this request, until the active request is found.
8577 // In a second phase, deal with the currently active request. In a third phase, inform
8578 // the providers that offer is unneeded for the remaining requests.
8579
8580 // First phase : inform providers of all requests above the active request.
8581 int i;
8582 for (i = 0; nri.mRequests.size() > i; ++i) {
8583 final NetworkRequest request = nri.mRequests.get(i);
8584 if (activeRequest == request) break; // Found the active request : go to phase 2
8585 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8586 // Since this request is higher-priority than the one currently satisfied, if the
8587 // offer can satisfy it, the provider should try and bring up the network for sure ;
8588 // no need to even ask the ranker – an offer that can satisfy is always better than
8589 // no network. Hence tell the provider so unless it already knew.
8590 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
8591 offer.onNetworkNeeded(request);
8592 }
8593 }
8594
8595 // Second phase : deal with the active request (if any)
8596 if (null != activeRequest && activeRequest.isRequest()) {
8597 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00008598 // If an offer can satisfy the request, it is considered needed if it is currently
8599 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09008600 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00008601 && satisfier.factorySerialNumber == offer.providerId
8602 && activeRequest.canBeSatisfiedBy(offer.caps);
8603 final boolean newNeeded = currentlyServing
8604 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008605 if (newNeeded != oldNeeded) {
8606 if (newNeeded) {
8607 offer.onNetworkNeeded(activeRequest);
8608 } else {
8609 // The offer used to be able to beat the satisfier. Now it can't.
8610 offer.onNetworkUnneeded(activeRequest);
8611 }
8612 }
8613 }
8614
8615 // Third phase : inform the providers that the offer isn't needed for any request
8616 // below the active one.
8617 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
8618 final NetworkRequest request = nri.mRequests.get(i);
8619 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8620 // Since this request is lower-priority than the one currently satisfied, if the
8621 // offer can satisfy it, the provider should not try and bring up the network.
8622 // Hence tell the provider so unless it already knew.
8623 if (offer.neededFor(request)) {
8624 offer.onNetworkUnneeded(request);
8625 }
8626 }
8627 }
8628
Chalard Jean61c79252019-11-07 23:07:32 +09008629 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8630 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8631 NetworkRequest nr = nai.requestAt(i);
8632 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8633 // legacy type tracker filters out repeat adds
8634 mLegacyTypeTracker.add(nr.legacyType, nai);
8635 }
8636 }
8637
8638 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09008639 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09008640 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8641 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8642 if (nai.isVPN()) {
8643 mLegacyTypeTracker.add(TYPE_VPN, nai);
8644 }
8645 }
8646
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008647 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04008648 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittia8de5ca2014-12-17 11:14:42 +09008649 if (!nai.everValidated) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09008650 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04008651 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09008652 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008653
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008654 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008655 // Don't repeat publish.
8656 if (newInetCondition == mDefaultInetConditionPublished) return;
8657
8658 mDefaultInetConditionPublished = newInetCondition;
8659 sendInetConditionBroadcast(nai.networkInfo);
8660 }
8661
Chalard Jeand61375d2020-01-14 22:46:36 +09008662 @NonNull
8663 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8664 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008665 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09008666 final boolean suspended =
8667 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8668 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8669 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8670 // state. This is because the network could have been suspended before connecting,
8671 // or it could be disconnecting while being suspended, and in both these cases
8672 // the state should not be overridden. Note that the only detailed state that
8673 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8674 // worry about multiple different substates of CONNECTED.
8675 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8676 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08008677 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8678 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8679 // network agent is created, then goes to suspended, then goes out of suspended without
8680 // ever setting connected. Check if network agent is ever connected to update the state.
8681 newInfo.setDetailedState(nai.everConnected
8682 ? NetworkInfo.DetailedState.CONNECTED
8683 : NetworkInfo.DetailedState.CONNECTING,
8684 info.getReason(),
8685 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09008686 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008687 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09008688 return newInfo;
8689 }
8690
8691 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8692 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8693
Erik Kline99f301b2017-02-15 19:59:17 +09008694 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008695 NetworkInfo oldInfo = null;
8696 synchronized (networkAgent) {
8697 oldInfo = networkAgent.networkInfo;
8698 networkAgent.networkInfo = newInfo;
8699 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008700
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008701 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008702 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8703 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008704 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07008705
Robin Leea8c0b6e2016-05-01 23:00:00 +01008706 if (!networkAgent.created
8707 && (state == NetworkInfo.State.CONNECTED
8708 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008709
8710 // A network that has just connected has zero requests and is thus a foreground network.
8711 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8712
Luke Huangfdd11f82019-04-09 18:41:49 +08008713 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09008714 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008715 // Initialize the network's capabilities to their starting values according to the
8716 // underlying networks. This ensures that the capabilities are correct before
8717 // anything happens to the network.
8718 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09008719 }
Paul Jensen74940202014-08-04 12:21:19 -04008720 networkAgent.created = true;
Chiachang Wang3f6cc072021-03-24 18:39:17 +08008721 networkAgent.onNetworkCreated();
Robin Leea8c0b6e2016-05-01 23:00:00 +01008722 }
8723
8724 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
8725 networkAgent.everConnected = true;
8726
lucaslin45e639b2019-04-03 17:09:28 +08008727 // NetworkCapabilities need to be set before sending the private DNS config to
8728 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09008729 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
8730
Erik Kline9a62f012018-03-21 07:18:33 -07008731 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08008732 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
8733 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008734
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008735 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
8736 // command must be sent after updating LinkProperties to maximize chances of
8737 // NetworkMonitor seeing the correct LinkProperties when starting.
8738 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008739 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09008740 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008741 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09008742 networkAgent.networkMonitor().notifyNetworkConnected(
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008743 new LinkProperties(networkAgent.linkProperties,
8744 true /* parcelSensitiveFields */),
8745 networkAgent.networkCapabilities);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09008746 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008747
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008748 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
8749 // be communicated to a particular NetworkAgent depends only on the network's immutable,
8750 // capabilities, so it only needs to be done once on initial connect, not every time the
8751 // network's capabilities change. Note that we do this before rematching the network,
8752 // so we could decide to tear it down immediately afterwards. That's fine though - on
8753 // disconnection NetworkAgents should stop any signal strength monitoring they have been
8754 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09008755 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008756
junyulai0ac374f2020-12-14 18:41:52 +08008757 // Before first rematching networks, put an inactivity timer without any request, this
8758 // allows {@code updateInactivityState} to update the state accordingly and prevent
8759 // tearing down for any {@code unneeded} evaluation in this period.
8760 // Note that the timer will not be rescheduled since the expiry time is
8761 // fixed after connection regardless of the network satisfying other requests or not.
8762 // But it will be removed as soon as the network satisfies a request for the first time.
8763 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
8764 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08008765 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008766
Paul Jensen05e85ee2014-09-11 11:00:39 -04008767 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008768 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008769
8770 // This has to happen after matching the requests, because callbacks are just requests.
8771 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008772 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008773 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04008774 if (networkAgent.isVPN()) {
Chalard Jeanb2a49912018-01-16 18:43:05 +09008775 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04008776 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09008777 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00008778 if (networkAgent.isVPN()) {
8779 // As the active or bound network changes for apps, broadcast the default proxy, as
8780 // apps may need to update their proxy data. This is called after disconnecting from
8781 // VPN to make sure we do not broadcast the old proxy data.
8782 // TODO(b/122649188): send the broadcast only to VPN users.
8783 mProxyTracker.sendProxyBroadcast();
8784 }
Yintang Gu5014b522019-06-18 14:24:32 +08008785 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
8786 state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008787 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008788 }
8789 }
8790
Chalard Jean28018572020-12-21 18:36:52 +09008791 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09008792 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
8793 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008794 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07008795 }
8796
Erik Kline99f301b2017-02-15 19:59:17 +09008797 // Notify only this one new request of the current state. Transfer all the
8798 // current state by calling NetworkCapabilities and LinkProperties callbacks
8799 // so that callers can be guaranteed to have as close to atomicity in state
8800 // transfer as can be supported by this current API.
8801 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07008802 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09008803 if (nri.mPendingIntent != null) {
8804 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
8805 // Attempt no subsequent state pushes where intents are involved.
8806 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008807 }
Erik Kline99f301b2017-02-15 19:59:17 +09008808
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008809 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08008810 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008811 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
8812 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
8813 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08008814 }
8815
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008816 // Notify the requests on this NAI that the network is now lingered.
8817 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08008818 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008819 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
8820 }
8821
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008822 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
8823 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
8824 return vpnBlocked
8825 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
8826 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
8827 }
8828
8829 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
8830 if (blockedReasons == BLOCKED_REASON_NONE) {
8831 mUidBlockedReasons.delete(uid);
8832 } else {
8833 mUidBlockedReasons.put(uid, blockedReasons);
8834 }
8835 }
8836
junyulaif2c67e42018-08-07 19:50:45 +08008837 /**
8838 * Notify of the blocked state apps with a registered callback matching a given NAI.
8839 *
8840 * Unlike other callbacks, blocked status is different between each individual uid. So for
8841 * any given nai, all requests need to be considered according to the uid who filed it.
8842 *
8843 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008844 * @param oldMetered True if the previous network capabilities were metered.
8845 * @param newMetered True if the current network capabilities are metered.
8846 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
8847 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08008848 */
8849 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00008850 boolean newMetered, List<UidRange> oldBlockedUidRanges,
8851 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08008852
8853 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8854 NetworkRequest nr = nai.requestAt(i);
8855 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008856
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008857 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8858 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
8859 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008860 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008861 : oldVpnBlocked;
8862
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008863 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
8864 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
8865 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08008866 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008867 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08008868 }
8869 }
8870 }
8871
8872 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00008873 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08008874 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00008875 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08008876 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008877 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008878 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08008879 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008880 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00008881
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008882 final int oldBlockedState = getBlockedState(
8883 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
8884 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
8885 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08008886 continue;
junyulaif2c67e42018-08-07 19:50:45 +08008887 }
junyulaif2c67e42018-08-07 19:50:45 +08008888 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8889 NetworkRequest nr = nai.requestAt(i);
8890 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008891 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008892 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8893 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08008894 }
8895 }
8896 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008897 }
8898
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008899 @VisibleForTesting
8900 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09008901 // The NetworkInfo we actually send out has no bearing on the real
8902 // state of affairs. For example, if the default connection is mobile,
8903 // and a request for HIPRI has just gone away, we need to pretend that
8904 // HIPRI has just disconnected. So we need to set the type to HIPRI and
8905 // the state to DISCONNECTED, even though the network is of type MOBILE
8906 // and is still connected.
8907 NetworkInfo info = new NetworkInfo(nai.networkInfo);
8908 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09008909 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008910 if (state != DetailedState.DISCONNECTED) {
8911 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09008912 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008913 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008914 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07008915 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
8916 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
8917 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
8918 if (info.isFailover()) {
8919 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
8920 nai.networkInfo.setFailover(false);
8921 }
8922 if (info.getReason() != null) {
8923 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
8924 }
8925 if (info.getExtraInfo() != null) {
8926 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
8927 }
8928 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09008929 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08008930 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07008931 if (newDefaultAgent != null) {
8932 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
8933 newDefaultAgent.networkInfo);
8934 } else {
8935 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
8936 }
8937 }
8938 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
8939 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09008940 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008941 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09008942 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008943 }
8944 }
8945 }
8946
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008947 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008948 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008949 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09008950 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09008951 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008952 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
8953 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008954 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8955 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008956 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008957 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008958 } else {
8959 sendPendingIntentForRequest(nri, networkAgent, notifyType);
8960 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008961 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008962 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07008963
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008964 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
8965 notifyNetworkCallbacks(networkAgent, notifyType, 0);
8966 }
8967
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008968 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09008969 * Returns the list of all interfaces that could be used by network traffic that does not
8970 * explicitly specify a network. This includes the default network, but also all VPNs that are
8971 * currently connected.
8972 *
8973 * Must be called on the handler thread.
8974 */
junyulaie7c7d2a2021-01-26 15:29:15 +08008975 @NonNull
8976 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08008977 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08008978 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08008979 final Set<Integer> activeNetIds = new ArraySet<>();
8980 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8981 if (nri.isBeingSatisfied()) {
8982 activeNetIds.add(nri.getSatisfier().network().netId);
8983 }
8984 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008985 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattis2516da32021-01-31 17:06:19 -08008986 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09008987 defaultNetworks.add(nai.network);
8988 }
8989 }
junyulaie7c7d2a2021-01-26 15:29:15 +08008990 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09008991 }
8992
8993 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09008994 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
8995 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008996 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08008997 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08008998 ensureRunningOnConnectivityServiceThread();
8999 String activeIface = null;
9000 LinkProperties activeLinkProperties = getActiveLinkProperties();
9001 if (activeLinkProperties != null) {
9002 activeIface = activeLinkProperties.getInterfaceName();
9003 }
Benedict Wong9308cd32019-06-12 17:46:31 +00009004
junyulai2050bed2021-01-23 09:46:34 +08009005 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009006 try {
junyulaide41fc22021-01-22 22:46:01 +08009007 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
junyulai69114da2021-03-05 14:46:25 +08009008 for (final NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaide41fc22021-01-22 22:46:01 +08009009 snapshots.add(snapshot);
9010 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009011 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
9012 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009013 } catch (Exception ignored) {
9014 }
9015 }
9016
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07009017 @Override
Udam Sainicd645462016-01-04 12:16:14 -08009018 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08009019 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009020 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009021 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009022
9023 if (!TextUtils.isEmpty(settingUrl)) {
9024 return settingUrl;
9025 }
9026
9027 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009028 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009029 if (!TextUtils.isEmpty(settingUrl)) {
9030 return settingUrl;
9031 }
9032
9033 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009034 }
9035
9036 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009037 public void startNattKeepalive(Network network, int intervalSeconds,
9038 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009039 enforceKeepalivePermission();
9040 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009041 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai070f9ff2019-01-16 20:23:34 +08009042 intervalSeconds, cb,
junyulai011b1f12019-01-03 18:50:15 +08009043 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009044 }
9045
9046 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009047 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009048 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulaid05a1922019-01-15 11:32:44 +08009049 String dstAddr) {
Josh Gao461a1222020-06-16 15:58:11 -07009050 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009051 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009052 mKeepaliveTracker.startNattKeepalive(
9053 getNetworkAgentInfoForNetwork(network), fd, resourceId,
9054 intervalSeconds, cb,
9055 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
9056 } finally {
9057 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9058 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009059 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9060 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009061 }
9062 }
junyulaid05a1922019-01-15 11:32:44 +08009063 }
9064
9065 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009066 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009067 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009068 try {
9069 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08009070 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009071 mKeepaliveTracker.startTcpKeepalive(
9072 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
9073 } finally {
9074 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9075 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009076 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9077 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009078 }
9079 }
junyulai0835a1e2019-01-08 20:04:33 +08009080 }
9081
9082 @Override
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009083 public void stopKeepalive(Network network, int slot) {
9084 mHandler.sendMessage(mHandler.obtainMessage(
junyulai011b1f12019-01-03 18:50:15 +08009085 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009086 }
9087
9088 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07009089 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08009090 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07009091
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009092 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08009093 final long token = Binder.clearCallingIdentity();
9094 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009095 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
9096 UserHandle.getUserHandleForUid(uid))) {
9097 return;
9098 }
9099
Heemin Seogdb8489d2019-06-12 09:21:44 -07009100 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
9101 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009102
9103 // Turn airplane mode off
9104 setAirplaneMode(false);
9105
9106 // restore private DNS settings to default mode (opportunistic)
9107 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
9108 UserHandle.getUserHandleForUid(uid))) {
9109 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
9110 PRIVATE_DNS_MODE_OPPORTUNISTIC);
9111 }
9112
9113 Settings.Global.putString(mContext.getContentResolver(),
9114 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08009115 } finally {
9116 Binder.restoreCallingIdentity(token);
9117 }
Stuart Scottd5463642015-04-02 18:00:02 -07009118 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04009119
Ricky Wai7097cc92018-01-23 04:09:45 +00009120 @Override
9121 public byte[] getNetworkWatchlistConfigHash() {
9122 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
9123 if (nwm == null) {
9124 loge("Unable to get NetworkWatchlistManager");
9125 return null;
9126 }
9127 // Redirect it to network watchlist service to access watchlist file and calculate hash.
9128 return nwm.getWatchlistConfigHash();
9129 }
9130
Hugo Benichibe0c7652016-05-31 16:28:06 +09009131 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09009132 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08009133 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09009134 }
Hugo Benichif4210292017-04-21 15:07:12 +09009135
9136 private static boolean toBool(int encodedBoolean) {
9137 return encodedBoolean != 0; // Only 0 means false.
9138 }
9139
9140 private static int encodeBool(boolean b) {
9141 return b ? 1 : 0;
9142 }
mswest4632928412018-03-12 10:34:34 -07009143
9144 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009145 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
9146 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
9147 @NonNull String[] args) {
9148 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
9149 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07009150 }
9151
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009152 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07009153 @Override
9154 public int onCommand(String cmd) {
9155 if (cmd == null) {
9156 return handleDefaultCommands(cmd);
9157 }
9158 final PrintWriter pw = getOutPrintWriter();
9159 try {
9160 switch (cmd) {
9161 case "airplane-mode":
9162 final String action = getNextArg();
9163 if ("enable".equals(action)) {
9164 setAirplaneMode(true);
9165 return 0;
9166 } else if ("disable".equals(action)) {
9167 setAirplaneMode(false);
9168 return 0;
9169 } else if (action == null) {
9170 final ContentResolver cr = mContext.getContentResolver();
9171 final int enabled = Settings.Global.getInt(cr,
9172 Settings.Global.AIRPLANE_MODE_ON);
9173 pw.println(enabled == 0 ? "disabled" : "enabled");
9174 return 0;
9175 } else {
9176 onHelp();
9177 return -1;
9178 }
9179 default:
9180 return handleDefaultCommands(cmd);
9181 }
9182 } catch (Exception e) {
9183 pw.println(e);
9184 }
9185 return -1;
9186 }
9187
9188 @Override
9189 public void onHelp() {
9190 PrintWriter pw = getOutPrintWriter();
9191 pw.println("Connectivity service commands:");
9192 pw.println(" help");
9193 pw.println(" Print this help text.");
9194 pw.println(" airplane-mode [enable|disable]");
9195 pw.println(" Turn airplane mode on or off.");
9196 pw.println(" airplane-mode");
9197 pw.println(" Get airplane mode.");
9198 }
9199 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009200
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09009201 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009202 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
9203 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
9204 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +08009205 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009206 }
9207
9208 /**
9209 * @param connectionInfo the connection to resolve.
9210 * @return {@code uid} if the connection is found and the app has permission to observe it
9211 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
9212 * connection is not found.
9213 */
9214 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009215 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
9216 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
9217 }
9218
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09009219 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009220 connectionInfo.local, connectionInfo.remote);
9221
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009222 if (uid == INVALID_UID) return uid; // Not found.
9223
9224 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
9225 // VPN, if any, that applies to the UID that owns the connection.
9226 if (checkNetworkStackPermission()) return uid;
9227
9228 final NetworkAgentInfo vpn = getVpnForUid(uid);
9229 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09009230 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009231 return INVALID_UID;
9232 }
9233
9234 return uid;
9235 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +00009236
Benedict Wong493e04b2018-11-09 14:45:34 -08009237 /**
9238 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
9239 *
9240 * <p>The TestNetworkService must be run in the system server due to TUN creation.
9241 */
9242 @Override
9243 public IBinder startOrGetTestNetworkService() {
9244 synchronized (mTNSLock) {
9245 TestNetworkService.enforceTestNetworkPermissions(mContext);
9246
9247 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +08009248 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -08009249 }
9250
9251 return mTNS;
9252 }
9253 }
Cody Kestingd199a9d2019-12-17 12:55:28 -08009254
Cody Kesting73708bf2019-12-18 10:57:50 -08009255 /**
9256 * Handler used for managing all Connectivity Diagnostics related functions.
9257 *
9258 * @see android.net.ConnectivityDiagnosticsManager
9259 *
9260 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9261 */
9262 @VisibleForTesting
9263 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009264 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9265
Cody Kesting73708bf2019-12-18 10:57:50 -08009266 /**
9267 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9268 * android.net.ConnectivityDiagnosticsManager}.
9269 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9270 * NetworkRequestInfo to be registered
9271 */
9272 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9273
9274 /**
9275 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9276 * android.net.ConnectivityDiagnosticsManager}.
9277 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9278 * arg1 = the uid of the caller
9279 */
9280 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9281
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009282 /**
9283 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
9284 * after processing {@link #EVENT_NETWORK_TESTED} events.
9285 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9286 * NetworkMonitor.
9287 * data = PersistableBundle of extras passed from NetworkMonitor.
9288 *
9289 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
9290 */
9291 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
9292
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009293 /**
9294 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9295 * been detected on the network.
9296 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9297 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9298 * arg2 = NetID.
9299 * data = PersistableBundle of extras passed from NetworkMonitor.
9300 */
9301 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9302
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009303 /**
9304 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9305 * the platform. This event will invoke {@link
9306 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9307 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -07009308 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009309 */
9310 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9311
Cody Kesting73708bf2019-12-18 10:57:50 -08009312 private ConnectivityDiagnosticsHandler(Looper looper) {
9313 super(looper);
9314 }
9315
9316 @Override
9317 public void handleMessage(Message msg) {
9318 switch (msg.what) {
9319 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9320 handleRegisterConnectivityDiagnosticsCallback(
9321 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9322 break;
9323 }
9324 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9325 handleUnregisterConnectivityDiagnosticsCallback(
9326 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9327 break;
9328 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009329 case EVENT_NETWORK_TESTED: {
9330 final ConnectivityReportEvent reportEvent =
9331 (ConnectivityReportEvent) msg.obj;
9332
Aaron Huang959d3642021-01-21 15:47:41 +08009333 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009334 break;
9335 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009336 case EVENT_DATA_STALL_SUSPECTED: {
9337 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +08009338 final Pair<Long, PersistableBundle> arg =
9339 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009340 if (nai == null) break;
9341
Aaron Huang959d3642021-01-21 15:47:41 +08009342 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009343 break;
9344 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009345 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -07009346 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009347 break;
9348 }
9349 default: {
9350 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9351 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009352 }
9353 }
9354 }
9355
9356 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9357 @VisibleForTesting
9358 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9359 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9360 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009361 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009362
9363 @VisibleForTesting
9364 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009365 @NonNull IConnectivityDiagnosticsCallback cb,
9366 @NonNull NetworkRequestInfo nri,
9367 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009368 mCb = cb;
9369 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009370 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009371 }
9372
9373 @Override
9374 public void binderDied() {
9375 log("ConnectivityDiagnosticsCallback IBinder died.");
9376 unregisterConnectivityDiagnosticsCallback(mCb);
9377 }
9378 }
9379
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009380 /**
9381 * Class used for sending information from {@link
9382 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9383 */
9384 private static class NetworkTestedResults {
9385 private final int mNetId;
9386 private final int mTestResult;
9387 private final long mTimestampMillis;
9388 @Nullable private final String mRedirectUrl;
9389
9390 private NetworkTestedResults(
9391 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9392 mNetId = netId;
9393 mTestResult = testResult;
9394 mTimestampMillis = timestampMillis;
9395 mRedirectUrl = redirectUrl;
9396 }
9397 }
9398
9399 /**
9400 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9401 * ConnectivityDiagnosticsHandler}.
9402 */
9403 private static class ConnectivityReportEvent {
9404 private final long mTimestampMillis;
9405 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +08009406 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009407
Aaron Huang959d3642021-01-21 15:47:41 +08009408 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9409 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009410 mTimestampMillis = timestampMillis;
9411 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +08009412 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009413 }
9414 }
9415
Cody Kestingf1120be2020-08-03 18:01:40 -07009416 /**
9417 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
9418 * ConnectivityDiagnosticsHandler}.
9419 */
9420 private static class ReportedNetworkConnectivityInfo {
9421 public final boolean hasConnectivity;
9422 public final boolean isNetworkRevalidating;
9423 public final int reporterUid;
9424 @NonNull public final NetworkAgentInfo nai;
9425
9426 private ReportedNetworkConnectivityInfo(
9427 boolean hasConnectivity,
9428 boolean isNetworkRevalidating,
9429 int reporterUid,
9430 @NonNull NetworkAgentInfo nai) {
9431 this.hasConnectivity = hasConnectivity;
9432 this.isNetworkRevalidating = isNetworkRevalidating;
9433 this.reporterUid = reporterUid;
9434 this.nai = nai;
9435 }
9436 }
9437
Cody Kesting73708bf2019-12-18 10:57:50 -08009438 private void handleRegisterConnectivityDiagnosticsCallback(
9439 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9440 ensureRunningOnConnectivityServiceThread();
9441
9442 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -08009443 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009444 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9445
James Mattis64b8b0f2020-11-24 17:40:49 -08009446 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9447 // confusing for these networks to change when an NRI is satisfied in another layer.
9448 if (nri.isMultilayerRequest()) {
9449 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9450 + "network requests.");
9451 }
9452
Cody Kesting73708bf2019-12-18 10:57:50 -08009453 // This means that the client registered the same callback multiple times. Do
9454 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -08009455 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009456 if (VDBG) log("Diagnostics callback is already registered");
9457
9458 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9459 // incremented when the NetworkRequestInfo is created as part of
9460 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009461 nri.decrementRequestCount();
Cody Kesting73708bf2019-12-18 10:57:50 -08009462 return;
9463 }
9464
Cody Kesting31f1ff62020-03-05 10:46:02 -08009465 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -08009466
9467 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -08009468 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009469 } catch (RemoteException e) {
9470 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -08009471 return;
9472 }
9473
9474 // Once registered, provide ConnectivityReports for matching Networks
9475 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9476 synchronized (mNetworkForNetId) {
9477 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9478 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -08009479 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9480 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -08009481 matchingNetworks.add(nai);
9482 }
9483 }
9484 }
9485 for (final NetworkAgentInfo nai : matchingNetworks) {
9486 final ConnectivityReport report = nai.getConnectivityReport();
9487 if (report == null) {
9488 continue;
9489 }
9490 if (!checkConnectivityDiagnosticsPermissions(
9491 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9492 continue;
9493 }
9494
9495 try {
9496 cb.onConnectivityReportAvailable(report);
9497 } catch (RemoteException e) {
9498 // Exception while sending the ConnectivityReport. Move on to the next network.
9499 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009500 }
9501 }
9502
9503 private void handleUnregisterConnectivityDiagnosticsCallback(
9504 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9505 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009506 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009507
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009508 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9509 mConnectivityDiagnosticsCallbacks.remove(iCb);
9510 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009511 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9512 return;
9513 }
9514
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009515 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -08009516
Cody Kesting70fa2b22020-12-02 12:16:56 -08009517 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9518 // (if the Binder died)
9519 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9520 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -08009521 return;
9522 }
9523
Cody Kesting46cb1672020-03-04 13:35:20 -08009524 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9525 // incremented when the NetworkRequestInfo is created as part of
9526 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009527 nri.decrementRequestCount();
Cody Kesting46cb1672020-03-04 13:35:20 -08009528
Cody Kesting31f1ff62020-03-05 10:46:02 -08009529 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009530 }
9531
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009532 private void handleNetworkTestedWithExtras(
9533 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9534 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -08009535 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009536 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009537 final ConnectivityReport report =
9538 new ConnectivityReport(
9539 reportEvent.mNai.network,
9540 reportEvent.mTimestampMillis,
9541 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009542 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009543 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -08009544 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -07009545
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009546 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009547 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009548 for (final IConnectivityDiagnosticsCallback cb : results) {
9549 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -08009550 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009551 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -07009552 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009553 }
9554 }
9555 }
9556
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009557 private void handleDataStallSuspected(
9558 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9559 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -08009560 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009561 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009562 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -08009563 new DataStallReport(
9564 nai.network,
9565 timestampMillis,
9566 detectionMethod,
9567 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009568 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -08009569 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009570 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009571 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009572 for (final IConnectivityDiagnosticsCallback cb : results) {
9573 try {
9574 cb.onDataStallSuspected(report);
9575 } catch (RemoteException ex) {
9576 loge("Error invoking onDataStallSuspected", ex);
9577 }
9578 }
9579 }
9580
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009581 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -07009582 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
9583 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
9584 final ConnectivityReport cachedReport = nai.getConnectivityReport();
9585
9586 // If the Network is being re-validated as a result of this call to
9587 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
9588 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009589 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009590 getMatchingPermissionedCallbacks(
9591 nai,
9592 reportedNetworkConnectivityInfo.isNetworkRevalidating
9593 ? Process.INVALID_UID
9594 : reportedNetworkConnectivityInfo.reporterUid);
9595
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009596 for (final IConnectivityDiagnosticsCallback cb : results) {
9597 try {
Cody Kestingf1120be2020-08-03 18:01:40 -07009598 cb.onNetworkConnectivityReported(
9599 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009600 } catch (RemoteException ex) {
9601 loge("Error invoking onNetworkConnectivityReported", ex);
9602 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009603
9604 // If the Network isn't re-validating, also provide the cached report. If there is no
9605 // cached report, the Network is still being validated and a report will be sent once
9606 // validation is complete. Note that networks which never undergo validation will still
9607 // have a cached ConnectivityReport with RESULT_SKIPPED.
9608 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
9609 try {
9610 cb.onConnectivityReportAvailable(cachedReport);
9611 } catch (RemoteException ex) {
9612 loge("Error invoking onConnectivityReportAvailable", ex);
9613 }
9614 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009615 }
9616 }
9617
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009618 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +09009619 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9620 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009621 sanitized.setUids(null);
9622 sanitized.setAdministratorUids(new int[0]);
9623 sanitized.setOwnerUid(Process.INVALID_UID);
9624 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -08009625 }
9626
Cody Kestingf1120be2020-08-03 18:01:40 -07009627 /**
9628 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
9629 *
9630 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
9631 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009632 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -07009633 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009634 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009635 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009636 mConnectivityDiagnosticsCallbacks.entrySet()) {
9637 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9638 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -07009639
James Mattis64b8b0f2020-11-24 17:40:49 -08009640 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -07009641 if (!nai.satisfies(nri.mRequests.get(0))) {
9642 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009643 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009644
9645 // UID for this callback must either be:
9646 // - INVALID_UID (which sends callbacks to all UIDs), or
9647 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
9648 // notified as a result)
9649 if (uid != Process.INVALID_UID && uid != nri.mUid) {
9650 continue;
9651 }
9652
9653 if (!checkConnectivityDiagnosticsPermissions(
9654 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9655 continue;
9656 }
9657
9658 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009659 }
9660 return results;
9661 }
9662
Cody Kesting7474f672021-05-11 14:22:40 -07009663 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
9664 @NonNull NetworkAgentInfo nai) {
9665 // TODO(b/188483916): replace with a transport-agnostic location-aware check
9666 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
9667 }
9668
Cody Kesting160ef392021-05-05 13:17:22 -07009669 private boolean hasLocationPermission(String packageName, int uid) {
9670 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9671 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9672 // call in a try-catch.
9673 try {
9674 if (!mLocationPermissionChecker.checkLocationPermission(
9675 packageName, null /* featureId */, uid, null /* message */)) {
9676 return false;
9677 }
9678 } catch (SecurityException e) {
9679 return false;
9680 }
9681
9682 return true;
9683 }
9684
9685 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
9686 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +09009687 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -07009688 && virtual.networkCapabilities.getOwnerUid() == uid
9689 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
9690 return true;
9691 }
9692 }
9693
9694 return false;
9695 }
9696
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009697 @VisibleForTesting
9698 boolean checkConnectivityDiagnosticsPermissions(
9699 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9700 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9701 return true;
9702 }
9703
Cody Kesting160ef392021-05-05 13:17:22 -07009704 // Administrator UIDs also contains the Owner UID
9705 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
9706 if (!CollectionUtils.contains(administratorUids, callbackUid)
9707 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009708 return false;
9709 }
9710
Cody Kesting7474f672021-05-11 14:22:40 -07009711 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
9712 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009713 }
9714
Cody Kestingd199a9d2019-12-17 12:55:28 -08009715 @Override
9716 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009717 @NonNull IConnectivityDiagnosticsCallback callback,
9718 @NonNull NetworkRequest request,
9719 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -07009720 Objects.requireNonNull(callback, "callback must not be null");
9721 Objects.requireNonNull(request, "request must not be null");
9722 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
9723
Cody Kesting73708bf2019-12-18 10:57:50 -08009724 if (request.legacyType != TYPE_NONE) {
9725 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
9726 + " Please use NetworkCapabilities instead.");
9727 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009728 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -08009729 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009730
9731 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
9732 // and administrator uids to be safe.
9733 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08009734 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009735
9736 final NetworkRequest requestWithId =
9737 new NetworkRequest(
9738 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
9739
9740 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
9741 //
9742 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
9743 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
9744 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009745 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -08009746 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009747 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009748
9749 mConnectivityDiagnosticsHandler.sendMessage(
9750 mConnectivityDiagnosticsHandler.obtainMessage(
9751 ConnectivityDiagnosticsHandler
9752 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9753 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -08009754 }
9755
9756 @Override
9757 public void unregisterConnectivityDiagnosticsCallback(
9758 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +08009759 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -08009760 mConnectivityDiagnosticsHandler.sendMessage(
9761 mConnectivityDiagnosticsHandler.obtainMessage(
9762 ConnectivityDiagnosticsHandler
9763 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009764 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -08009765 0,
9766 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -08009767 }
Cody Kestingf53a0752020-04-15 12:33:28 -07009768
9769 @Override
9770 public void simulateDataStall(int detectionMethod, long timestampMillis,
9771 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -07009772 Objects.requireNonNull(network, "network must not be null");
9773 Objects.requireNonNull(extras, "extras must not be null");
9774
Cody Kestingf53a0752020-04-15 12:33:28 -07009775 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
9776 android.Manifest.permission.NETWORK_STACK);
9777 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
9778 if (!nc.hasTransport(TRANSPORT_TEST)) {
9779 throw new SecurityException("Data Stall simluation is only possible for test networks");
9780 }
9781
9782 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009783 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -07009784 throw new SecurityException("Data Stall simulation is only possible for network "
9785 + "creators");
9786 }
9787
Cody Kesting652e3ec2020-05-21 12:08:21 -07009788 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
9789 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
9790 // Data Stall information as a DataStallReportParcelable and passing to
9791 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
9792 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -07009793 final DataStallReportParcelable p = new DataStallReportParcelable();
9794 p.timestampMillis = timestampMillis;
9795 p.detectionMethod = detectionMethod;
9796
9797 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
9798 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
9799 }
9800 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
9801 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
9802 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
9803 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
9804 }
9805
Serik Beketayevec8ad212020-12-07 22:43:07 -08009806 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -07009807 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009808
lucaslin66f44212021-02-23 01:12:55 +08009809 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
9810 @Override
lucaslin87b58aa2021-02-25 15:10:29 +08009811 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +08009812 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +08009813 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +08009814 }
lucaslin37a16d92021-01-21 19:48:09 +08009815
9816 @Override
9817 public void onInterfaceLinkStateChanged(String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +08009818 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +08009819 nai.clatd.interfaceLinkStateChanged(iface, up);
9820 }
9821 }
9822
9823 @Override
9824 public void onInterfaceRemoved(String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +08009825 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +08009826 nai.clatd.interfaceRemoved(iface);
9827 }
lucaslin66f44212021-02-23 01:12:55 +08009828 }
9829 }
9830
lucaslin1a8b4c62021-01-21 02:02:55 +08009831 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
9832
9833 /**
9834 * Class used for updating network activity tracking with netd and notify network activity
9835 * changes.
9836 */
9837 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +08009838 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +08009839 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +08009840 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +08009841 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
9842 new RemoteCallbackList<>();
9843 // Indicate the current system default network activity is active or not.
9844 @GuardedBy("mActiveIdleTimers")
9845 private boolean mNetworkActive;
9846 @GuardedBy("mActiveIdleTimers")
9847 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
9848 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +08009849
lucaslin1193a5d2021-01-21 02:04:15 +08009850 private class IdleTimerParams {
9851 public final int timeout;
9852 public final int transportType;
9853
9854 IdleTimerParams(int timeout, int transport) {
9855 this.timeout = timeout;
9856 this.transportType = transport;
9857 }
9858 }
9859
9860 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +08009861 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +08009862 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +08009863 mNetd = netd;
9864 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +08009865 }
9866
lucaslin66f44212021-02-23 01:12:55 +08009867 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
9868 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
9869 synchronized (mActiveIdleTimers) {
9870 mNetworkActive = active;
9871 // If there are no idle timers, it means that system is not monitoring
9872 // activity, so the system default network for those default network
9873 // unspecified apps is always considered active.
9874 //
9875 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
9876 // any network activity change event. Whenever this event is received,
9877 // the mActiveIdleTimers should be always not empty. The legacy behavior
9878 // is no-op. Remove to refer to mNetworkActive only.
9879 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
9880 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
9881 }
9882 }
9883 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009884
lucaslin1193a5d2021-01-21 02:04:15 +08009885 // The network activity should only be updated from ConnectivityService handler thread
9886 // when mActiveIdleTimers lock is held.
9887 @GuardedBy("mActiveIdleTimers")
9888 private void reportNetworkActive() {
9889 final int length = mNetworkActivityListeners.beginBroadcast();
9890 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
9891 try {
9892 for (int i = 0; i < length; i++) {
9893 try {
9894 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
9895 } catch (RemoteException | RuntimeException e) {
9896 loge("Fail to send network activie to listener " + e);
9897 }
9898 }
9899 } finally {
9900 mNetworkActivityListeners.finishBroadcast();
9901 }
9902 }
9903
9904 @GuardedBy("mActiveIdleTimers")
9905 public void handleReportNetworkActivity() {
9906 synchronized (mActiveIdleTimers) {
9907 reportNetworkActive();
9908 }
9909 }
9910
lucaslin1a8b4c62021-01-21 02:02:55 +08009911 // This is deprecated and only to support legacy use cases.
9912 private int transportTypeToLegacyType(int type) {
9913 switch (type) {
9914 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009915 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +08009916 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009917 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +08009918 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009919 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +08009920 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009921 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +08009922 default:
9923 loge("Unexpected transport in transportTypeToLegacyType: " + type);
9924 }
9925 return ConnectivityManager.TYPE_NONE;
9926 }
9927
9928 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
9929 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
9930 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
9931 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
9932 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
9933 final long ident = Binder.clearCallingIdentity();
9934 try {
9935 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
9936 RECEIVE_DATA_ACTIVITY_CHANGE,
9937 null /* resultReceiver */,
9938 null /* scheduler */,
9939 0 /* initialCode */,
9940 null /* initialData */,
9941 null /* initialExtra */);
9942 } finally {
9943 Binder.restoreCallingIdentity(ident);
9944 }
9945 }
9946
9947 /**
9948 * Setup data activity tracking for the given network.
9949 *
9950 * Every {@code setupDataActivityTracking} should be paired with a
9951 * {@link #removeDataActivityTracking} for cleanup.
9952 */
9953 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
9954 final String iface = networkAgent.linkProperties.getInterfaceName();
9955
9956 final int timeout;
9957 final int type;
9958
9959 if (networkAgent.networkCapabilities.hasTransport(
9960 NetworkCapabilities.TRANSPORT_CELLULAR)) {
9961 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009962 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +08009963 10);
9964 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9965 } else if (networkAgent.networkCapabilities.hasTransport(
9966 NetworkCapabilities.TRANSPORT_WIFI)) {
9967 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009968 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +08009969 15);
9970 type = NetworkCapabilities.TRANSPORT_WIFI;
9971 } else {
9972 return; // do not track any other networks
9973 }
9974
lucaslinb961efc2021-01-21 02:03:17 +08009975 updateRadioPowerState(true /* isActive */, type);
9976
lucaslin1a8b4c62021-01-21 02:02:55 +08009977 if (timeout > 0 && iface != null) {
9978 try {
lucaslin1193a5d2021-01-21 02:04:15 +08009979 synchronized (mActiveIdleTimers) {
9980 // Networks start up.
9981 mNetworkActive = true;
9982 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
9983 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
9984 reportNetworkActive();
9985 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009986 } catch (Exception e) {
9987 // You shall not crash!
9988 loge("Exception in setupDataActivityTracking " + e);
9989 }
9990 }
9991 }
9992
9993 /**
9994 * Remove data activity tracking when network disconnects.
9995 */
9996 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
9997 final String iface = networkAgent.linkProperties.getInterfaceName();
9998 final NetworkCapabilities caps = networkAgent.networkCapabilities;
9999
lucaslinb961efc2021-01-21 02:03:17 +080010000 if (iface == null) return;
10001
10002 final int type;
10003 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
10004 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10005 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
10006 type = NetworkCapabilities.TRANSPORT_WIFI;
10007 } else {
10008 return; // do not track any other networks
10009 }
10010
10011 try {
10012 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080010013 synchronized (mActiveIdleTimers) {
10014 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
10015 // The call fails silently if no idle timer setup for this interface
10016 mNetd.idletimerRemoveInterface(iface, params.timeout,
10017 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080010018 }
lucaslinb961efc2021-01-21 02:03:17 +080010019 } catch (Exception e) {
10020 // You shall not crash!
10021 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080010022 }
10023 }
10024
10025 /**
10026 * Update data activity tracking when network state is updated.
10027 */
10028 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
10029 NetworkAgentInfo oldNetwork) {
10030 if (newNetwork != null) {
10031 setupDataActivityTracking(newNetwork);
10032 }
10033 if (oldNetwork != null) {
10034 removeDataActivityTracking(oldNetwork);
10035 }
10036 }
lucaslinb961efc2021-01-21 02:03:17 +080010037
10038 private void updateRadioPowerState(boolean isActive, int transportType) {
10039 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
10040 switch (transportType) {
10041 case NetworkCapabilities.TRANSPORT_CELLULAR:
10042 bs.reportMobileRadioPowerState(isActive, NO_UID);
10043 break;
10044 case NetworkCapabilities.TRANSPORT_WIFI:
10045 bs.reportWifiRadioPowerState(isActive, NO_UID);
10046 break;
10047 default:
10048 logw("Untracked transport type:" + transportType);
10049 }
10050 }
lucaslin1193a5d2021-01-21 02:04:15 +080010051
10052 public boolean isDefaultNetworkActive() {
10053 synchronized (mActiveIdleTimers) {
10054 // If there are no idle timers, it means that system is not monitoring activity,
10055 // so the default network is always considered active.
10056 //
10057 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
10058 // tracking is disabled (negative idle timer value configured), or no active default
10059 // network. In the latter case, this reports active but it should report inactive.
10060 return mNetworkActive || mActiveIdleTimers.isEmpty();
10061 }
10062 }
10063
10064 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
10065 mNetworkActivityListeners.register(l);
10066 }
10067
10068 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
10069 mNetworkActivityListeners.unregister(l);
10070 }
lucaslin012f7a12021-01-21 02:04:35 +080010071
10072 public void dump(IndentingPrintWriter pw) {
10073 synchronized (mActiveIdleTimers) {
10074 pw.print("mNetworkActive="); pw.println(mNetworkActive);
10075 pw.println("Idle timers:");
10076 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
10077 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
10078 final IdleTimerParams params = ent.getValue();
10079 pw.print(" timeout="); pw.print(params.timeout);
10080 pw.print(" type="); pw.println(params.transportType);
10081 }
10082 }
10083 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010084 }
James Mattis47db0582021-01-01 14:13:35 -080010085
Daniel Brightf9e945b2020-06-15 16:10:01 -070010086 /**
10087 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
10088 *
10089 * @param socketInfo the socket information
10090 * @param callback the callback to register
10091 */
10092 @Override
10093 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
10094 @NonNull final IQosCallback callback) {
10095 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
10096 if (nai == null || nai.networkCapabilities == null) {
10097 try {
10098 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
10099 } catch (final RemoteException ex) {
10100 loge("registerQosCallbackInternal: RemoteException", ex);
10101 }
10102 return;
10103 }
10104 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
10105 }
10106
10107 /**
10108 * Register a {@link IQosCallback} with base {@link QosFilter}.
10109 *
10110 * @param filter the filter to register
10111 * @param callback the callback to register
10112 * @param nai the agent information related to the filter's network
10113 */
10114 @VisibleForTesting
10115 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
10116 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
10117 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
10118 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
10119
10120 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
10121 enforceConnectivityRestrictedNetworksPermission();
10122 }
10123 mQosCallbackTracker.registerCallback(callback, filter, nai);
10124 }
10125
10126 /**
10127 * Unregisters the given callback.
10128 *
10129 * @param callback the callback to unregister
10130 */
10131 @Override
10132 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010133 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010134 mQosCallbackTracker.unregisterCallback(callback);
10135 }
James Mattis47db0582021-01-01 14:13:35 -080010136
James Mattis45d81842021-01-10 14:24:24 -080010137 /**
Chalard Jeanfa45a682021-02-25 17:23:40 +090010138 * Request that a user profile is put by default on a network matching a given preference.
10139 *
10140 * See the documentation for the individual preferences for a description of the supported
10141 * behaviors.
10142 *
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010143 * @param profile the user profile for whih the preference is being set.
10144 * @param preferences the list of profile network preferences for the
10145 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010146 * @param listener an optional listener to listen for completion of the operation.
10147 */
10148 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010149 public void setProfileNetworkPreferences(
10150 @NonNull final UserHandle profile,
10151 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090010152 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010153 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010154 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010155
10156 if (preferences.size() == 0) {
10157 preferences.add((new ProfileNetworkPreference.Builder()).build());
10158 }
10159
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010160 PermissionUtils.enforceNetworkStackPermission(mContext);
10161 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010162 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010163 }
10164 if (profile.getIdentifier() < 0) {
10165 throw new IllegalArgumentException("Must explicitly specify a user handle ("
10166 + "UserHandle.CURRENT not supported)");
10167 }
Chalard Jeana21ef9b2021-04-02 19:24:44 +090010168 final UserManager um = mContext.getSystemService(UserManager.class);
10169 if (!um.isManagedProfile(profile.getIdentifier())) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010170 throw new IllegalArgumentException("Profile must be a managed profile");
10171 }
paulhuaa0743d2021-05-26 21:56:03 +080010172
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010173 final List<ProfileNetworkPreferenceList.Preference> preferenceList =
10174 new ArrayList<ProfileNetworkPreferenceList.Preference>();
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010175 boolean allowFallback = true;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010176 for (final ProfileNetworkPreference preference : preferences) {
10177 final NetworkCapabilities nc;
10178 switch (preference.getPreference()) {
10179 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
10180 nc = null;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010181 if (preference.getPreferenceEnterpriseId() != 0) {
10182 throw new IllegalArgumentException(
10183 "Invalid enterprise identifier in setProfileNetworkPreferences");
10184 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010185 break;
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010186 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
10187 allowFallback = false;
10188 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010189 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010190 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
10191 throw new IllegalArgumentException(
10192 "Invalid enterprise identifier in setProfileNetworkPreferences");
10193 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010194 final Set<UidRange> uidRangeSet =
10195 getUidListToBeAppliedForNetworkPreference(profile, preference);
10196 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
10197 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
10198 } else {
10199 throw new IllegalArgumentException(
10200 "Overlapping uid range in setProfileNetworkPreferences");
10201 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010202 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010203 nc.addEnterpriseId(
10204 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010205 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10206 break;
10207 default:
10208 throw new IllegalArgumentException(
10209 "Invalid preference in setProfileNetworkPreferences");
10210 }
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010211 preferenceList.add(new ProfileNetworkPreferenceList.Preference(
10212 profile, nc, allowFallback));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010213 }
10214 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010215 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010216 }
10217
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010218 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
10219 @NonNull final UserHandle profile,
10220 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
10221 final UidRange profileUids = UidRange.createForUser(profile);
10222 Set<UidRange> uidRangeSet = UidRangeUtils.convertListToUidRange(
10223 profileNetworkPreference.getIncludedUids());
10224 if (uidRangeSet.size() > 0) {
10225 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
10226 throw new IllegalArgumentException(
10227 "Allow uid range is outside the uid range of profile.");
10228 }
10229 } else {
10230 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertListToUidRange(
10231 profileNetworkPreference.getExcludedUids());
10232 if (disallowUidRangeSet.size() > 0) {
10233 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
10234 throw new IllegalArgumentException(
10235 "disallow uid range is outside the uid range of profile.");
10236 }
10237 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
10238 disallowUidRangeSet);
10239 } else {
10240 uidRangeSet = new ArraySet<UidRange>();
10241 uidRangeSet.add(profileUids);
10242 }
10243 }
10244 return uidRangeSet;
10245 }
10246
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010247 private boolean isEnterpriseIdentifierValid(
10248 @NetworkCapabilities.EnterpriseId int identifier) {
10249 if ((identifier >= NET_ENTERPRISE_ID_1)
10250 && (identifier <= NET_ENTERPRISE_ID_5)) {
10251 return true;
10252 }
10253 return false;
10254 }
10255
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010256 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
10257 @Nullable final NetworkCapabilities nc) {
10258 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
10259 ensureRequestableCapabilities(nc);
10260 }
10261
10262 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010263 @NonNull final ProfileNetworkPreferenceList prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010264 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010265 for (final ProfileNetworkPreferenceList.Preference pref : prefs.preferences) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010266 // The NRI for a user should contain the request for capabilities.
10267 // If fallback to default network is needed then NRI should include
10268 // the request for the default network. Create an image of it to
10269 // have the correct UIDs in it (also a request can only be part of one NRI, because
10270 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010271 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
10272 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010273 if (pref.allowFallback) {
10274 nrs.add(createDefaultInternetRequestForTransport(
10275 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10276 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010277 if (VDBG) {
10278 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
10279 pref.capabilities.getUids()));
10280 }
10281
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010282 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080010283 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080010284 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010285 result.add(nri);
10286 }
10287 return result;
10288 }
10289
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010290 /**
10291 * Compare if the given UID range sets have the same UIDs.
10292 *
10293 */
10294 private boolean isRangeAlreadyInPreferenceList(
10295 @NonNull List<ProfileNetworkPreferenceList.Preference> preferenceList,
10296 @NonNull Set<UidRange> uidRangeSet) {
10297 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
10298 return false;
10299 }
10300 for (ProfileNetworkPreferenceList.Preference pref : preferenceList) {
10301 if (UidRangeUtils.doesRangeSetOverlap(
10302 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
10303 return true;
10304 }
10305 }
10306 return false;
10307 }
10308
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010309 private void handleSetProfileNetworkPreference(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010310 @NonNull final List<ProfileNetworkPreferenceList.Preference> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010311 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010312 for (final ProfileNetworkPreferenceList.Preference preference : preferenceList) {
10313 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
10314 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
10315 }
paulhu74128522021-09-28 02:29:03 +000010316 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
10317 addPerAppDefaultNetworkRequests(
10318 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010319 // Finally, rematch.
10320 rematchAllNetworksAndRequests();
10321
10322 if (null != listener) {
10323 try {
10324 listener.onComplete();
10325 } catch (RemoteException e) {
10326 loge("Listener for setProfileNetworkPreference has died");
10327 }
10328 }
10329 }
10330
paulhu51f77dc2021-06-07 02:34:20 +000010331 @VisibleForTesting
10332 @NonNull
10333 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
10334 @NonNull final Set<Integer> uids) {
10335 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10336 if (uids.size() == 0) {
10337 // Should not create NetworkRequestInfo if no preferences. Without uid range in
10338 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
10339 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
10340 return nris;
10341 }
10342
10343 final List<NetworkRequest> requests = new ArrayList<>();
10344 // The NRI should be comprised of two layers:
10345 // - The request for the mobile network preferred.
10346 // - The request for the default network, for fallback.
10347 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090010348 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000010349 requests.add(createDefaultInternetRequestForTransport(
10350 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10351 final Set<UidRange> ranges = new ArraySet<>();
10352 for (final int uid : uids) {
10353 ranges.add(new UidRange(uid, uid));
10354 }
10355 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080010356 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080010357 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000010358 return nris;
10359 }
10360
10361 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000010362 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000010363 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
10364 addPerAppDefaultNetworkRequests(
10365 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000010366 // Finally, rematch.
10367 rematchAllNetworksAndRequests();
10368 }
10369
James Mattis45d81842021-01-10 14:24:24 -080010370 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080010371 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
10372 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080010373 }
10374
10375 /**
10376 * Used by automotive devices to set the network preferences used to direct traffic at an
10377 * application level as per the given OemNetworkPreferences. An example use-case would be an
10378 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
10379 * vehicle via a particular network.
10380 *
10381 * Calling this will overwrite the existing preference.
10382 *
James Mattisda32cfe2021-01-26 16:23:52 -080010383 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090010384 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080010385 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080010386 */
James Mattis47db0582021-01-01 14:13:35 -080010387 @Override
James Mattis45d81842021-01-10 14:24:24 -080010388 public void setOemNetworkPreference(
10389 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010390 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080010391
James Mattisfa270db2021-05-31 17:11:10 -070010392 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10393 // Only bypass the permission/device checks if this is a valid test request.
10394 if (isValidTestOemNetworkPreference(preference)) {
10395 enforceManageTestNetworksPermission();
10396 } else {
10397 enforceAutomotiveDevice();
10398 enforceOemNetworkPreferencesPermission();
10399 validateOemNetworkPreferences(preference);
10400 }
James Mattis45d81842021-01-10 14:24:24 -080010401
James Mattis45d81842021-01-10 14:24:24 -080010402 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
10403 new Pair<>(preference, listener)));
10404 }
10405
James Mattisfa270db2021-05-31 17:11:10 -070010406 /**
10407 * Check the validity of an OEM network preference to be used for testing purposes.
10408 * @param preference the preference to validate
10409 * @return true if this is a valid OEM network preference test request.
10410 */
10411 private boolean isValidTestOemNetworkPreference(
10412 @NonNull final OemNetworkPreferences preference) {
10413 // Allow for clearing of an existing OemNetworkPreference used for testing.
10414 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
10415 // changes after this check is complete. This is an unlikely scenario as calling of this API
10416 // is controlled by the OEM therefore the added complexity is not worth adding given those
10417 // circumstances. That said, it is an edge case to be aware of hence this comment.
10418 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
10419 && isTestOemNetworkPreference(mOemNetworkPreferences);
10420 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
10421 }
10422
10423 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
10424 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
10425 return prefMap.size() == 1
10426 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
10427 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
10428 }
10429
James Mattis45d81842021-01-10 14:24:24 -080010430 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
10431 for (@OemNetworkPreferences.OemNetworkPreference final int pref
10432 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070010433 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
10434 throw new IllegalArgumentException(
10435 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
10436 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080010437 }
10438 }
10439 }
10440
10441 private void handleSetOemNetworkPreference(
10442 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010443 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080010444 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10445 if (DBG) {
10446 log("set OEM network preferences :" + preference.toString());
10447 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010448
James Mattiscb1e0362021-04-06 17:07:42 -070010449 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000010450 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
10451 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
10452 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080010453 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080010454
10455 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010456 try {
10457 listener.onComplete();
10458 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080010459 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010460 }
James Mattis45d81842021-01-10 14:24:24 -080010461 }
10462 }
10463
paulhu74128522021-09-28 02:29:03 +000010464 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080010465 // Skip the requests which are set by other network preference. Because the uid range rules
10466 // should stay in netd.
10467 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080010468 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080010469 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080010470 }
10471
James Mattis3ce3d3c2021-02-09 18:18:28 -080010472 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
10473 ensureRunningOnConnectivityServiceThread();
10474 mDefaultNetworkRequests.addAll(nris);
10475 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
10476 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080010477 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000010478 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
10479 nrisToRegister.addAll(
10480 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
10481 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010482 }
10483
10484 /**
10485 * All current requests that are tracking the default network need to be assessed as to whether
10486 * or not the current set of per-application default requests will be changing their default
10487 * network. If so, those requests will need to be updated so that they will send callbacks for
10488 * default network changes at the appropriate time. Additionally, those requests tracking the
10489 * default that were previously updated by this flow will need to be reassessed.
10490 * @return the nris which will need to be updated.
10491 */
10492 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
10493 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
10494 // Get the distinct nris to check since for multilayer requests, it is possible to have the
10495 // same nri in the map's values for each of its NetworkRequest objects.
10496 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080010497 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010498 // Include this nri if it is currently being tracked.
10499 if (isPerAppTrackedNri(nri)) {
10500 defaultCallbackRequests.add(nri);
10501 continue;
10502 }
10503 // We only track callbacks for requests tracking the default.
10504 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
10505 continue;
10506 }
10507 // Include this nri if it will be tracked by the new per-app default requests.
10508 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010509 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080010510 if (isNriGoingToBeTracked) {
10511 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080010512 }
10513 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080010514 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080010515 }
10516
James Mattis3ce3d3c2021-02-09 18:18:28 -080010517 /**
10518 * Create nris for those network requests that are currently tracking the default network that
10519 * are being controlled by a per-application default.
10520 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
10521 * foundation when creating the nri. Important items include the calling uid's original
10522 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
10523 * requests are assumed to have already been validated as needing to be updated.
10524 * @return the Set of nris to use when registering network requests.
10525 */
10526 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
10527 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
10528 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
10529 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
10530 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010531 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010532
Chalard Jean9473c982021-07-29 20:03:04 +090010533 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080010534 if (trackingNri == mDefaultRequest) {
10535 callbackRequestsToRegister.add(new NetworkRequestInfo(
10536 callbackRequest,
10537 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
10538 continue;
10539 }
10540
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010541 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010542 callbackRequestsToRegister.add(new NetworkRequestInfo(
10543 callbackRequest,
10544 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010545 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090010546 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080010547 }
10548 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080010549 }
10550
Chalard Jean17215832021-03-01 14:06:28 +090010551 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
10552 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090010553 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010554 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090010555 }
10556 }
10557
James Mattis45d81842021-01-10 14:24:24 -080010558 /**
10559 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
10560 */
10561 @VisibleForTesting
10562 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010563 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080010564 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010565 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080010566 final SparseArray<Set<Integer>> uids =
10567 createUidsFromOemNetworkPreferences(preference);
10568 for (int i = 0; i < uids.size(); i++) {
10569 final int key = uids.keyAt(i);
10570 final Set<Integer> value = uids.valueAt(i);
10571 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
10572 // No need to add an nri without any requests.
10573 if (0 == nri.mRequests.size()) {
10574 continue;
10575 }
10576 nris.add(nri);
10577 }
10578
10579 return nris;
10580 }
10581
10582 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
10583 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070010584 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080010585 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080010586 final List<UserHandle> users =
10587 mContext.getSystemService(UserManager.class).getUserHandles(true);
10588 if (null == users || users.size() == 0) {
10589 if (VDBG || DDBG) {
10590 log("No users currently available for setting the OEM network preference.");
10591 }
James Mattisb6b6a432021-06-01 22:30:36 -070010592 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080010593 }
James Mattis45d81842021-01-10 14:24:24 -080010594 for (final Map.Entry<String, Integer> entry :
10595 preference.getNetworkPreferences().entrySet()) {
10596 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070010597 // Add the rules for all users as this policy is device wide.
10598 for (final UserHandle user : users) {
10599 try {
10600 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
10601 if (!prefToUids.contains(pref)) {
10602 prefToUids.put(pref, new ArraySet<>());
10603 }
10604 prefToUids.get(pref).add(uid);
10605 } catch (PackageManager.NameNotFoundException e) {
10606 // Although this may seem like an error scenario, it is ok that uninstalled
10607 // packages are sent on a network preference as the system will watch for
10608 // package installations associated with this network preference and update
10609 // accordingly. This is done to minimize race conditions on app install.
10610 continue;
James Mattis45d81842021-01-10 14:24:24 -080010611 }
James Mattis45d81842021-01-10 14:24:24 -080010612 }
10613 }
James Mattisb6b6a432021-06-01 22:30:36 -070010614 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080010615 }
10616
10617 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10618 @OemNetworkPreferences.OemNetworkPreference final int preference,
10619 @NonNull final Set<Integer> uids) {
10620 final List<NetworkRequest> requests = new ArrayList<>();
10621 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10622 switch (preference) {
10623 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10624 requests.add(createUnmeteredNetworkRequest());
10625 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070010626 requests.add(createDefaultInternetRequestForTransport(
10627 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080010628 break;
10629 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10630 requests.add(createUnmeteredNetworkRequest());
10631 requests.add(createOemPaidNetworkRequest());
10632 break;
10633 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10634 requests.add(createOemPaidNetworkRequest());
10635 break;
10636 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10637 requests.add(createOemPrivateNetworkRequest());
10638 break;
James Mattisfa270db2021-05-31 17:11:10 -070010639 case OEM_NETWORK_PREFERENCE_TEST:
10640 requests.add(createUnmeteredNetworkRequest());
10641 requests.add(createTestNetworkRequest());
10642 requests.add(createDefaultRequest());
10643 break;
10644 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
10645 requests.add(createTestNetworkRequest());
10646 break;
James Mattis45d81842021-01-10 14:24:24 -080010647 default:
10648 // This should never happen.
10649 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10650 + " called with invalid preference of " + preference);
10651 }
10652
James Mattisfa270db2021-05-31 17:11:10 -070010653 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090010654 for (final int uid : uids) {
10655 ranges.add(new UidRange(uid, uid));
10656 }
10657 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080010658 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080010659 }
10660
10661 private NetworkRequest createUnmeteredNetworkRequest() {
10662 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10663 .addCapability(NET_CAPABILITY_NOT_METERED)
10664 .addCapability(NET_CAPABILITY_VALIDATED);
10665 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10666 }
10667
10668 private NetworkRequest createOemPaidNetworkRequest() {
10669 // NET_CAPABILITY_OEM_PAID is a restricted capability.
10670 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10671 .addCapability(NET_CAPABILITY_OEM_PAID)
10672 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10673 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10674 }
10675
10676 private NetworkRequest createOemPrivateNetworkRequest() {
10677 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
10678 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10679 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
10680 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10681 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10682 }
10683
10684 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070010685 final NetworkCapabilities netcap = new NetworkCapabilities();
10686 netcap.addCapability(NET_CAPABILITY_INTERNET);
10687 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
10688 return netcap;
10689 }
10690
10691 private NetworkRequest createTestNetworkRequest() {
10692 final NetworkCapabilities netcap = new NetworkCapabilities();
10693 netcap.clearAll();
10694 netcap.addTransportType(TRANSPORT_TEST);
10695 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080010696 }
James Mattis47db0582021-01-01 14:13:35 -080010697 }
markchien738ad912021-12-09 18:15:45 +080010698
10699 @Override
10700 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
10701 enforceNetworkStackOrSettingsPermission();
10702
10703 try {
10704 if (add) {
10705 mNetd.bandwidthAddNiceApp(uid);
10706 } else {
10707 mNetd.bandwidthRemoveNiceApp(uid);
10708 }
10709 } catch (RemoteException | ServiceSpecificException e) {
10710 throw new IllegalStateException(e);
10711 }
10712 }
10713
10714 @Override
10715 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
10716 enforceNetworkStackOrSettingsPermission();
10717
10718 try {
10719 if (add) {
10720 mNetd.bandwidthAddNaughtyApp(uid);
10721 } else {
10722 mNetd.bandwidthRemoveNaughtyApp(uid);
10723 }
10724 } catch (RemoteException | ServiceSpecificException e) {
10725 throw new IllegalStateException(e);
10726 }
10727 }
markchiene1561fa2021-12-09 22:00:56 +080010728
10729 @Override
10730 public void updateFirewallRule(final int chain, final int uid, final boolean allow) {
10731 enforceNetworkStackOrSettingsPermission();
10732
10733 try {
10734 mNetd.firewallSetUidRule(chain, uid,
10735 allow ? INetd.FIREWALL_RULE_ALLOW : INetd.FIREWALL_RULE_DENY);
10736 } catch (RemoteException | ServiceSpecificException e) {
10737 throw new IllegalStateException(e);
10738 }
10739 }
markchien98a6f952022-01-13 23:43:53 +080010740
10741 @Override
10742 public void setFirewallChainEnabled(final int chain, final boolean enable) {
10743 enforceNetworkStackOrSettingsPermission();
10744
10745 try {
10746 mNetd.firewallEnableChildChain(chain, enable);
10747 } catch (RemoteException | ServiceSpecificException e) {
10748 throw new IllegalStateException(e);
10749 }
10750 }
10751
markchien00a0bed2022-01-13 23:46:13 +080010752 @Override
10753 public void replaceFirewallChain(final int chain, final int[] uids) {
10754 enforceNetworkStackOrSettingsPermission();
10755
10756 try {
10757 switch (chain) {
10758 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
10759 mNetd.firewallReplaceUidChain("fw_dozable", true /* isAllowList */, uids);
10760 break;
10761 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
10762 mNetd.firewallReplaceUidChain("fw_standby", false /* isAllowList */, uids);
10763 break;
10764 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
10765 mNetd.firewallReplaceUidChain("fw_powersave", true /* isAllowList */, uids);
10766 break;
10767 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
10768 mNetd.firewallReplaceUidChain("fw_restricted", true /* isAllowList */, uids);
10769 break;
10770 default:
10771 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
10772 + chain);
10773 }
10774 } catch (RemoteException | ServiceSpecificException e) {
10775 throw new IllegalStateException(e);
10776 }
10777 }
markchien9c806112022-01-11 23:28:23 +080010778
10779 @Override
10780 public void swapActiveStatsMap() {
10781 enforceNetworkStackOrSettingsPermission();
10782 try {
10783 mNetd.trafficSwapActiveStatsMap();
10784 } catch (RemoteException | ServiceSpecificException e) {
10785 throw new IllegalStateException(e);
10786 }
10787 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070010788}