blob: a453270c3ec06c3d4f82eab311480c969317f79a [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;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800252import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900253import com.android.server.connectivity.ConnectivityFlags;
Erik Kline32120082017-12-13 19:40:49 +0900254import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500255import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700256import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900257import com.android.server.connectivity.FullScore;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900258import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100259import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700260import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700261import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600262import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900263import com.android.server.connectivity.NetworkNotificationManager;
264import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900265import com.android.server.connectivity.NetworkOffer;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900266import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700267import com.android.server.connectivity.PermissionMonitor;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800268import com.android.server.connectivity.ProfileNetworkPreferenceList;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900269import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700270import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800271import com.android.server.connectivity.UidRangeUtils;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600272
Josh Gao461a1222020-06-16 15:58:11 -0700273import libcore.io.IoUtils;
274
The Android Open Source Project28527d22009-03-03 19:31:44 -0800275import java.io.FileDescriptor;
276import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900277import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700278import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700279import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900280import java.net.InetSocketAddress;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700281import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700282import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700283import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700284import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800285import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900286import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800287import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700288import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700289import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700290import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700291import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900292import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700293import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900294import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600295import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900296import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600297import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900298import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800299
300/**
301 * @hide
302 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800303public class ConnectivityService extends IConnectivityManager.Stub
304 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900305 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800306
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900307 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900308 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900309 private static final String NETWORK_ARG = "networks";
310 private static final String REQUEST_ARG = "requests";
Erik Klined364a242017-05-12 16:52:48 +0900311
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900312 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900313 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
314 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800315
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900316 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700317
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100318 /**
319 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
320 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800321 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100322 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
323 * (preferably via runtime resource overlays).
324 */
325 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
326 "http://connectivitycheck.gstatic.com/generate_204";
327
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700328 // TODO: create better separation between radio types and network types
329
Robert Greenwalt2034b912009-08-12 16:08:25 -0700330 // how long to wait before switching back to a radio's default network
331 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
332 // system property that can override the above value
333 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
334 "android.telephony.apn-restore";
335
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900336 // How long to wait before putting up a "This network doesn't have an Internet connection,
337 // connect anyway?" dialog after the user selects a network that doesn't validate.
338 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
339
junyulai0ac374f2020-12-14 18:41:52 +0800340 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900341 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
342 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800343 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700344
345 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900346 @VisibleForTesting
347 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700348
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900349 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700350 @VisibleForTesting
351 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900352
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900353 @VisibleForTesting
354 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800355 @VisibleForTesting
356 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900357 // True if the cell radio of the device is capable of time-sharing.
358 @VisibleForTesting
359 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900360
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800361 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800362 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800363 private final int mReleasePendingIntentDelayMs;
364
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900365 private MockableSystemProperties mSystemProperties;
366
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000367 @VisibleForTesting
368 protected final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700369
Chalard Jean9473c982021-07-29 20:03:04 +0900370 @VisibleForTesting
371 final PerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700372 @VisibleForTesting
373 final PerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700374
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900375 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700376
junyulaif2c67e42018-08-07 19:50:45 +0800377 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000378 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
379 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800380 */
Sudheer Shanka9967d462021-03-18 19:09:25 +0000381 private SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800382
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900383 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900384 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000385 // The Context is created for UserHandle.ALL.
386 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900387 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900388 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700389 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700390 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800391
Chenbo Feng15416292018-11-08 17:36:21 -0800392 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800393 protected IDnsResolver mDnsResolver;
394 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800395 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700396 private DscpPolicyTracker mDscpPolicyTracker = null;
junyulaie7c7d2a2021-01-26 15:29:15 +0800397 private NetworkStatsManager mStatsManager;
paulhu9a9f71b2020-12-29 18:15:13 +0800398 private NetworkPolicyManager mPolicyManager;
lucaslin66f44212021-02-23 01:12:55 +0800399 private final NetdCallback mNetdCallback;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800400 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700401
Benedict Wong493e04b2018-11-09 14:45:34 -0800402 /**
403 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
404 * instances.
405 */
406 @GuardedBy("mTNSLock")
407 private TestNetworkService mTNS;
408
409 private final Object mTNSLock = new Object();
410
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700411 private String mCurrentTcpBufferSizes;
412
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900413 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
lifraf3a3492021-03-10 13:58:14 +0800414 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900415
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500416 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400417 // Tear down networks that have no chance (e.g. even if validated) of becoming
418 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500419 // all networks have been rematched against all NetworkRequests.
420 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400421 // Don't reap networks. This should be passed when some networks have not yet been
422 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500423 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900424 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500425
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900426 private enum UnneededFor {
427 LINGER, // Determine whether this network is unneeded and should be lingered.
428 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
429 }
430
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700431 /**
paulhuaa0743d2021-05-26 21:56:03 +0800432 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800433 * should have priority. The order is passed to netd which will use it together
434 * with UID ranges to generate the corresponding IP rule. This serves to
435 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800436 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800437 * Order ints passed to netd must be in the 0~999 range. Larger values code for
paulhuaa0743d2021-05-26 21:56:03 +0800438 * a lower priority, {@see NativeUidRangeConfig}
paulhue9913722021-05-26 15:19:20 +0800439 *
paulhu48291862021-07-14 14:53:57 +0800440 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
441 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800442 */
paulhu48291862021-07-14 14:53:57 +0800443 // 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;
paulhuaa0743d2021-05-26 21:56:03 +0800450 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800451 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
452 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800453 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800454 static final int PREFERENCE_ORDER_OEM = 10;
455 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800456 // See {@link #setProfileNetworkPreference}.
457 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800458 static final int PREFERENCE_ORDER_PROFILE = 20;
459 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800460 // better scores are connected.
461 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800462 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800463 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900464 // Preference order that signifies the network shouldn't be set as a default network for
465 // the UIDs, only give them access to it. TODO : replace this with a boolean
466 // in NativeUidRangeConfig
467 @VisibleForTesting
468 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
469 // Bound for the lowest valid preference order.
470 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800471
472 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700473 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700474 * from one net to another. Clear happens when we get a new
475 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
476 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700477 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700478 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700479
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700480 /**
481 * used internally to reload global proxy settings
482 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700483 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700484
Robert Greenwalt34848c02011-03-25 13:09:25 -0700485 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400486 * PAC manager has received new port.
487 */
488 private static final int EVENT_PROXY_HAS_CHANGED = 16;
489
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700490 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900491 * used internally when registering NetworkProviders
492 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700493 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900494 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700495
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700496 /**
497 * used internally when registering NetworkAgents
498 * obj = Messenger
499 */
500 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
501
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700502 /**
503 * used to add a network request
504 * includes a NetworkRequestInfo
505 */
506 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
507
508 /**
509 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900510 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700511 * cancel it.
512 * includes a NetworkRequestInfo
513 */
514 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
515
516 /**
517 * used to add a network listener - no request
518 * includes a NetworkRequestInfo
519 */
520 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
521
522 /**
523 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400524 * arg1 = UID of caller
525 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700526 */
527 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
528
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700529 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900530 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700531 * obj = Messenger
532 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900533 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700534
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700535 /**
536 * used internally to expire a wakelock when transitioning
537 * from one net to another. Expire happens when we fail to find
538 * a new network (typically after 1 minute) -
539 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
540 * a replacement network.
541 */
542 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
543
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700544 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800545 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400546 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800547 */
548 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
549
550 /**
551 * used to remove a pending intent and its associated network request.
552 * arg1 = UID of caller
553 * obj = PendingIntent
554 */
555 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
556
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900557 /**
558 * used to specify whether a network should be used even if unvalidated.
559 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
560 * arg2 = whether to remember this choice in the future (1 or 0)
561 * obj = network
562 */
563 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
564
565 /**
566 * used to ask the user to confirm a connection to an unvalidated network.
567 * obj = network
568 */
569 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700570
Erik Kline05f2b402015-04-30 12:58:40 +0900571 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700572 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900573 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700574 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900575
Paul Jensenc8873fc2015-06-17 14:15:39 -0400576 /**
577 * used to add a network listener with a pending intent
578 * obj = NetworkRequestInfo
579 */
580 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
581
Hugo Benichid6b510a2017-04-06 17:22:18 +0900582 /**
583 * used to specify whether a network should not be penalized when it becomes unvalidated.
584 */
585 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
586
587 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700588 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900589 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700590 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900591
Erik Kline31b4a9e2018-01-11 21:07:29 +0900592 // Handle changes in Private DNS settings.
593 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
594
dalyk1720e542018-03-05 12:42:22 -0500595 // Handle private DNS validation status updates.
596 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
597
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800598 /**
599 * used to remove a network request, either a listener or a real request and call unavailable
600 * arg1 = UID of caller
601 * obj = NetworkRequest
602 */
603 private static final int EVENT_RELEASE_NETWORK_REQUEST_AND_CALL_UNAVAILABLE = 39;
604
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900605 /**
606 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
607 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800608 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
609 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
610 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900611 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900612 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900613
614 /**
615 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
616 * config was resolved.
617 * obj = PrivateDnsConfig
618 * arg2 = netid
619 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900620 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900621
622 /**
623 * Request ConnectivityService display provisioning notification.
624 * arg1 = Whether to make the notification visible.
625 * arg2 = NetID.
626 * obj = Intent to be launched when notification selected by user, null if !arg1.
627 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900628 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900629
630 /**
lucaslin2240ef62019-03-12 13:08:03 +0800631 * Used to specify whether a network should be used even if connectivity is partial.
632 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
633 * false)
634 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
635 * obj = network
636 */
lucaslin444d43a2020-02-20 16:56:59 +0800637 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800638
639 /**
lucasline117e2e2019-10-22 18:27:33 +0800640 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
641 * Both of the arguments are bitmasks, and the value of bits come from
642 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
643 * arg1 = A bitmask to describe which probes are completed.
644 * arg2 = A bitmask to describe which probes are successful.
645 */
lucaslin444d43a2020-02-20 16:56:59 +0800646 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800647
648 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900649 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
650 * arg1 = unused
651 * arg2 = netId
652 * obj = captive portal data
653 */
lucaslin444d43a2020-02-20 16:56:59 +0800654 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900655
656 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900657 * Used by setRequireVpnForUids.
658 * arg1 = whether the specified UID ranges are required to use a VPN.
659 * obj = Array of UidRange objects.
660 */
661 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
662
663 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900664 * Used internally when setting the default networks for OemNetworkPreferences.
665 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800666 */
667 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
668
669 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800670 * Used to indicate the system default network becomes active.
671 */
672 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
673
674 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900675 * Used internally when setting a network preference for a user profile.
676 * obj = Pair<ProfileNetworkPreference, Listener>
677 */
678 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
679
680 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000681 * Event to specify that reasons for why an uid is blocked changed.
682 * arg1 = uid
683 * arg2 = blockedReasons
684 */
685 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
686
687 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900688 * Event to register a new network offer
689 * obj = NetworkOffer
690 */
691 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
692
693 /**
694 * Event to unregister an existing network offer
695 * obj = INetworkOfferCallback
696 */
697 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
698
699 /**
paulhu51f77dc2021-06-07 02:34:20 +0000700 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
701 */
702 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
703
704 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800705 * Event to set temporary allow bad wifi within a limited time to override
706 * {@code config_networkAvoidBadWifi}.
707 */
708 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
709
710 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900711 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
712 * should be shown.
713 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900714 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900715
716 /**
717 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
718 * should be hidden.
719 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900720 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900721
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800722 /**
723 * The maximum alive time to allow bad wifi configuration for testing.
724 */
725 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
726
Hugo Benichi47011212017-03-30 10:46:05 +0900727 private static String eventName(int what) {
728 return sMagicDecoderRing.get(what, Integer.toString(what));
729 }
730
paulhua10d8212020-11-10 15:32:56 +0800731 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900732 final DnsResolverServiceManager dsm = context.getSystemService(
733 DnsResolverServiceManager.class);
734 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800735 }
736
Cody Kesting73708bf2019-12-18 10:57:50 -0800737 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900738 @VisibleForTesting
739 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700740 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700741 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700742 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700743 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800744 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
745 @VisibleForTesting
746 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
747
Erik Kline32120082017-12-13 19:40:49 +0900748 private final DnsManager mDnsManager;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900749 private final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700750
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400751 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800752 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400753
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700754 private PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800755 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700756
Chalard Jean5d70ba42018-06-07 16:44:04 +0900757 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
758 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000759 @VisibleForTesting
760 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400761
Erik Kline05f2b402015-04-30 12:58:40 +0900762 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700763
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400764 private UserManager mUserManager;
765
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700766 // the set of network types that can only be enabled by system/sig apps
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900767 private List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700768
Valentin Iftime9fa35092019-09-24 13:32:13 +0200769 private Set<String> mWolSupportedInterfaces;
770
Roshan Pius08c94fb2020-01-16 12:17:17 -0800771 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800772 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800773 private final AppOpsManager mAppOpsManager;
774
775 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400776
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900777 private KeepaliveTracker mKeepaliveTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700778 private QosCallbackTracker mQosCallbackTracker;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900779 private NetworkNotificationManager mNotifier;
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +0900780 private LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900781
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700782 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800783 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700784
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900785 // Sequence number for NetworkProvider IDs.
786 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
787 NetworkProvider.FIRST_PROVIDER_ID);
788
Erik Klineedf878b2015-07-09 18:24:03 +0900789 // NetworkRequest activity String log entries.
790 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
791 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
792
Hugo Benichid159fdd2016-07-11 11:05:12 +0900793 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900794 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900795 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
796
Hugo Benichi47011212017-03-30 10:46:05 +0900797 private static final int MAX_WAKELOCK_LOGS = 20;
798 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900799 private int mTotalWakelockAcquisitions = 0;
800 private int mTotalWakelockReleases = 0;
801 private long mTotalWakelockDurationMs = 0;
802 private long mMaxWakelockDurationMs = 0;
803 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900804
Hugo Benichi208c0102016-07-28 17:53:06 +0900805 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900806
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700807 @GuardedBy("mBandwidthRequests")
808 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
809
Erik Kline95ecfee2016-10-02 18:02:14 +0900810 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900811 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900812
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900813 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800814 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
815 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800816
Robert Greenwalt802c1102014-06-02 15:32:02 -0700817 /**
818 * Implements support for the legacy "one network per network type" model.
819 *
820 * We used to have a static array of NetworkStateTrackers, one for each
821 * network type, but that doesn't work any more now that we can have,
822 * for example, more that one wifi network. This class stores all the
823 * NetworkAgentInfo objects that support a given type, but the legacy
824 * API will only see the first one.
825 *
826 * It serves two main purposes:
827 *
828 * 1. Provide information about "the network for a given type" (since this
829 * API only supports one).
830 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
831 * the first network for a given type changes, or if the default network
832 * changes.
833 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900834 @VisibleForTesting
835 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900836
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900837 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900838 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900839
Robert Greenwalt802c1102014-06-02 15:32:02 -0700840 /**
841 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
842 * Each list holds references to all NetworkAgentInfos that are used to
843 * satisfy requests for that network type.
844 *
845 * This array is built out at startup such that an unsupported network
846 * doesn't get an ArrayList instance, making this a tristate:
847 * unsupported, supported but not active and active.
848 *
849 * The actual lists are populated when we scan the network types that
850 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900851 *
852 * Threading model:
853 * - addSupportedType() is only called in the constructor
854 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
855 * They are therefore not thread-safe with respect to each other.
856 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
857 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900858 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900859 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700860 */
Hugo Benichi389633f2016-06-21 09:48:07 +0900861 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900862 @NonNull
863 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700864
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900865 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
866 // an entry have no timer (equivalent to -1). Lazily loaded.
867 @NonNull
868 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
869
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900870 LegacyTypeTracker(@NonNull ConnectivityService service) {
871 mService = service;
872 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700873 }
874
Chiachang Wang3bc52762021-11-25 14:17:57 +0800875 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
876 // addressed.
877 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900878 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
879 final PackageManager pm = ctx.getPackageManager();
880 if (pm.hasSystemFeature(FEATURE_WIFI)) {
881 addSupportedType(TYPE_WIFI);
882 }
883 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
884 addSupportedType(TYPE_WIFI_P2P);
885 }
886 if (tm.isDataCapable()) {
887 // Telephony does not have granular support for these types: they are either all
888 // supported, or none is supported
889 addSupportedType(TYPE_MOBILE);
890 addSupportedType(TYPE_MOBILE_MMS);
891 addSupportedType(TYPE_MOBILE_SUPL);
892 addSupportedType(TYPE_MOBILE_DUN);
893 addSupportedType(TYPE_MOBILE_HIPRI);
894 addSupportedType(TYPE_MOBILE_FOTA);
895 addSupportedType(TYPE_MOBILE_IMS);
896 addSupportedType(TYPE_MOBILE_CBS);
897 addSupportedType(TYPE_MOBILE_IA);
898 addSupportedType(TYPE_MOBILE_EMERGENCY);
899 }
900 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
901 addSupportedType(TYPE_BLUETOOTH);
902 }
903 if (pm.hasSystemFeature(FEATURE_WATCH)) {
904 // TYPE_PROXY is only used on Wear
905 addSupportedType(TYPE_PROXY);
906 }
907 // Ethernet is often not specified in the configs, although many devices can use it via
908 // USB host adapters. Add it as long as the ethernet service is here.
909 if (ctx.getSystemService(Context.ETHERNET_SERVICE) != null) {
910 addSupportedType(TYPE_ETHERNET);
911 }
912
913 // Always add TYPE_VPN as a supported type
914 addSupportedType(TYPE_VPN);
915 }
916
917 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700918 if (mTypeLists[type] != null) {
919 throw new IllegalStateException(
920 "legacy list for type " + type + "already initialized");
921 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900922 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -0700923 }
924
Robert Greenwalt802c1102014-06-02 15:32:02 -0700925 public boolean isTypeSupported(int type) {
926 return isNetworkTypeValid(type) && mTypeLists[type] != null;
927 }
928
929 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +0900930 synchronized (mTypeLists) {
931 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
932 return mTypeLists[type].get(0);
933 }
Robert Greenwalt802c1102014-06-02 15:32:02 -0700934 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900935 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700936 }
937
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900938 public int getRestoreTimerForType(int type) {
939 synchronized (mTypeLists) {
940 if (mRestoreTimers == null) {
941 mRestoreTimers = loadRestoreTimers();
942 }
943 return mRestoreTimers.getOrDefault(type, -1);
944 }
945 }
946
947 private ArrayMap<Integer, Integer> loadRestoreTimers() {
948 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900949 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900950 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
951 for (final String config : configs) {
952 final String[] splits = TextUtils.split(config, ",");
953 if (splits.length != 2) {
954 logwtf("Invalid restore timer token count: " + config);
955 continue;
956 }
957 try {
958 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
959 } catch (NumberFormatException e) {
960 logwtf("Invalid restore timer number format: " + config, e);
961 }
962 }
963 return ret;
964 }
965
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -0700966 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +0900967 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900968 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +0900969 log("Sending " + state
970 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +0900971 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900972 }
973 }
974
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900975 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
976 // network type, to preserve previous behaviour.
977 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
978 if (vpnNai != mService.getLegacyLockdownNai()) return;
979
980 if (vpnNai.declaredUnderlyingNetworks == null
981 || vpnNai.declaredUnderlyingNetworks.length != 1) {
982 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
983 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
984 return;
985 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +0900986 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900987 vpnNai.declaredUnderlyingNetworks[0]);
988 if (underlyingNai == null) return;
989
990 final int type = underlyingNai.networkInfo.getType();
991 final DetailedState state = DetailedState.CONNECTED;
992 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
993 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
994 }
995
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900996 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -0700997 public void add(int type, NetworkAgentInfo nai) {
998 if (!isTypeSupported(type)) {
999 return; // Invalid network type.
1000 }
1001 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1002
1003 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1004 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001005 return;
1006 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001007 synchronized (mTypeLists) {
1008 list.add(nai);
1009 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001010
Chalard Jean5b409c72021-02-04 13:12:59 +09001011 // Send a broadcast if this is the first network of its type or if it's the default.
1012 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001013
1014 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1015 // to preserve previous behaviour.
1016 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001017 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001018 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1019 mService.sendLegacyNetworkBroadcast(nai, state, type);
1020 }
1021
1022 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1023 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001024 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001025 }
1026
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001027 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001028 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001029 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1030 if (list == null || list.isEmpty()) {
1031 return;
1032 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001033 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001034
Hugo Benichi389633f2016-06-21 09:48:07 +09001035 synchronized (mTypeLists) {
1036 if (!list.remove(nai)) {
1037 return;
1038 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001039 }
1040
Lorenzo Colitti49767722015-05-01 00:30:10 +09001041 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001042 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1043 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001044 }
1045
1046 if (!list.isEmpty() && wasFirstNetwork) {
1047 if (DBG) log("Other network available for type " + type +
1048 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001049 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001050 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001051 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001052 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001053 }
1054 }
1055
1056 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001057 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1058 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001059 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001060 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001061 }
1062 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001063
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001064 // send out another legacy broadcast - currently only used for suspend/unsuspend
1065 // toggle
1066 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001067 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001068 final DetailedState state = nai.networkInfo.getDetailedState();
1069 for (int type = 0; type < mTypeLists.length; type++) {
1070 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001071 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001072 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001073 if (isFirst || contains && isDefault) {
1074 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001075 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001076 }
1077 }
1078 }
1079
Robert Greenwalt94e22142014-07-30 16:31:24 -07001080 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001081 pw.println("mLegacyTypeTracker:");
1082 pw.increaseIndent();
1083 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001084 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001085 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001086 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001087 pw.println();
1088 pw.println("Current state:");
1089 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001090 synchronized (mTypeLists) {
1091 for (int type = 0; type < mTypeLists.length; type++) {
1092 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1093 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001094 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001095 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001096 }
1097 }
1098 pw.decreaseIndent();
1099 pw.decreaseIndent();
1100 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001101 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001102 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001103 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001104
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001105 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001106 /**
1107 * Helper class which parses out priority arguments and dumps sections according to their
1108 * priority. If priority arguments are omitted, function calls the legacy dump command.
1109 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001110 private class LocalPriorityDump {
1111 private static final String PRIORITY_ARG = "--dump-priority";
1112 private static final String PRIORITY_ARG_HIGH = "HIGH";
1113 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1114
1115 LocalPriorityDump() {}
1116
1117 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1118 doDump(fd, pw, new String[] {DIAG_ARG});
1119 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001120 }
1121
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001122 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1123 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001124 }
1125
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001126 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1127 if (args == null) {
1128 dumpNormal(fd, pw, args);
1129 return;
1130 }
1131
1132 String priority = null;
1133 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1134 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1135 argIndex++;
1136 priority = args[argIndex];
1137 }
1138 }
1139
1140 if (PRIORITY_ARG_HIGH.equals(priority)) {
1141 dumpHigh(fd, pw);
1142 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1143 dumpNormal(fd, pw, args);
1144 } else {
1145 // ConnectivityService publishes binder service using publishBinderService() with
1146 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001147 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1148 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001149 // TODO: Integrate into signal dump.
1150 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001151 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001152 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001153 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001154
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001155 /**
Daniel Brightf9e945b2020-06-15 16:10:01 -07001156 * Keeps track of the number of requests made under different uids.
1157 */
1158 public static class PerUidCounter {
1159 private final int mMaxCountPerUid;
1160
1161 // Map from UID to number of NetworkRequests that UID has filed.
James Mattis20a4a8b2021-03-28 17:41:09 -07001162 @VisibleForTesting
Daniel Brightf9e945b2020-06-15 16:10:01 -07001163 @GuardedBy("mUidToNetworkRequestCount")
James Mattis20a4a8b2021-03-28 17:41:09 -07001164 final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
Daniel Brightf9e945b2020-06-15 16:10:01 -07001165
1166 /**
1167 * Constructor
1168 *
1169 * @param maxCountPerUid the maximum count per uid allowed
1170 */
1171 public PerUidCounter(final int maxCountPerUid) {
1172 mMaxCountPerUid = maxCountPerUid;
1173 }
1174
1175 /**
1176 * Increments the request count of the given uid. Throws an exception if the number
1177 * of open requests for the uid exceeds the value of maxCounterPerUid which is the value
1178 * passed into the constructor. see: {@link #PerUidCounter(int)}.
1179 *
1180 * @throws ServiceSpecificException with
1181 * {@link ConnectivityManager.Errors.TOO_MANY_REQUESTS} if the number of requests for
1182 * the uid exceed the allowed number.
1183 *
1184 * @param uid the uid that the request was made under
1185 */
1186 public void incrementCountOrThrow(final int uid) {
1187 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001188 incrementCountOrThrow(uid, 1 /* numToIncrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001189 }
1190 }
1191
James Mattis20a4a8b2021-03-28 17:41:09 -07001192 private void incrementCountOrThrow(final int uid, final int numToIncrement) {
1193 final int newRequestCount =
1194 mUidToNetworkRequestCount.get(uid, 0) + numToIncrement;
Chalard Jean9473c982021-07-29 20:03:04 +09001195 if (newRequestCount >= mMaxCountPerUid
1196 // HACK : the system server is allowed to go over the request count limit
1197 // when it is creating requests on behalf of another app (but not itself,
1198 // so it can still detect its own request leaks). This only happens in the
1199 // per-app API flows in which case the old requests for that particular
1200 // UID will be removed soon.
1201 // TODO : instead of this hack, addPerAppDefaultNetworkRequests and other
1202 // users of transact() should unregister the requests to decrease the count
1203 // before they increase it again by creating a new NRI. Then remove the
1204 // transact() method.
1205 && (Process.myUid() == uid || Process.myUid() != Binder.getCallingUid())) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001206 throw new ServiceSpecificException(
Chalard Jean9473c982021-07-29 20:03:04 +09001207 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
1208 "Uid " + uid + " exceeded its allotted requests limit");
James Mattis20a4a8b2021-03-28 17:41:09 -07001209 }
1210 mUidToNetworkRequestCount.put(uid, newRequestCount);
1211 }
1212
Daniel Brightf9e945b2020-06-15 16:10:01 -07001213 /**
1214 * Decrements the request count of the given uid.
1215 *
1216 * @param uid the uid that the request was made under
1217 */
1218 public void decrementCount(final int uid) {
1219 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001220 decrementCount(uid, 1 /* numToDecrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001221 }
1222 }
James Mattis20a4a8b2021-03-28 17:41:09 -07001223
1224 private void decrementCount(final int uid, final int numToDecrement) {
1225 final int newRequestCount =
1226 mUidToNetworkRequestCount.get(uid, 0) - numToDecrement;
1227 if (newRequestCount < 0) {
1228 logwtf("BUG: too small request count " + newRequestCount + " for UID " + uid);
1229 } else if (newRequestCount == 0) {
1230 mUidToNetworkRequestCount.delete(uid);
1231 } else {
1232 mUidToNetworkRequestCount.put(uid, newRequestCount);
1233 }
1234 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07001235 }
1236
1237 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001238 * Dependencies of ConnectivityService, for injection in tests.
1239 */
1240 @VisibleForTesting
1241 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001242 public int getCallingUid() {
1243 return Binder.getCallingUid();
1244 }
1245
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001246 /**
1247 * Get system properties to use in ConnectivityService.
1248 */
1249 public MockableSystemProperties getSystemProperties() {
1250 return new MockableSystemProperties();
1251 }
1252
1253 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001254 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1255 */
1256 public ConnectivityResources getResources(@NonNull Context ctx) {
1257 return new ConnectivityResources(ctx);
1258 }
1259
1260 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001261 * Create a HandlerThread to use in ConnectivityService.
1262 */
1263 public HandlerThread makeHandlerThread() {
1264 return new HandlerThread("ConnectivityServiceThread");
1265 }
1266
1267 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001268 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001269 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001270 public NetworkStackClientBase getNetworkStack() {
1271 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001272 }
1273
1274 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001275 * @see ProxyTracker
1276 */
1277 public ProxyTracker makeProxyTracker(@NonNull Context context,
1278 @NonNull Handler connServiceHandler) {
1279 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1280 }
1281
1282 /**
1283 * @see NetIdManager
1284 */
1285 public NetIdManager makeNetIdManager() {
1286 return new NetIdManager();
1287 }
1288
1289 /**
1290 * @see NetworkUtils#queryUserAccess(int, int)
1291 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001292 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1293 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001294 }
1295
1296 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001297 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1298 * requires CAP_NET_ADMIN, which the unit tests do not have.
1299 */
1300 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1301 InetSocketAddress remote) {
1302 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1303 }
1304
1305 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001306 * @see MultinetworkPolicyTracker
1307 */
1308 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1309 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1310 return new MultinetworkPolicyTracker(c, h, r);
1311 }
1312
Aaron Huang330a4c02020-10-27 03:36:19 +08001313 /**
1314 * @see BatteryStatsManager
1315 */
1316 public void reportNetworkInterfaceForTransports(Context context, String iface,
1317 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001318 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001319 context.getSystemService(BatteryStatsManager.class);
1320 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1321 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001322
1323 public boolean getCellular464XlatEnabled() {
1324 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1325 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001326
1327 /**
1328 * @see PendingIntent#intentFilterEquals
1329 */
1330 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1331 return a.intentFilterEquals(b);
1332 }
1333
1334 /**
1335 * @see LocationPermissionChecker
1336 */
1337 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1338 return new LocationPermissionChecker(context);
1339 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001340
1341 /**
1342 * @see DeviceConfigUtils#isFeatureEnabled
1343 */
1344 public boolean isFeatureEnabled(Context context, String name, boolean defaultEnabled) {
1345 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, name,
1346 TETHERING_MODULE_NAME, defaultEnabled);
1347 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001348
1349 /**
1350 * Get the BpfNetMaps implementation to use in ConnectivityService.
1351 * @param netd
1352 * @return BpfNetMaps implementation.
1353 */
1354 public BpfNetMaps getBpfNetMaps(INetd netd) {
1355 return new BpfNetMaps(netd);
1356 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001357 }
1358
junyulaie7c7d2a2021-01-26 15:29:15 +08001359 public ConnectivityService(Context context) {
1360 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001361 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1362 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001363 }
1364
1365 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001366 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1367 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001368 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001369
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001370 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001371 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001372 mSystemProperties = mDeps.getSystemProperties();
1373 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001374 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001375 mResources = deps.getResources(mContext);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001376 mNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_UID);
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09001377 mSystemNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001378
Hugo Benichi208c0102016-07-28 17:53:06 +09001379 mMetricsLog = logger;
Chalard Jean96a4f4b2019-12-10 22:16:53 +09001380 mNetworkRanker = new NetworkRanker();
James Mattis45d81842021-01-10 14:24:24 -08001381 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1382 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001383 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001384 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001385 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001386 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1387 mDefaultNetworkRequests.add(mDefaultRequest);
1388 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001389
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001390 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001391 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001392
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001393 // The default WiFi request is a background request so that apps using WiFi are
1394 // migrated to a better network (typically ethernet) when one comes up, instead
1395 // of staying on WiFi forever.
1396 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1397 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1398
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001399 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1400 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1401 NetworkRequest.Type.BACKGROUND_REQUEST);
1402
Chalard Jean0702f982021-09-16 21:50:07 +09001403 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1404 // TODO: Consider making the timer customizable.
1405 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1406 mCellularRadioTimesharingCapable =
1407 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1408
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001409 mHandlerThread = mDeps.makeHandlerThread();
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001410 mHandlerThread.start();
1411 mHandler = new InternalHandler(mHandlerThread.getLooper());
1412 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001413 mConnectivityDiagnosticsHandler =
1414 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001415
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001416 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001417 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001418
junyulaie7c7d2a2021-01-26 15:29:15 +08001419 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001420 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001421 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001422 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001423
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001424 mNetd = netd;
Wayne Ma2fde98c2022-01-17 18:04:05 +08001425 mBpfNetMaps = mDeps.getBpfNetMaps(netd);
Wink Saville32506bc2013-06-29 21:10:57 -07001426 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001427 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001428 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08001429 if (SdkLevel.isAtLeastT()) {
1430 mCarrierPrivilegeAuthenticator =
1431 new CarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
1432 } else {
1433 mCarrierPrivilegeAuthenticator = null;
1434 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001435
Sudheer Shanka9967d462021-03-18 19:09:25 +00001436 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001437 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1438 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001439 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001440
1441 final PowerManager powerManager = (PowerManager) context.getSystemService(
1442 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001443 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001444 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001445
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001446 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1447 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001448 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001449 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001450 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001451 mProtectedNetworks.add(p);
1452 } else {
1453 if (DBG) loge("Ignoring protectedNetwork " + p);
1454 }
1455 }
1456
soma, kawata29444ae2019-05-23 09:30:40 +09001457 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1458
Wayne Ma2fde98c2022-01-17 18:04:05 +08001459 mPermissionMonitor = new PermissionMonitor(mContext, mNetd, mBpfNetMaps);
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -07001460
James Mattis02220e22021-03-13 19:27:21 -08001461 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001462 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001463 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001464 final IntentFilter userIntentFilter = new IntentFilter();
1465 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1466 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1467 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1468 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001469
James Mattis02220e22021-03-13 19:27:21 -08001470 // Listen to package add/removes for netd
1471 final IntentFilter packageIntentFilter = new IntentFilter();
1472 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1473 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1474 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1475 packageIntentFilter.addDataScheme("package");
1476 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001477 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001478
lucaslind5c2d072021-02-20 18:59:47 +08001479 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001480
lucaslin66f44212021-02-23 01:12:55 +08001481 mNetdCallback = new NetdCallback();
1482 try {
1483 mNetd.registerUnsolicitedEventListener(mNetdCallback);
1484 } catch (RemoteException | ServiceSpecificException e) {
1485 loge("Error registering event listener :" + e);
1486 }
1487
Erik Kline05f2b402015-04-30 12:58:40 +09001488 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1489 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001490
junyulai7e06ad42019-03-04 22:45:36 +08001491 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001492 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001493 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001494
1495 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001496 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001497 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1498 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001499 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001500 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1501 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001502
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001503 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001504 mContext, mHandler, () -> updateAvoidBadWifi());
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001505 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001506
Chiachang Wangc1215d32020-10-20 15:38:58 +08001507 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001508 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001509
Chalard Jean28018572020-12-21 18:36:52 +09001510 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1511 // request that doesn't allow fallback to the default network. It should never be visible
1512 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1513 // arguments like the handler or the DnsResolver.
1514 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001515 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001516 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001517 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001518 new LinkProperties(), new NetworkCapabilities(),
1519 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001520 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1521 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001522
1523 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001524 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1525 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1526 // Even if it could, running on S would at least require mocking out the BPF map,
1527 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1528 // the bpf syscall. http://aosp/1907693
1529 if (SdkLevel.isAtLeastT()) {
1530 mDscpPolicyTracker = new DscpPolicyTracker();
1531 }
Tyler Wear72388212021-09-09 14:49:02 -07001532 } catch (ErrnoException e) {
1533 loge("Unable to create DscpPolicyTracker");
1534 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001535 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001536
Chalard Jean46adcf32018-04-18 20:18:38 +09001537 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001538 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1539 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001540 }
1541
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001542 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1543 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001544 final NetworkCapabilities netCap = new NetworkCapabilities();
1545 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001546 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001547 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001548 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001549 return netCap;
1550 }
1551
James Mattis45d81842021-01-10 14:24:24 -08001552 private NetworkRequest createDefaultRequest() {
1553 return createDefaultInternetRequestForTransport(
1554 TYPE_NONE, NetworkRequest.Type.REQUEST);
1555 }
1556
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001557 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001558 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001559 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001560 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001561 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001562 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001563 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001564 netCap.addTransportType(transportType);
1565 }
James Mattis45d81842021-01-10 14:24:24 -08001566 return createNetworkRequest(type, netCap);
1567 }
1568
1569 private NetworkRequest createNetworkRequest(
1570 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001571 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001572 }
1573
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001574 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1575 NetworkRequest.Type type) {
1576 final NetworkCapabilities netCap = new NetworkCapabilities();
1577 netCap.clearAll();
1578 netCap.addCapability(capability);
1579 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1580 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1581 }
1582
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001583 // Used only for testing.
1584 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001585 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001586 // changing ContentResolver to make registerContentObserver non-final).
1587 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1588 // by subclassing SettingsObserver.
1589 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001590 void updateAlwaysOnNetworks() {
1591 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001592 }
1593
Erik Kline9a62f012018-03-21 07:18:33 -07001594 // See FakeSettingsProvider comment above.
1595 @VisibleForTesting
1596 void updatePrivateDnsSettings() {
1597 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1598 }
1599
paulhu51f77dc2021-06-07 02:34:20 +00001600 @VisibleForTesting
1601 void updateMobileDataPreferredUids() {
1602 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1603 }
1604
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09001605 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, int id) {
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001606 final boolean enable = mContext.getResources().getBoolean(id);
1607 handleAlwaysOnNetworkRequest(networkRequest, enable);
1608 }
1609
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001610 private void handleAlwaysOnNetworkRequest(
1611 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001612 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001613 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001614 handleAlwaysOnNetworkRequest(networkRequest, enable);
1615 }
1616
1617 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001618 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001619 if (enable == isEnabled) {
1620 return; // Nothing to do.
1621 }
1622
1623 if (enable) {
1624 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001625 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001626 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001627 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001628 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001629 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1630 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001631 }
1632 }
1633
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001634 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001635 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1636 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1637 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1638 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001639 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1640 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001641 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001642 }
1643
paulhu51f77dc2021-06-07 02:34:20 +00001644 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001645 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001646 private void registerSettingsCallbacks() {
1647 // Watch for global HTTP proxy changes.
1648 mSettingsObserver.observe(
1649 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1650 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1651
1652 // Watch for whether or not to keep mobile data always on.
1653 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001654 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001655 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1656
1657 // Watch for whether or not to keep wifi always on.
1658 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001659 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001660 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001661
1662 // Watch for mobile data preferred uids changes.
1663 mSettingsObserver.observe(
1664 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1665 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001666 }
1667
Erik Kline31b4a9e2018-01-11 21:07:29 +09001668 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001669 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1670 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001671 }
1672 }
1673
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001674 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001675 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1676 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001677 return mNextNetworkRequestId++;
1678 }
1679
junyulai74f9a8b2018-06-13 15:00:37 +08001680 @VisibleForTesting
1681 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001682 if (network == null) {
1683 return null;
1684 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001685 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001686 }
1687
1688 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001689 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001690 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001691 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001692 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001693
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001694 // TODO: determine what to do when more than one VPN applies to |uid|.
1695 private NetworkAgentInfo getVpnForUid(int uid) {
1696 synchronized (mNetworkForNetId) {
1697 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1698 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
1699 if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) {
1700 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001701 }
1702 }
1703 }
1704 return null;
1705 }
1706
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001707 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001708 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001709 final NetworkAgentInfo nai = getVpnForUid(uid);
1710 if (nai != null) return nai.declaredUnderlyingNetworks;
1711 return null;
1712 }
1713
Lorenzo Colittia7574052021-01-19 01:33:05 +09001714 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001715 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001716
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001717 final Network[] networks = getVpnUnderlyingNetworks(uid);
1718 if (networks != null) {
1719 // getUnderlyingNetworks() returns:
1720 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1721 // empty array => the VPN explicitly said "no default network".
1722 // non-empty array => the VPN specified one or more default networks; we use the
1723 // first one.
1724 if (networks.length > 0) {
1725 nai = getNetworkAgentInfoForNetwork(networks[0]);
1726 } else {
1727 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001728 }
1729 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001730 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001731 }
1732
1733 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001734 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001735 */
paulhu7aeba372020-12-30 00:42:19 +08001736 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1737 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001738 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001739 if (ignoreBlocked) {
1740 return false;
1741 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001742 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001743 final long ident = Binder.clearCallingIdentity();
1744 try {
1745 final boolean metered = nc == null ? true : nc.isMetered();
1746 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1747 } finally {
1748 Binder.restoreCallingIdentity(ident);
1749 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001750 }
1751
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001752 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001753 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1754 return;
1755 }
Hugo Benichi47011212017-03-30 10:46:05 +09001756 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001757 synchronized (mBlockedAppUids) {
1758 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001759 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001760 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001761 blocked = false;
1762 } else {
1763 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001764 }
1765 }
Hugo Benichi47011212017-03-30 10:46:05 +09001766 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1767 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1768 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001769 }
1770
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001771 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001772 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1773 return;
1774 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001775 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001776 final int requestId = nri.getActiveRequest() != null
1777 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001778 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001779 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001780 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001781 }
1782
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001783 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001784 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001785 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001786 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001787 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001788 @NonNull
1789 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1790 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001791 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1792 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1793 // but only exists if an app asks about them or requests them. Ensure the requesting app
1794 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001795 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001796 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1797 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1798 null /* extraInfo */);
1799 }
1800 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001801 return filtered;
1802 }
1803
1804 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1805 boolean ignoreBlocked) {
1806 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1807 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001808 }
1809
1810 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001811 * Return NetworkInfo for the active (i.e., connected) network interface.
1812 * It is assumed that at most one network is active at a time. If more
1813 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001814 * @return the info for the active network, or {@code null} if none is
1815 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001816 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001817 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001818 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001819 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001820 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001821 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1822 if (nai == null) return null;
1823 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1824 maybeLogBlockedNetworkInfo(networkInfo, uid);
1825 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001826 }
1827
Paul Jensen1f567382015-02-13 14:18:39 -05001828 @Override
1829 public Network getActiveNetwork() {
1830 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001831 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00001832 }
1833
1834 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001835 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001836 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001837 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001838 }
1839
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001840 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001841 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1842 if (vpnNai != null) {
1843 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1844 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1845 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09001846 }
Paul Jensen1f567382015-02-13 14:18:39 -05001847 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001848
James Mattis2516da32021-01-31 17:06:19 -08001849 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001850 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1851 ignoreBlocked)) {
1852 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001853 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001854 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05001855 }
1856
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001857 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001858 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001859 PermissionUtils.enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001860 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1861 if (nai == null) return null;
1862 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001863 }
1864
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001865 /** Returns a NetworkInfo object for a network that doesn't exist. */
1866 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1867 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1868 getNetworkTypeName(networkType), "" /* subtypeName */);
1869 info.setIsAvailable(true);
1870 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1871 // background data is restricted.
1872 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1873 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1874 ? DetailedState.BLOCKED
1875 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001876 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1877 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001878 return info;
1879 }
1880
Lorenzo Colittia7574052021-01-19 01:33:05 +09001881 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001882 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1883 return null;
1884 }
1885 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001886 if (nai == null) {
1887 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001888 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001889 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1890 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001891 }
1892
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001893 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001894 public NetworkInfo getNetworkInfo(int networkType) {
1895 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001896 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001897 if (getVpnUnderlyingNetworks(uid) != null) {
1898 // A VPN is active, so we may need to return one of its underlying networks. This
1899 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09001900 // getNetworkAgentInfoForUid.
1901 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1902 if (nai == null) return null;
1903 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1904 if (networkInfo.getType() == networkType) {
1905 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001906 }
1907 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001908 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001909 }
1910
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001911 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001912 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001913 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001914 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001915 if (nai == null) return null;
1916 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001917 }
1918
1919 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001920 public NetworkInfo[] getAllNetworkInfo() {
1921 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08001922 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04001923 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1924 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001925 NetworkInfo info = getNetworkInfo(networkType);
1926 if (info != null) {
1927 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001928 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001929 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001930 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001931 }
1932
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001933 @Override
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001934 public Network getNetworkForType(int networkType) {
1935 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001936 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1937 return null;
1938 }
1939 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1940 if (nai == null) {
1941 return null;
1942 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001943 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001944 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
1945 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001946 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001947 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001948 }
1949
1950 @Override
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001951 public Network[] getAllNetworks() {
1952 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001953 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04001954 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001955 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04001956 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001957 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04001958 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001959 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001960 }
1961
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001962 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08001963 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001964 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001965 // The basic principle is: if an app's traffic could possibly go over a
1966 // network, without the app doing anything multinetwork-specific,
1967 // (hence, by "default"), then include that network's capabilities in
1968 // the array.
1969 //
1970 // In the normal case, app traffic only goes over the system's default
1971 // network connection, so that's the only network returned.
1972 //
1973 // With a VPN in force, some app traffic may go into the VPN, and thus
1974 // over whatever underlying networks the VPN specifies, while other app
1975 // traffic may go over the system default network (e.g.: a split-tunnel
1976 // VPN, or an app disallowed by the VPN), so the set of networks
1977 // returned includes the VPN's underlying networks and the system
1978 // default.
1979 enforceAccessPermission();
1980
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001981 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001982
James Mattis2516da32021-01-31 17:06:19 -08001983 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
1984 if (!nri.isBeingSatisfied()) {
1985 continue;
1986 }
1987 final NetworkAgentInfo nai = nri.getSatisfier();
1988 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
1989 if (null != nc
1990 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
1991 && !result.containsKey(nai.network)) {
1992 result.put(
1993 nai.network,
1994 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08001995 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08001996 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
1997 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08001998 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001999 }
2000
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002001 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002002 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002003 if (null != networks) {
2004 for (final Network network : networks) {
2005 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2006 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002007 result.put(
2008 network,
2009 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002010 nc,
2011 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002012 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002013 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002014 }
2015 }
2016 }
2017
2018 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2019 out = result.values().toArray(out);
2020 return out;
2021 }
2022
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002023 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002024 public boolean isNetworkSupported(int networkType) {
2025 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002026 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002027 }
2028
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002029 /**
2030 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002031 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002032 * @return the ip properties for the active network, or {@code null} if
2033 * none is active
2034 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002035 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002036 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002037 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002038 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002039 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2040 if (nai == null) return null;
2041 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002042 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002043 }
2044
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002045 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002046 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002047 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002048 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002049 final LinkProperties lp = getLinkProperties(nai);
2050 if (lp == null) return null;
2051 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002052 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002053 }
2054
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002055 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002056 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002057 public LinkProperties getLinkProperties(Network network) {
2058 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002059 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2060 if (lp == null) return null;
2061 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002062 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002063 }
2064
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002065 @Nullable
2066 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002067 if (nai == null) {
2068 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002069 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002070 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002071 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002072 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002073 }
2074
Qingxi Lib2748102020-01-08 12:51:49 -08002075 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2076 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2077 }
2078
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002079 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002080 if (nai == null) return null;
2081 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002082 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002083 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002084 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002085 }
2086
2087 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002088 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2089 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002090 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002091 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002092 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002093 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002094 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002095 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002096 }
2097
Qingxi Libb8da982020-01-17 17:54:27 -08002098 @VisibleForTesting
2099 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002100 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002101 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002102 if (!checkSettingsPermission(callerPid, callerUid)) {
2103 newNc.setUids(null);
2104 newNc.setSSID(null);
lucaslin6adf5ac2021-10-19 15:04:56 +08002105 newNc.setUnderlyingNetworks(null);
Chalard Jean46adcf32018-04-18 20:18:38 +09002106 }
Etan Cohen107ae952018-12-30 17:59:59 -08002107 if (newNc.getNetworkSpecifier() != null) {
2108 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2109 }
Cody Kesting5ab1f552020-03-16 18:15:28 -07002110 newNc.setAdministratorUids(new int[0]);
Benedict Wong53de25f2021-03-24 14:01:51 -07002111 if (!checkAnyPermissionOf(
2112 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09002113 newNc.setAccessUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002114 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002115 }
Qingxi Libb8da982020-01-17 17:54:27 -08002116
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002117 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002118 }
2119
Roshan Pius98f59ec2021-02-23 08:47:39 -08002120 /**
2121 * Wrapper used to cache the permission check results performed for the corresponding
2122 * app. This avoid performing multiple permission checks for different fields in
2123 * NetworkCapabilities.
2124 * Note: This wrapper does not support any sort of invalidation and thus must not be
2125 * persistent or long-lived. It may only be used for the time necessary to
2126 * compute the redactions required by one particular NetworkCallback or
2127 * synchronous call.
2128 */
2129 private class RedactionPermissionChecker {
2130 private final int mCallingPid;
2131 private final int mCallingUid;
2132 @NonNull private final String mCallingPackageName;
2133 @Nullable private final String mCallingAttributionTag;
2134
2135 private Boolean mHasLocationPermission = null;
2136 private Boolean mHasLocalMacAddressPermission = null;
2137 private Boolean mHasSettingsPermission = null;
2138
2139 RedactionPermissionChecker(int callingPid, int callingUid,
2140 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2141 mCallingPid = callingPid;
2142 mCallingUid = callingUid;
2143 mCallingPackageName = callingPackageName;
2144 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002145 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002146
2147 private boolean hasLocationPermissionInternal() {
2148 final long token = Binder.clearCallingIdentity();
2149 try {
2150 return mLocationPermissionChecker.checkLocationPermission(
2151 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2152 null /* message */);
2153 } finally {
2154 Binder.restoreCallingIdentity(token);
2155 }
2156 }
2157
2158 /**
2159 * Returns whether the app holds location permission or not (might return cached result
2160 * if the permission was already checked before).
2161 */
2162 public boolean hasLocationPermission() {
2163 if (mHasLocationPermission == null) {
2164 // If there is no cached result, perform the check now.
2165 mHasLocationPermission = hasLocationPermissionInternal();
2166 }
2167 return mHasLocationPermission;
2168 }
2169
2170 /**
2171 * Returns whether the app holds local mac address permission or not (might return cached
2172 * result if the permission was already checked before).
2173 */
2174 public boolean hasLocalMacAddressPermission() {
2175 if (mHasLocalMacAddressPermission == null) {
2176 // If there is no cached result, perform the check now.
2177 mHasLocalMacAddressPermission =
2178 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2179 }
2180 return mHasLocalMacAddressPermission;
2181 }
2182
2183 /**
2184 * Returns whether the app holds settings permission or not (might return cached
2185 * result if the permission was already checked before).
2186 */
2187 public boolean hasSettingsPermission() {
2188 if (mHasSettingsPermission == null) {
2189 // If there is no cached result, perform the check now.
2190 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2191 }
2192 return mHasSettingsPermission;
2193 }
2194 }
2195
2196 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2197 @NetworkCapabilities.NetCapability long redaction) {
2198 return (redactions & redaction) != 0;
2199 }
2200
2201 /**
2202 * Use the provided |applicableRedactions| to check the receiving app's
2203 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2204 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2205 * before being sent to the corresponding app.
2206 */
2207 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2208 @NetworkCapabilities.RedactionType long applicableRedactions,
2209 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2210 boolean includeLocationSensitiveInfo) {
2211 long redactions = applicableRedactions;
2212 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2213 if (includeLocationSensitiveInfo
2214 && redactionPermissionChecker.hasLocationPermission()) {
2215 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2216 }
2217 }
2218 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2219 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2220 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2221 }
2222 }
2223 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2224 if (redactionPermissionChecker.hasSettingsPermission()) {
2225 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2226 }
2227 }
2228 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002229 }
2230
Qingxi Lib2748102020-01-08 12:51:49 -08002231 @VisibleForTesting
2232 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002233 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002234 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002235 int callingPid, int callingUid, @NonNull String callingPkgName,
2236 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002237 if (nc == null) {
2238 return null;
2239 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002240 // Avoid doing location permission check if the transport info has no location sensitive
2241 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002242 final RedactionPermissionChecker redactionPermissionChecker =
2243 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2244 callingAttributionTag);
2245 final long redactions = retrieveRequiredRedactions(
2246 nc.getApplicableRedactions(), redactionPermissionChecker,
2247 includeLocationSensitiveInfo);
2248 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002249 // Reset owner uid if not destined for the owner app.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002250 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002251 newNc.setOwnerUid(INVALID_UID);
2252 return newNc;
2253 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002254 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2255 if (nc.hasTransport(TRANSPORT_VPN)) {
2256 // Owner UIDs already checked above. No need to re-check.
2257 return newNc;
2258 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002259 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2260 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002261 // compatibility for older apps.
2262 if (!includeLocationSensitiveInfo
2263 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002264 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002265 newNc.setOwnerUid(INVALID_UID);
2266 return newNc;
2267 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002268 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002269 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002270 newNc.setOwnerUid(INVALID_UID);
2271 }
Qingxi Lib2748102020-01-08 12:51:49 -08002272 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002273 }
2274
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002275 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2276 LinkProperties lp, int callerPid, int callerUid) {
2277 if (lp == null) return new LinkProperties();
2278
2279 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2280 final boolean needsSanitization =
2281 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2282 if (!needsSanitization) {
2283 return new LinkProperties(lp);
2284 }
2285
2286 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002287 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002288 }
2289
2290 final LinkProperties newLp = new LinkProperties(lp);
2291 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2292 // object gets parceled.
2293 newLp.setCaptivePortalApiUrl(null);
2294 newLp.setCaptivePortalData(null);
2295 return newLp;
2296 }
2297
Roshan Pius08c94fb2020-01-16 12:17:17 -08002298 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2299 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002300 // There is no need to track the effective UID of the request here. If the caller
2301 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002302 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002303 // Unprivileged apps can only pass in null or their own UID.
2304 if (nc.getUids() == null) {
2305 // If the caller passes in null, the callback will also match networks that do not
2306 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2307 // In this case, redact everything in the request immediately. This ensures that the
2308 // app is not able to get any redacted information by filing an unredacted request
2309 // and observing whether the request matches something.
2310 if (nc.getNetworkSpecifier() != null) {
2311 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2312 }
2313 } else {
2314 nc.setSingleUid(callerUid);
2315 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002316 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002317 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002318 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002319
2320 // Clear owner UID; this can never come from an app.
2321 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002322 }
2323
Chalard Jean38354d12018-03-20 19:13:57 +09002324 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002325 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002326 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2327 }
2328 }
2329
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002330 @Override
2331 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2332 enforceAccessPermission();
2333 final int callerUid = Binder.getCallingUid();
2334 final long token = Binder.clearCallingIdentity();
2335 try {
2336 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2337 } finally {
2338 Binder.restoreCallingIdentity(token);
2339 }
2340 }
2341
junyulaiebd15162021-03-03 12:09:05 +08002342 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002343 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002344 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002345 // This contains IMSI details, so make sure the caller is privileged.
paulhudf23d662021-01-25 18:53:17 +08002346 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002347
Serik Beketayev05130302021-01-15 16:47:25 -08002348 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002349 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002350 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2351 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002352 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002353 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002354 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002355 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2356 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002357 }
2358 }
2359 return result.toArray(new NetworkState[result.size()]);
2360 }
2361
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002362 @Override
junyulaiebd15162021-03-03 12:09:05 +08002363 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002364 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002365 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002366 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002367
2368 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2369 for (Network network : getAllNetworks()) {
2370 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Junyu Laiddecb662021-08-17 08:44:36 +00002371 if (nai != null && nai.everConnected) {
junyulaiebd15162021-03-03 12:09:05 +08002372 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2373 // NetworkCapabilities, which may contain UIDs of apps to which the
2374 // network applies. Should the UIDs be cleared so as not to leak or
2375 // interfere ?
2376 result.add(nai.getNetworkStateSnapshot());
2377 }
2378 }
2379 return result;
2380 }
2381
2382 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002383 public boolean isActiveNetworkMetered() {
2384 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002385
Qingxi Lib2748102020-01-08 12:51:49 -08002386 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002387 if (caps != null) {
2388 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2389 } else {
2390 // Always return the most conservative value
2391 return true;
2392 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002393 }
2394
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002395 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002396 * Ensures that the system cannot call a particular method.
2397 */
2398 private boolean disallowedBecauseSystemCaller() {
2399 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002400 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2401 // for devices launched with Q and above. However, existing devices upgrading to Q and
2402 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002403 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002404 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002405 log("This method exists only for app backwards compatibility"
2406 + " and must not be called by system services.");
2407 return true;
2408 }
2409 return false;
2410 }
2411
paulhub2c28682021-08-18 18:35:54 +08002412 private int getAppUid(final String app, final UserHandle user) {
2413 final PackageManager pm =
2414 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2415 final long token = Binder.clearCallingIdentity();
2416 try {
2417 return pm.getPackageUid(app, 0 /* flags */);
2418 } catch (PackageManager.NameNotFoundException e) {
2419 return -1;
2420 } finally {
2421 Binder.restoreCallingIdentity(token);
2422 }
2423 }
2424
2425 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2426 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2427 if (getAppUid(packageName, user) != callingUid) {
2428 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2429 }
2430 }
2431
Lorenzo Colitti23862912018-09-28 11:31:55 +09002432 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002433 * Ensure that a network route exists to deliver traffic to the specified
2434 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002435 * @param networkType the type of the network over which traffic to the
2436 * specified host is to be routed
2437 * @param hostAddress the IP address of the host to which the route is
2438 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002439 * @return {@code true} on success, {@code false} on failure
2440 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002441 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002442 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2443 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002444 if (disallowedBecauseSystemCaller()) {
2445 return false;
2446 }
paulhub2c28682021-08-18 18:35:54 +08002447 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002448 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002449 if (mProtectedNetworks.contains(networkType)) {
paulhu8e96a752019-08-12 16:25:11 +08002450 enforceConnectivityRestrictedNetworksPermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002451 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002452
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002453 InetAddress addr;
2454 try {
2455 addr = InetAddress.getByAddress(hostAddress);
2456 } catch (UnknownHostException e) {
2457 if (DBG) log("requestRouteToHostAddress got " + e.toString());
2458 return false;
2459 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002460
The Android Open Source Project28527d22009-03-03 19:31:44 -08002461 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002462 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002463 return false;
2464 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002465
2466 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2467 if (nai == null) {
2468 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
2469 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2470 } else {
2471 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2472 }
2473 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002474 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002475
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002476 DetailedState netState;
2477 synchronized (nai) {
2478 netState = nai.networkInfo.getDetailedState();
2479 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002480
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002481 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002482 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002483 log("requestRouteToHostAddress on down network "
2484 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002485 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002486 }
2487 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002488 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002489
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002490 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002491 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002492 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002493 LinkProperties lp;
2494 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002495 synchronized (nai) {
2496 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002497 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002498 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002499 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002500 if (DBG) {
2501 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2502 }
Wink Saville32506bc2013-06-29 21:10:57 -07002503 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002504 } finally {
2505 Binder.restoreCallingIdentity(token);
2506 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002507 }
2508
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002509 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002510 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002511 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002512 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002513 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002514 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002515 if (bestRoute.getGateway().equals(addr)) {
2516 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002517 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002518 } else {
2519 // if we will connect to this through another route, add a direct route
2520 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002521 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002522 }
2523 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002524 if (DBG) log("Adding legacy route " + bestRoute +
2525 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002526
2527 final String dst = bestRoute.getDestinationLinkAddress().toString();
2528 final String nextHop = bestRoute.hasGateway()
2529 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002530 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002531 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2532 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002533 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002534 return false;
2535 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002536 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002537 }
2538
paulhu7c0a2e62021-01-08 00:51:49 +08002539 class DnsResolverUnsolicitedEventCallback extends
2540 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002541 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002542 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002543 try {
2544 mHandler.sendMessage(mHandler.obtainMessage(
2545 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002546 new PrivateDnsValidationUpdate(event.netId,
2547 InetAddresses.parseNumericAddress(event.ipAddress),
2548 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002549 } catch (IllegalArgumentException e) {
2550 loge("Error parsing ip address in validation event");
2551 }
2552 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002553
2554 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002555 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2556 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002557 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2558 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2559 // event callback for certain nai. e.g. cellular. Register here to pass to
2560 // NetworkMonitor instead.
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002561 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allow one
2562 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2563 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002564 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002565 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002566 }
2567 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002568
2569 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002570 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2571 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2572 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002573 }
dalyk1720e542018-03-05 12:42:22 -05002574
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002575 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002576 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002577 return this.VERSION;
2578 }
2579
2580 @Override
2581 public String getInterfaceHash() {
2582 return this.HASH;
2583 }
paulhu7c0a2e62021-01-08 00:51:49 +08002584 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002585
2586 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002587 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2588 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002589
paulhu7c0a2e62021-01-08 00:51:49 +08002590 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002591 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002592 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002593 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002594 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002595 }
2596 }
2597
Sudheer Shanka9967d462021-03-18 19:09:25 +00002598 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002599 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002600 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002601 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2602 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002603 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002604 };
2605
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002606 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002607 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002608 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002609 }
2610
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002611 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002612 for (String permission : permissions) {
2613 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002614 return true;
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002615 }
2616 }
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002617 return false;
2618 }
2619
paulhu1a407652019-03-22 16:35:06 +08002620 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2621 for (String permission : permissions) {
2622 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2623 return true;
2624 }
2625 }
2626 return false;
2627 }
2628
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002629 private void enforceAnyPermissionOf(String... permissions) {
2630 if (!checkAnyPermissionOf(permissions)) {
2631 throw new SecurityException("Requires one of the following permissions: "
2632 + String.join(", ", permissions) + ".");
2633 }
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002634 }
2635
Paul Jensen83f5d572014-08-29 09:54:01 -04002636 private void enforceInternetPermission() {
2637 mContext.enforceCallingOrSelfPermission(
2638 android.Manifest.permission.INTERNET,
2639 "ConnectivityService");
2640 }
2641
The Android Open Source Project28527d22009-03-03 19:31:44 -08002642 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002643 mContext.enforceCallingOrSelfPermission(
2644 android.Manifest.permission.ACCESS_NETWORK_STATE,
2645 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002646 }
2647
paulhua6ee2122021-02-22 15:40:43 +08002648 /**
2649 * Performs a strict and comprehensive check of whether a calling package is allowed to
2650 * change the state of network, as the condition differs for pre-M, M+, and
2651 * privileged/preinstalled apps. The caller is expected to have either the
2652 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2653 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2654 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2655 * permission and cannot be revoked. See http://b/23597341
2656 *
2657 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2658 * of this app will be updated to the current time.
2659 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002660 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002661 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2662 == PackageManager.PERMISSION_GRANTED) {
2663 return;
2664 }
2665
2666 if (callingPkg == null) {
2667 throw new SecurityException("Calling package name is null.");
2668 }
2669
2670 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2671 final int uid = mDeps.getCallingUid();
2672 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2673 callingPkg, callingAttributionTag, null /* message */);
2674
2675 if (mode == AppOpsManager.MODE_ALLOWED) {
2676 return;
2677 }
2678
2679 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2680 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2681 return;
2682 }
2683
2684 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2685 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2686 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002687 }
2688
Charles He9369e612017-05-15 17:07:18 +01002689 private void enforceSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002690 enforceAnyPermissionOf(
Charles He9369e612017-05-15 17:07:18 +01002691 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002692 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002693 }
2694
paulhu8e96a752019-08-12 16:25:11 +08002695 private void enforceNetworkFactoryPermission() {
paulhub6ba8e82020-03-04 09:43:41 +08002696 enforceAnyPermissionOf(
paulhu8e96a752019-08-12 16:25:11 +08002697 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002698 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002699 }
2700
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002701 private void enforceNetworkFactoryOrSettingsPermission() {
2702 enforceAnyPermissionOf(
2703 android.Manifest.permission.NETWORK_SETTINGS,
2704 android.Manifest.permission.NETWORK_FACTORY,
2705 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2706 }
2707
2708 private void enforceNetworkFactoryOrTestNetworksPermission() {
2709 enforceAnyPermissionOf(
2710 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2711 android.Manifest.permission.NETWORK_FACTORY,
2712 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2713 }
2714
Chalard Jean9a396cc2018-02-21 18:43:54 +09002715 private boolean checkSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002716 return checkAnyPermissionOf(
2717 android.Manifest.permission.NETWORK_SETTINGS,
2718 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002719 }
2720
2721 private boolean checkSettingsPermission(int pid, int uid) {
2722 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002723 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2724 || PERMISSION_GRANTED == mContext.checkPermission(
2725 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002726 }
2727
paulhu8e96a752019-08-12 16:25:11 +08002728 private void enforceNetworkStackOrSettingsPermission() {
2729 enforceAnyPermissionOf(
2730 android.Manifest.permission.NETWORK_SETTINGS,
2731 android.Manifest.permission.NETWORK_STACK,
2732 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2733 }
2734
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002735 private void enforceNetworkStackSettingsOrSetup() {
2736 enforceAnyPermissionOf(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002737 android.Manifest.permission.NETWORK_SETTINGS,
2738 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002739 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002740 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002741 }
2742
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002743 private void enforceAirplaneModePermission() {
2744 enforceAnyPermissionOf(
2745 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2746 android.Manifest.permission.NETWORK_SETTINGS,
2747 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2748 android.Manifest.permission.NETWORK_STACK,
2749 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2750 }
2751
James Mattis8378aec2021-01-26 14:05:36 -08002752 private void enforceOemNetworkPreferencesPermission() {
2753 mContext.enforceCallingOrSelfPermission(
2754 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2755 "ConnectivityService");
2756 }
2757
James Mattisfa270db2021-05-31 17:11:10 -07002758 private void enforceManageTestNetworksPermission() {
2759 mContext.enforceCallingOrSelfPermission(
2760 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2761 "ConnectivityService");
2762 }
2763
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002764 private boolean checkNetworkStackPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002765 return checkAnyPermissionOf(
2766 android.Manifest.permission.NETWORK_STACK,
2767 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002768 }
2769
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002770 private boolean checkNetworkStackPermission(int pid, int uid) {
2771 return checkAnyPermissionOf(pid, uid,
2772 android.Manifest.permission.NETWORK_STACK,
2773 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2774 }
2775
paulhu1a407652019-03-22 16:35:06 +08002776 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2777 return checkAnyPermissionOf(pid, uid,
2778 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002779 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2780 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002781 }
2782
Hugo Benichibd0cc762016-07-19 15:59:27 +09002783 private void enforceConnectivityRestrictedNetworksPermission() {
2784 try {
2785 mContext.enforceCallingOrSelfPermission(
2786 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2787 "ConnectivityService");
2788 return;
2789 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
paulhu8e96a752019-08-12 16:25:11 +08002790 // TODO: Remove this fallback check after all apps have declared
2791 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2792 mContext.enforceCallingOrSelfPermission(
2793 android.Manifest.permission.CONNECTIVITY_INTERNAL,
2794 "ConnectivityService");
Hugo Benichibd0cc762016-07-19 15:59:27 +09002795 }
2796
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002797 private void enforceKeepalivePermission() {
Lorenzo Colittif25beee2015-09-08 13:21:48 +09002798 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002799 }
2800
Roshan Pius98f59ec2021-02-23 08:47:39 -08002801 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2802 return PERMISSION_GRANTED == mContext.checkPermission(
2803 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2804 }
2805
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002806 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002807 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002808 }
2809
2810 private void sendInetConditionBroadcast(NetworkInfo info) {
2811 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2812 }
2813
Wink Saville4f0de1e2011-08-04 15:01:58 -07002814 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002815 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002816 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002817 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002818 if (info.isFailover()) {
2819 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2820 info.setFailover(false);
2821 }
2822 if (info.getReason() != null) {
2823 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2824 }
2825 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002826 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2827 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002828 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002829 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002830 return intent;
2831 }
2832
2833 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2834 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2835 }
2836
Chiachang Wang3bc52762021-11-25 14:17:57 +08002837 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
2838 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002839 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09002840 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09002841 if (!mSystemReady
2842 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002843 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002844 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002845 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002846 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002847 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002848 }
2849
Dianne Hackborn66dd0332015-12-09 17:22:26 -08002850 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07002851 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002852 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07002853 final NetworkInfo ni = intent.getParcelableExtra(
2854 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08002855 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2856 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2857 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08002858 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002859 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07002860 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00002861 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002862 } finally {
2863 Binder.restoreCallingIdentity(ident);
2864 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002865 }
2866 }
2867
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002868 /**
Aaron Huang96011892020-06-27 07:18:23 +08002869 * Called by SystemServer through ConnectivityManager when the system is ready.
2870 */
2871 @Override
2872 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002873 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08002874 throw new SecurityException("Calling Uid is not system uid.");
2875 }
2876 systemReadyInternal();
2877 }
2878
2879 /**
2880 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002881 */
2882 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08002883 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09002884 // Load flags after PackageManager is ready to query module version
2885 mFlags.loadFlags(mDeps, mContext);
2886
Aaron Huang9a57acf2020-12-08 10:03:29 +08002887 // Since mApps in PermissionMonitor needs to be populated first to ensure that
2888 // listening network request which is sent by MultipathPolicyTracker won't be added
2889 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
2890 // be called after PermissionMonitor#startMonitoring().
2891 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
2892 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
2893 // to ensure the tracking will be initialized correctly.
paulhuc62d3c22019-11-19 17:55:31 +08002894 mPermissionMonitor.startMonitoring();
Chalard Jeane4f9bd92018-06-08 12:47:42 +09002895 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08002896 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002897
Hugo Benichie5220992017-04-26 14:53:28 +09002898 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002899 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002900 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07002901 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002902 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002903 }
2904 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002905
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002906 // Create network requests for always-on networks.
2907 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00002908
2909 // Update mobile data preference if necessary.
2910 // Note that empty uid list can be skip here only because no uid rules applied before system
2911 // ready. Normally, the empty uid list means to clear the uids rules on netd.
2912 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
2913 updateMobileDataPreferredUids();
2914 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002915 }
2916
The Android Open Source Project28527d22009-03-03 19:31:44 -08002917 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002918 * Start listening for default data network activity state changes.
2919 */
2920 @Override
2921 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08002922 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002923 }
2924
2925 /**
2926 * Stop listening for default data network activity state changes.
2927 */
2928 @Override
2929 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08002930 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002931 }
2932
2933 /**
2934 * Check whether the default network radio is currently active.
2935 */
2936 @Override
2937 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08002938 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002939 }
2940
2941 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09002942 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09002943 * and set it on it's iface.
2944 */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002945 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2946 final String iface = newLp.getInterfaceName();
2947 final int mtu = newLp.getMtu();
Pierre Imai07c53a32016-02-08 16:01:40 +09002948 if (oldLp == null && mtu == 0) {
2949 // Silently ignore unset MTU value.
2950 return;
2951 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002952 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2953 if (VDBG) log("identical MTU - not setting");
2954 return;
2955 }
paulhucbbc3db2019-03-08 16:35:20 +08002956 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002957 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002958 return;
2959 }
sy.yun4aa73922013-09-02 05:24:09 +09002960
w19976e714f1d2014-08-05 15:18:11 -07002961 // Cannot set MTU without interface name
2962 if (TextUtils.isEmpty(iface)) {
2963 loge("Setting MTU size with null iface.");
2964 return;
2965 }
2966
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002967 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09002968 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08002969 mNetd.interfaceSetMtu(iface, mtu);
2970 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08002971 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002972 }
2973 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002974
Chenbo Feng15416292018-11-08 17:36:21 -08002975 @VisibleForTesting
2976 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04002977
lucaslin821c9782018-11-28 19:27:52 +08002978 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002979 String[] values = null;
2980 if (tcpBufferSizes != null) {
2981 values = tcpBufferSizes.split(",");
2982 }
2983
2984 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07002985 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002986 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2987 values = tcpBufferSizes.split(",");
2988 }
2989
2990 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2991
2992 try {
Aaron Huang6616df32020-10-30 22:04:25 +08002993 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002994
Chenbo Feng15416292018-11-08 17:36:21 -08002995 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2996 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2997 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002998 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08002999 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003000 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003001 }
3002 }
3003
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003004 @Override
3005 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003006 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003007 NETWORK_RESTORE_DELAY_PROP_NAME);
3008 if(restoreDefaultNetworkDelayStr != null &&
3009 restoreDefaultNetworkDelayStr.length() != 0) {
3010 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003011 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003012 } catch (NumberFormatException e) {
3013 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003014 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003015 // if the system property isn't set, use the value for the apn type
3016 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3017
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003018 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3019 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003020 }
3021 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003022 }
3023
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003024 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
3025 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
3026 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003027 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003028 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003029 // Start gathering diagnostic information.
3030 netDiags.add(new NetworkDiagnostics(
3031 nai.network,
3032 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003033 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003034 DIAG_TIME_MS));
3035 }
3036
3037 for (NetworkDiagnostics netDiag : netDiags) {
3038 pw.println();
3039 netDiag.waitForMeasurements();
3040 netDiag.dump(pw);
3041 }
3042 }
3043
The Android Open Source Project28527d22009-03-03 19:31:44 -08003044 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003045 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3046 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003047 if (!checkDumpPermission(mContext, TAG, writer)) return;
3048
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003049 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003050 }
3051
lucaslin99473f62020-12-10 15:10:54 +08003052 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3053 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3054 != PackageManager.PERMISSION_GRANTED) {
3055 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003056 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003057 + " due to missing android.permission.DUMP permission");
3058 return false;
3059 } else {
3060 return true;
3061 }
3062 }
3063
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003064 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003065 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003066
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003067 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003068 dumpNetworkDiagnostics(pw);
3069 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003070 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003071 dumpNetworks(pw);
3072 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003073 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003074 dumpNetworkRequests(pw);
3075 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003076 }
Erik Kline9647f382015-06-05 17:47:34 +09003077
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003078 pw.print("NetworkProviders for:");
3079 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
3080 pw.print(" " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003081 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09003082 pw.println();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003083 pw.println();
3084
Chalard Jean5b409c72021-02-04 13:12:59 +09003085 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003086 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003087 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003088 pw.println("none");
3089 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003090 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003091 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003092 pw.println();
3093
James Mattis8b298a02021-06-01 22:34:04 -07003094 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003095 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003096 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003097 pw.decreaseIndent();
3098 pw.println();
3099
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003100 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003101 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003102 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003103 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003104 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003105
junyulaif2c67e42018-08-07 19:50:45 +08003106 pw.println("Status for known UIDs:");
3107 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003108 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003109 for (int i = 0; i < size; i++) {
3110 // Don't crash if the array is modified while dumping in bugreports.
3111 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003112 final int uid = mUidBlockedReasons.keyAt(i);
3113 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3114 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003115 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003116 } catch (ArrayIndexOutOfBoundsException e) {
3117 pw.println(" ArrayIndexOutOfBoundsException");
3118 } catch (ConcurrentModificationException e) {
3119 pw.println(" ConcurrentModificationException");
3120 }
3121 }
3122 pw.println();
3123 pw.decreaseIndent();
3124
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003125 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003126 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003127 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003128 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003129 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003130
Robert Greenwalt94e22142014-07-30 16:31:24 -07003131 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003132
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003133 pw.println();
markchien5e866652019-09-30 14:40:57 +08003134 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003135
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003136 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003137 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003138
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003139 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003140
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003141 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003142 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003143 pw.println("mNetworkRequestInfoLogs (most recent first):");
3144 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003145 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003146 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003147
3148 pw.println();
3149 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3150 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003151 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003152 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003153
3154 pw.println();
3155 pw.println("NetTransition WakeLock activity (most recent first):");
3156 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003157 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3158 pw.println("total releases: " + mTotalWakelockReleases);
3159 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3160 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3161 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3162 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3163 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3164 }
James Mattiscb1e0362021-04-06 17:07:42 -07003165 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003166
3167 pw.println();
3168 pw.println("bandwidth update requests (by uid):");
3169 pw.increaseIndent();
3170 synchronized (mBandwidthRequests) {
3171 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3172 pw.println("[" + mBandwidthRequests.keyAt(i)
3173 + "]: " + mBandwidthRequests.valueAt(i));
3174 }
3175 }
3176 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003177 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003178
James Mattiscb1e0362021-04-06 17:07:42 -07003179 pw.println();
3180 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3181 pw.increaseIndent();
3182 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003183 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003184 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003185
3186 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003187
3188 pw.println();
3189 pw.println("Permission Monitor:");
3190 pw.increaseIndent();
3191 mPermissionMonitor.dump(pw);
3192 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003193
3194 pw.println();
3195 pw.println("Legacy network activity:");
3196 pw.increaseIndent();
3197 mNetworkActivityTracker.dump(pw);
3198 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003199 }
3200
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003201 private void dumpNetworks(IndentingPrintWriter pw) {
3202 for (NetworkAgentInfo nai : networksSortedById()) {
3203 pw.println(nai.toString());
3204 pw.increaseIndent();
3205 pw.println(String.format(
3206 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3207 nai.numForegroundNetworkRequests(),
3208 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3209 nai.numBackgroundNetworkRequests(),
3210 nai.numNetworkRequests()));
3211 pw.increaseIndent();
3212 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3213 pw.println(nai.requestAt(i).toString());
3214 }
3215 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003216 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003217 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003218 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003219 pw.decreaseIndent();
3220 pw.decreaseIndent();
3221 }
3222 }
3223
James Mattis8b298a02021-06-01 22:34:04 -07003224 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3225 if (!mProfileNetworkPreferences.isEmpty()) {
3226 pw.println("Profile preferences:");
3227 pw.increaseIndent();
3228 pw.println(mProfileNetworkPreferences.preferences);
3229 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003230 }
James Mattis8b298a02021-06-01 22:34:04 -07003231 if (!mOemNetworkPreferences.isEmpty()) {
3232 pw.println("OEM preferences:");
3233 pw.increaseIndent();
3234 pw.println(mOemNetworkPreferences);
3235 pw.decreaseIndent();
3236 }
3237 if (!mMobileDataPreferredUids.isEmpty()) {
3238 pw.println("Mobile data preferred UIDs:");
3239 pw.increaseIndent();
3240 pw.println(mMobileDataPreferredUids);
3241 pw.decreaseIndent();
3242 }
James Mattis45d81842021-01-10 14:24:24 -08003243
James Mattis8b298a02021-06-01 22:34:04 -07003244 pw.println("Default requests:");
3245 pw.increaseIndent();
3246 dumpPerAppDefaultRequests(pw);
3247 pw.decreaseIndent();
3248 }
3249
3250 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003251 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3252 if (mDefaultRequest == defaultRequest) {
3253 continue;
3254 }
3255
James Mattis8b298a02021-06-01 22:34:04 -07003256 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3257 final String networkOutput;
3258 if (null == satisfier) {
3259 networkOutput = "null";
3260 } else if (mNoServiceNetwork.equals(satisfier)) {
3261 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003262 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003263 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003264 }
James Mattis8b298a02021-06-01 22:34:04 -07003265 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3266 ? "" : " asUid: " + defaultRequest.mAsUid;
3267 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3268 + defaultRequest.mPid + asUidString + "]";
3269 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3270 + " Preference order: " + defaultRequest.mPreferenceOrder
3271 + " Tracked UIDs: " + defaultRequest.getUids();
3272 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003273 }
3274 }
3275
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003276 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003277 NetworkRequestInfo[] infos = null;
3278 while (infos == null) {
3279 try {
3280 infos = requestsSortedById();
3281 } catch (ConcurrentModificationException e) {
3282 // mNetworkRequests should only be accessed from handler thread, except dump().
3283 // As dump() is never called in normal usage, it would be needlessly expensive
3284 // to lock the collection only for its benefit. Instead, retry getting the
3285 // requests if ConcurrentModificationException is thrown during dump().
3286 }
3287 }
3288 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003289 pw.println(nri.toString());
3290 }
3291 }
3292
Chalard Jean524f0b12021-10-25 21:11:56 +09003293 private void dumpAllRequestInfoLogsToLogcat() {
3294 try (PrintWriter logPw = new PrintWriter(new Writer() {
3295 @Override
3296 public void write(final char[] cbuf, final int off, final int len) {
3297 // This method is called with 0-length and 1-length arrays for empty strings
3298 // or strings containing only the DEL character.
3299 if (len <= 1) return;
3300 Log.e(TAG, new String(cbuf, off, len));
3301 }
3302 @Override public void flush() {}
3303 @Override public void close() {}
3304 })) {
3305 mNetworkRequestInfoLogs.dump(logPw);
3306 }
3307 }
3308
Hugo Benichia480ba52018-09-03 08:19:02 +09003309 /**
3310 * Return an array of all current NetworkAgentInfos sorted by network id.
3311 */
3312 private NetworkAgentInfo[] networksSortedById() {
3313 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003314 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003315 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003316 return networks;
3317 }
3318
3319 /**
3320 * Return an array of all current NetworkRequest sorted by request id.
3321 */
James Mattis258ea3c2020-11-15 15:04:40 -08003322 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003323 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003324 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003325 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003326 // Sort the array based off the NRI containing the min requestId in its requests.
3327 Arrays.sort(requests,
3328 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3329 Comparator.comparingInt(req -> req.requestId)).requestId
3330 )
3331 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003332 return requests;
3333 }
3334
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003335 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003336 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003337 if (officialNai != null && officialNai.equals(nai)) return true;
3338 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003339 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003340 " - " + nai);
3341 }
3342 return false;
3343 }
3344
Robert Greenwalt2034b912009-08-12 16:08:25 -07003345 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003346 private class NetworkStateTrackerHandler extends Handler {
3347 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003348 super(looper);
3349 }
3350
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003351 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003352 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3353 final NetworkAgentInfo nai = arg.first;
3354 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003355 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003356 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003357 }
3358 return;
3359 }
3360
3361 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003362 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean15228572022-01-28 19:29:12 +09003363 final NetworkCapabilities networkCapabilities = new NetworkCapabilities(
3364 (NetworkCapabilities) arg.second);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003365 processCapabilitiesFromAgent(nai, networkCapabilities);
Hugo Benichibbc15192016-09-15 18:18:48 +09003366 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003367 break;
3368 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003369 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003370 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003371 processLinkPropertiesFromAgent(nai, newLp);
3372 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003373 break;
3374 }
3375 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003376 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003377 updateNetworkInfo(nai, info);
3378 break;
3379 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003380 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003381 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003382 break;
3383 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003384 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003385 if (nai.everConnected) {
3386 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003387 // Note that if the NAI had been connected, this would affect the
3388 // score, and therefore would require re-mixing the score and performing
3389 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003390 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003391 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3392 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003393 // Mark the network as temporarily accepting partial connectivity so that it
3394 // will be validated (and possibly become default) even if it only provides
3395 // partial internet access. Note that if user connects to partial connectivity
3396 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3397 // out of wifi coverage) and if the same wifi is available again, the device
3398 // will auto connect to this wifi even though the wifi has "no internet".
3399 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003400 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003401 break;
3402 }
junyulai011b1f12019-01-03 18:50:15 +08003403 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003404 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003405 break;
3406 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003407 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003408 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003409 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003410
3411 if (isLegacyLockdownNai(nai)
3412 && (underlying == null || underlying.size() != 1)) {
3413 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3414 + " must have exactly one underlying network: " + underlying);
3415 }
3416
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003417 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3418 nai.declaredUnderlyingNetworks = (underlying != null)
3419 ? underlying.toArray(new Network[0]) : null;
3420
3421 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3422 if (DBG) {
3423 log(nai.toShortString() + " changed underlying networks to "
3424 + Arrays.toString(nai.declaredUnderlyingNetworks));
3425 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003426 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003427 notifyIfacesChangedForNetworkStats();
3428 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003429 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003430 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003431 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3432 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3433 nai.teardownDelayMs = msg.arg1;
3434 } else {
3435 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3436 }
Chalard Jean550b5212021-03-05 23:07:53 +09003437 break;
3438 }
3439 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3440 nai.setLingerDuration((int) arg.second);
3441 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003442 }
Tyler Wear72388212021-09-09 14:49:02 -07003443 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3444 DscpPolicy policy = (DscpPolicy) arg.second;
3445 if (mDscpPolicyTracker != null) {
3446 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3447 }
3448 break;
3449 }
3450 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3451 if (mDscpPolicyTracker != null) {
3452 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3453 }
3454 break;
3455 }
3456 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3457 if (mDscpPolicyTracker != null) {
3458 mDscpPolicyTracker.removeAllDscpPolicies(nai);
3459 }
3460 break;
3461 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003462 }
3463 }
3464
3465 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
3466 switch (msg.what) {
3467 default:
3468 return false;
lucasline117e2e2019-10-22 18:27:33 +08003469 case EVENT_PROBE_STATUS_CHANGED: {
3470 final Integer netId = (Integer) msg.obj;
3471 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3472 if (nai == null) {
3473 break;
3474 }
3475 final boolean probePrivateDnsCompleted =
3476 ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
3477 final boolean privateDnsBroken =
3478 ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
3479 if (probePrivateDnsCompleted) {
3480 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3481 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003482 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003483 }
3484 // Only show the notification when the private DNS is broken and the
3485 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003486 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003487 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3488 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003489 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003490 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3491 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3492 // private DNS is broken, it means this network is being reevaluated.
3493 // Either probing private DNS is not necessary any more or it hasn't been
3494 // done yet. In either case, the networkCapabilities should be updated to
3495 // reflect the new status.
3496 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003497 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003498 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003499 }
3500 break;
3501 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003502 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003503 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3504
3505 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(results.mNetId);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003506 if (nai == null) break;
3507
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003508 handleNetworkTested(nai, results.mTestResult,
3509 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003510 break;
3511 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003512 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09003513 final int netId = msg.arg2;
Hugo Benichif4210292017-04-21 15:07:12 +09003514 final boolean visible = toBool(msg.arg1);
Erik Kline9a62f012018-03-21 07:18:33 -07003515 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Ondada1452016-10-11 15:10:46 -07003516 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04003517 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3518 nai.lastCaptivePortalDetected = visible;
3519 nai.everCaptivePortalDetected |= visible;
Calvin Ondada1452016-10-11 15:10:46 -07003520 if (nai.lastCaptivePortalDetected &&
paulhu56e09df2021-03-17 20:30:33 +08003521 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3522 == getCaptivePortalMode()) {
Chalard Jean49707572019-12-10 21:07:02 +09003523 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003524 nai.onPreventAutomaticReconnect();
Calvin Ondada1452016-10-11 15:10:46 -07003525 teardownUnneededNetwork(nai);
3526 break;
3527 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003528 updateCapabilitiesForNetwork(nai);
Paul Jensen53f08952015-06-16 14:27:36 -04003529 }
3530 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003531 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003532 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003533 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3534 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003535 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003536 if (nai == null) {
3537 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3538 break;
3539 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003540 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003541 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003542 (PendingIntent) msg.obj,
3543 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003544 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003545 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003546 break;
3547 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003548 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline9a62f012018-03-21 07:18:33 -07003549 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003550 if (nai == null) break;
3551
Erik Kline9a62f012018-03-21 07:18:33 -07003552 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003553 break;
3554 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003555 case EVENT_CAPPORT_DATA_CHANGED: {
3556 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3557 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003558 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003559 break;
3560 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003561 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003562 return true;
3563 }
3564
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003565 private void handleNetworkTested(
3566 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
3567 final boolean wasPartial = nai.partialConnectivity;
3568 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3569 final boolean partialConnectivityChanged =
3570 (wasPartial != nai.partialConnectivity);
3571
3572 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3573 final boolean wasValidated = nai.lastValidated;
Chalard Jean5b409c72021-02-04 13:12:59 +09003574 final boolean wasDefault = isDefaultNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003575
3576 if (DBG) {
3577 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3578 ? " with redirect to " + redirectUrl
3579 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003580 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003581 }
3582 if (valid != nai.lastValidated) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003583 final int oldScore = nai.getCurrentScore();
3584 nai.lastValidated = valid;
3585 nai.everValidated |= valid;
3586 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003587 if (valid) {
3588 handleFreshlyValidatedNetwork(nai);
3589 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3590 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003591 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003592 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003593 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003594 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003595 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003596 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003597 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003598 NotificationType.PRIVATE_DNS_BROKEN);
3599 // If network becomes valid, the hasShownBroken should be reset for
3600 // that network so that the notification will be fired when the private
3601 // DNS is broken again.
3602 nai.networkAgentConfig.hasShownBroken = false;
3603 }
3604 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003605 updateCapabilitiesForNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003606 }
3607 updateInetCondition(nai);
3608 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003609 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003610 nai.onValidationStatusChanged(
3611 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3612 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003613
3614 // If NetworkMonitor detects partial connectivity before
3615 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3616 // immediately. Re-notify partial connectivity silently if no internet
3617 // notification already there.
3618 if (!wasPartial && nai.partialConnectivity) {
3619 // Remove delayed message if there is a pending message.
3620 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3621 handlePromptUnvalidated(nai.network);
3622 }
3623
3624 if (wasValidated && !nai.lastValidated) {
3625 handleNetworkUnvalidated(nai);
3626 }
3627 }
3628
Calvin Ondada1452016-10-11 15:10:46 -07003629 private int getCaptivePortalMode() {
3630 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08003631 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3632 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07003633 }
3634
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003635 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3636 switch (msg.what) {
3637 default:
3638 return false;
3639 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3640 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3641 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3642 handleLingerComplete(nai);
3643 }
3644 break;
3645 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003646 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3647 handleNetworkAgentRegistered(msg);
3648 break;
3649 }
3650 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3651 handleNetworkAgentDisconnected(msg);
3652 break;
3653 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003654 }
3655 return true;
3656 }
3657
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003658 @Override
3659 public void handleMessage(Message msg) {
lifraf3a3492021-03-10 13:58:14 +08003660 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09003661 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003662 maybeHandleNetworkAgentMessage(msg);
3663 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003664 }
3665 }
3666
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003667 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09003668 private final int mNetId;
3669 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003670
3671 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003672 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003673 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003674 }
3675
3676 @Override
3677 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3678 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09003679 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003680 }
3681
3682 @Override
3683 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003684 // Legacy version of notifyNetworkTestedWithExtras.
3685 // Would only be called if the system has a NetworkStack module older than the
3686 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08003687 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003688 }
3689
3690 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003691 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09003692 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3693 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003694 final Message msg = mTrackerHandler.obtainMessage(
3695 EVENT_NETWORK_TESTED,
3696 new NetworkTestedResults(
3697 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003698 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003699
3700 // Invoke ConnectivityReport generation for this Network test event.
3701 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3702 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003703
Cody Kestingf1120be2020-08-03 18:01:40 -07003704 // NetworkMonitor reports the network validation result as a bitmask while
3705 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
3706 // logical value for ConnectivityDiagnostics.
3707 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
3708 p.result);
3709
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003710 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07003711 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003712 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3713 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3714
Aaron Huang959d3642021-01-21 15:47:41 +08003715 ConnectivityReportEvent reportEvent =
3716 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3717 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
3718 ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003719 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003720 }
3721
3722 @Override
3723 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3724 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3725 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09003726 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003727 }
3728
3729 @Override
lucasline117e2e2019-10-22 18:27:33 +08003730 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3731 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3732 EVENT_PROBE_STATUS_CHANGED,
3733 probesCompleted, probesSucceeded, new Integer(mNetId)));
3734 }
3735
3736 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003737 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3738 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3739 EVENT_CAPPORT_DATA_CHANGED,
3740 0, mNetId, data));
3741 }
3742
3743 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003744 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003745 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003746 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003747
3748 final PendingIntent pendingIntent;
3749 // Only the system server can register notifications with package "android"
3750 final long token = Binder.clearCallingIdentity();
3751 try {
paulhu7746e4e2020-06-09 19:07:03 +08003752 pendingIntent = PendingIntent.getBroadcast(
3753 mContext,
3754 0 /* requestCode */,
3755 intent,
3756 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003757 } finally {
3758 Binder.restoreCallingIdentity(token);
3759 }
3760 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3761 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09003762 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003763 }
3764
3765 @Override
3766 public void hideProvisioningNotification() {
3767 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09003768 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003769 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003770
3771 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003772 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003773 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08003774 }
3775
3776 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003777 public int getInterfaceVersion() {
3778 return this.VERSION;
3779 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09003780
3781 @Override
3782 public String getInterfaceHash() {
3783 return this.HASH;
3784 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003785 }
3786
Cody Kestingf1120be2020-08-03 18:01:40 -07003787 /**
3788 * Converts the given NetworkMonitor-specific validation result bitmask to a
3789 * ConnectivityDiagnostics-specific validation result int.
3790 */
3791 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
3792 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
3793 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
3794 }
3795 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
3796 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
3797 }
3798 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
3799 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
3800 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
3801 }
3802
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003803 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07003804 log("Data stall detected with methods: " + p.detectionMethod);
3805
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003806 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07003807 int detectionMethod = 0;
3808 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
3809 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
3810 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
3811 }
3812 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
3813 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
3814 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
3815 p.tcpMetricsCollectionPeriodMillis);
3816 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003817 }
3818
Cody Kestingf53a0752020-04-15 12:33:28 -07003819 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003820 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08003821 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07003822
3823 // NetworkStateTrackerHandler currently doesn't take any actions based on data
3824 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
3825 // the cost of going through two handlers.
3826 mConnectivityDiagnosticsHandler.sendMessage(msg);
3827 }
3828
Cody Kestingb37958e2020-05-15 10:36:01 -07003829 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
3830 return (p.detectionMethod & detectionMethod) != 0;
3831 }
3832
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003833 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
3834 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07003835 }
3836
Erik Klinea73af002018-06-26 18:53:43 +09003837 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
3838 if (nai == null) return;
3839 // If the Private DNS mode is opportunistic, reprogram the DNS servers
3840 // in order to restart a validation pass from within netd.
3841 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3842 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003843 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09003844 }
3845 }
3846
Erik Kline31b4a9e2018-01-11 21:07:29 +09003847 private void handlePrivateDnsSettingsChanged() {
3848 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3849
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003850 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07003851 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003852 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05003853 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3854 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09003855 }
3856 }
3857
Erik Kline9a62f012018-03-21 07:18:33 -07003858 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
3859 // Private DNS only ever applies to networks that might provide
3860 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003861 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09003862
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003863 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07003864 // schedule DNS resolutions. If a DNS resolution is required the
3865 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09003866 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07003867
3868 // With Private DNS bypass support, we can proceed to update the
3869 // Private DNS config immediately, even if we're in strict mode
3870 // and have not yet resolved the provider name into a set of IPs.
3871 updatePrivateDns(nai, cfg);
3872 }
3873
3874 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
3875 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003876 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09003877 }
3878
dalyk1720e542018-03-05 12:42:22 -05003879 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
3880 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
3881 if (nai == null) {
3882 return;
3883 }
3884 mDnsManager.updatePrivateDnsValidation(update);
3885 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3886 }
3887
paulhu7c0a2e62021-01-08 00:51:49 +08003888 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003889 int prefixLength) {
3890 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
3891 if (nai == null) return;
3892
paulhu7c0a2e62021-01-08 00:51:49 +08003893 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
3894 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003895
3896 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08003897 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003898 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003899 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003900 prefixLength);
3901 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003902 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003903 return;
3904 }
3905 }
3906
Lorenzo Colittid523d142020-04-01 20:16:30 +09003907 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003908 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3909 }
3910
Hai Shalome58bdc62021-01-11 18:45:34 -08003911 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003912 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08003913 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003914 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
3915 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3916 }
3917
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003918 /**
junyulai2b6f0c22021-02-03 20:15:30 +08003919 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003920 * @param nai the agent info to update
3921 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08003922 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003923 */
junyulai2b6f0c22021-02-03 20:15:30 +08003924 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
3925 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
3926 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003927 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08003928 // one lingered request, set inactive.
3929 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08003930 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08003931 if (DBG) log("Unsetting inactive " + nai.toShortString());
3932 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003933 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08003934 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003935 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08003936 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
3937 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003938 }
junyulai2b6f0c22021-02-03 20:15:30 +08003939 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003940 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003941 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003942 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003943 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05003944 }
3945
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003946 private void handleNetworkAgentRegistered(Message msg) {
3947 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3948 if (!mNetworkAgentInfos.contains(nai)) {
3949 return;
3950 }
3951
3952 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
3953 if (VDBG) log("NetworkAgent registered");
3954 } else {
3955 loge("Error connecting NetworkAgent");
3956 mNetworkAgentInfos.remove(nai);
3957 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09003958 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003959 synchronized (mNetworkForNetId) {
3960 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003961 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003962 mNetIdManager.releaseNetId(nai.network.getNetId());
3963 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09003964 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003965 }
3966 }
3967 }
Paul Jensend5f53392014-11-25 15:26:53 -05003968
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003969 private void handleNetworkAgentDisconnected(Message msg) {
3970 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07003971 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003972 }
3973
Chalard Jeand9fffc32018-05-11 20:19:20 +09003974 // Destroys a network, remove references to it from the internal state managed by
3975 // ConnectivityService, free its interfaces and clean up.
3976 // Must be called on the Handler thread.
3977 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09003978 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07003979
3980 if (!mNetworkAgentInfos.contains(nai)) return;
3981
Chalard Jeand9fffc32018-05-11 20:19:20 +09003982 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09003983 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003984 }
lucaslinb25c9a62019-02-12 15:30:13 +08003985 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003986 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003987 // A network agent has disconnected.
3988 // TODO - if we move the logic to the network agent (have them disconnect
3989 // because they lost all their requests or because their score isn't good)
3990 // then they would disconnect organically, report their new state and then
3991 // disconnect the channel.
3992 if (nai.networkInfo.isConnected()) {
3993 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3994 null, null);
3995 }
Chalard Jean5b409c72021-02-04 13:12:59 +09003996 final boolean wasDefault = isDefaultNetwork(nai);
3997 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09003998 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09003999 }
4000 notifyIfacesChangedForNetworkStats();
4001 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4002 // by other networks that are already connected. Perhaps that can be done by
4003 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4004 // of rematchAllNetworksAndRequests
4005 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004006 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004007
4008 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004009 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4010 // Disable wakeup packet monitoring for each interface.
4011 wakeupModifyInterface(iface, nai.networkCapabilities, false);
4012 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004013 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004014 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004015 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004016 synchronized (mNetworkForNetId) {
4017 // Remove the NetworkAgent, but don't mark the netId as
4018 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004019 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004020 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004021 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004022 // Remove all previously satisfied requests.
4023 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004024 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004025 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004026 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004027 if (currentNetwork != null
4028 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004029 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004030 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4031 // rematch not to keep disconnected agents instead of setting it here ; this
4032 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004033 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004034 for (final NetworkOfferInfo noi : mNetworkOffers) {
4035 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004036 }
James Mattise3ef1912020-12-20 11:09:58 -08004037
Chalard Jean5b409c72021-02-04 13:12:59 +09004038 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004039 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004040 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004041 // network, because while incorrect this is the closest to the old (also
4042 // incorrect) behavior.
4043 mNetworkActivityTracker.updateDataActivityTracking(
4044 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004045 ensureNetworkTransitionWakelock(nai.toShortString());
4046 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004047 }
4048 }
junyulai2b6f0c22021-02-03 20:15:30 +08004049 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004050 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004051 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004052 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004053 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004054 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004055 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004056
4057 // Immediate teardown.
4058 if (nai.teardownDelayMs == 0) {
4059 destroyNetwork(nai);
4060 return;
4061 }
4062
4063 // Delayed teardown.
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304064 if (nai.created) {
4065 try {
4066 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4067 } catch (RemoteException e) {
4068 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4069 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004070 }
4071 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4072 }
4073
4074 private void destroyNetwork(NetworkAgentInfo nai) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004075 if (nai.created) {
4076 // Tell netd to clean up the configuration for this network
4077 // (routing rules, DNS, etc).
4078 // This may be slow as it requires a lot of netd shelling out to ip and
4079 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004080 // after we've rematched networks with requests (which might change the default
4081 // network or service a new request from an app), so network traffic isn't interrupted
4082 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004083 destroyNativeNetwork(nai);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004084 mDnsManager.removeNetwork(nai.network);
4085 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004086 mNetIdManager.releaseNetId(nai.network.getNetId());
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004087 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004088 }
4089
Ken Chen6df7a902021-04-09 15:08:42 +08004090 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004091 try {
4092 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004093 final NativeNetworkConfig config;
4094 if (nai.isVPN()) {
4095 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004096 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004097 return false;
4098 }
4099 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4100 INetd.PERMISSION_NONE,
4101 (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass),
Chiachang Wang9164c102022-01-13 10:54:32 +08004102 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004103 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004104 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
4105 getNetworkPermission(nai.networkCapabilities), /*secure=*/ false,
Chiachang Wangbf6b8792022-01-11 10:48:07 +08004106 VpnManager.TYPE_VPN_NONE, /*excludeLocalRoutes=*/ false);
Luke Huangfdd11f82019-04-09 18:41:49 +08004107 }
Ken Chen6df7a902021-04-09 15:08:42 +08004108 mNetd.networkCreate(config);
4109 mDnsResolver.createNetworkCache(nai.network.getNetId());
4110 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4111 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004112 return true;
4113 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004114 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004115 return false;
4116 }
4117 }
4118
Ken Chen6df7a902021-04-09 15:08:42 +08004119 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004120 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004121 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004122 } catch (RemoteException | ServiceSpecificException e) {
4123 loge("Exception destroying network(networkDestroy): " + e);
4124 }
4125 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004126 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004127 } catch (RemoteException | ServiceSpecificException e) {
4128 loge("Exception destroying network: " + e);
4129 }
4130 }
4131
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004132 // If this method proves to be too slow then we can maintain a separate
4133 // pendingIntent => NetworkRequestInfo map.
4134 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4135 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004136 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4137 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4138 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004139 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004140 return entry.getValue();
4141 }
4142 }
4143 return null;
4144 }
4145
Chalard Jean524f0b12021-10-25 21:11:56 +09004146 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4147 if (SdkLevel.isAtLeastT()) {
4148 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4149 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4150 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4151 // bug is fixed.
4152 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004153 throw new IllegalStateException("This NRI is already registered. New : " + nri
4154 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004155 }
4156 }
4157 }
4158 }
4159
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004160 private boolean hasCarrierPrivilegeForNetworkRequest(int callingUid,
4161 NetworkRequest networkRequest) {
4162 if (SdkLevel.isAtLeastT() && mCarrierPrivilegeAuthenticator != null) {
4163 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkRequest(callingUid,
4164 networkRequest);
4165 }
4166 return false;
4167 }
4168
James Mattisf7027322020-12-13 16:28:14 -08004169 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004170 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004171 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4172 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4173 final NetworkRequestInfo existingRequest =
4174 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004175 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004176 if (DBG) {
4177 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4178 + nri.mRequests.get(0) + " because their intents matched.");
4179 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004180 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004181 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004182 }
Erik Kline05f2b402015-04-30 12:58:40 +09004183 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004184 }
4185
James Mattisf7027322020-12-13 16:28:14 -08004186 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004187 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004188 }
4189
James Mattis3ce3d3c2021-02-09 18:18:28 -08004190 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004191 ensureRunningOnConnectivityServiceThread();
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004192 NetworkRequest requestToBeReleased = null;
James Mattis45d81842021-01-10 14:24:24 -08004193 for (final NetworkRequestInfo nri : nris) {
4194 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004195 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004196 for (final NetworkRequest req : nri.mRequests) {
4197 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004198 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004199 if (req.isListen()) {
4200 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4201 if (req.networkCapabilities.hasSignalStrength()
4202 && network.satisfiesImmutableCapabilitiesOf(req)) {
4203 updateSignalStrengthThresholds(network, "REGISTER", req);
4204 }
James Mattisf7027322020-12-13 16:28:14 -08004205 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004206 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004207 if (req.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
4208 if (!hasCarrierPrivilegeForNetworkRequest(nri.mUid, req)
4209 && !checkConnectivityRestrictedNetworksPermission(
4210 nri.mPid, nri.mUid)) {
4211 requestToBeReleased = req;
4212 }
4213 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004214 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004215
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004216 // If this NRI has a satisfier already, it is replacing an older request that
4217 // has been removed. Track it.
4218 final NetworkRequest activeRequest = nri.getActiveRequest();
4219 if (null != activeRequest) {
4220 // If there is an active request, then for sure there is a satisfier.
4221 nri.getSatisfier().addRequest(activeRequest);
4222 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004223 }
James Mattisf7027322020-12-13 16:28:14 -08004224
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004225 if (requestToBeReleased != null) {
4226 releaseNetworkRequestAndCallOnUnavailable(requestToBeReleased);
4227 return;
4228 }
4229
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004230 if (mFlags.noRematchAllRequestsOnRegister()) {
4231 rematchNetworksAndRequests(nris);
4232 } else {
4233 rematchAllNetworksAndRequests();
4234 }
James Mattis45d81842021-01-10 14:24:24 -08004235
Chalard Jean0354d8c2021-01-12 10:58:56 +09004236 // Requests that have not been matched to a network will not have been sent to the
4237 // providers, because the old satisfier and the new satisfier are the same (null in this
4238 // case). Send these requests to the providers.
4239 for (final NetworkRequestInfo nri : nris) {
4240 for (final NetworkOfferInfo noi : mNetworkOffers) {
4241 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004242 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004243 }
4244 }
4245
James Mattisf7027322020-12-13 16:28:14 -08004246 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4247 final int callingUid) {
4248 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004249 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004250 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4251 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4252 handleReleaseNetworkRequest(
4253 nri.mRequests.get(0),
4254 callingUid,
4255 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004256 }
4257 }
4258
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004259 // Determines whether the network is the best (or could become the best, if it validated), for
4260 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4261 // on the value of reason:
4262 //
4263 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4264 // then it should be torn down.
4265 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4266 // then it should be lingered.
4267 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004268 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004269
4270 if (!nai.everConnected || nai.isVPN() || nai.isInactive()
4271 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4272 return false;
4273 }
4274
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004275 final int numRequests;
4276 switch (reason) {
4277 case TEARDOWN:
4278 numRequests = nai.numRequestNetworkRequests();
4279 break;
4280 case LINGER:
4281 numRequests = nai.numForegroundNetworkRequests();
4282 break;
4283 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004284 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004285 return true;
4286 }
4287
Chalard Jean947acd42021-03-08 22:29:27 +09004288 if (numRequests > 0) return false;
4289
Paul Jensende49eb12015-06-25 15:30:08 -04004290 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004291 if (reason == UnneededFor.LINGER
4292 && !nri.isMultilayerRequest()
4293 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004294 // Background requests don't affect lingering.
4295 continue;
4296 }
4297
James Mattis3d229892020-11-16 16:46:28 -08004298 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004299 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004300 }
4301 }
Paul Jensende49eb12015-06-25 15:30:08 -04004302 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004303 }
4304
James Mattis3d229892020-11-16 16:46:28 -08004305 private boolean isNetworkPotentialSatisfier(
4306 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4307 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004308 // request, return immediately. For multilayer requests, check to see if any of the
4309 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004310 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4311 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004312 return false;
4313 }
4314 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004315 // This multilayer listen request is satisfied therefore no further requests need to be
4316 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004317 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004318 return false;
4319 }
James Mattis3d229892020-11-16 16:46:28 -08004320 // As non-multilayer listen requests have already returned, the below would only happen
4321 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004322 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004323 continue;
4324 }
4325 // If this Network is already the highest scoring Network for a request, or if
4326 // there is hope for it to become one if it validated, then it is needed.
4327 if (candidate.satisfies(req)) {
4328 // As soon as a network is found that satisfies a request, return. Specifically for
4329 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4330 // is important so as to not evaluate lower priority requests further in
4331 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004332 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4333 ? nri.getSatisfier() : null;
4334 // Note that this catches two important cases:
4335 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4336 // is currently satisfying the request. This is desirable when
4337 // cellular ends up validating but WiFi does not.
4338 // 2. Unvalidated WiFi will not be reaped when validated cellular
4339 // is currently satisfying the request. This is desirable when
4340 // WiFi ends up validating and out scoring cellular.
4341 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004342 }
4343 }
4344
4345 return false;
4346 }
4347
Erik Kline0c04b742016-07-07 16:50:58 +09004348 private NetworkRequestInfo getNriForAppRequest(
4349 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004350 // Looking up the app passed param request in mRequests isn't possible since it may return
4351 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4352 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004353 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4354 // to avoid potential race conditions when validating a package->uid mapping when sending
4355 // the callback on the very low-chance that an application shuts down prior to the callback
4356 // being sent.
4357 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4358 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004359
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004360 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004361 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004362 log(String.format("UID %d attempted to %s for unowned request %s",
4363 callingUid, requestedOperation, nri));
4364 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004365 }
Erik Kline0c04b742016-07-07 16:50:58 +09004366 }
4367
4368 return nri;
4369 }
4370
James Mattisf7027322020-12-13 16:28:14 -08004371 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4372 final String callingMethod) {
4373 if (nri.isMultilayerRequest()) {
4374 throw new IllegalStateException(
4375 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004376 }
4377 }
4378
James Mattisf7027322020-12-13 16:28:14 -08004379 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004380 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004381 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4382 // single NetworkRequest and thus does not apply to multilayer requests.
4383 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4384 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004385 return;
4386 }
James Mattis2516da32021-01-31 17:06:19 -08004387 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004388 return;
4389 }
James Mattisf7027322020-12-13 16:28:14 -08004390 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4391 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004392 }
4393 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004394 callCallbackForRequest(
4395 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004396 }
4397
James Mattisf7027322020-12-13 16:28:14 -08004398 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4399 final int callingUid,
4400 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004401 final NetworkRequestInfo nri =
4402 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4403 if (nri == null) {
4404 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004405 }
James Mattisf7027322020-12-13 16:28:14 -08004406 if (VDBG || (DBG && request.isRequest())) {
4407 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004408 }
4409 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004410 if (callOnUnavailable) {
4411 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4412 }
Erik Kline155a59a2015-11-25 12:49:38 +09004413 }
Erik Kline0c04b742016-07-07 16:50:58 +09004414
James Mattisa076c532020-12-02 14:12:41 -08004415 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004416 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004417 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004418 if (null == mNetworkRequests.remove(req)) {
4419 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4420 continue;
4421 }
James Mattisa076c532020-12-02 14:12:41 -08004422 if (req.isListen()) {
4423 removeListenRequestFromNetworks(req);
4424 }
4425 }
James Mattis8f036802021-06-20 16:26:01 -07004426 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004427 if (mDefaultNetworkRequests.remove(nri)) {
4428 // If this request was one of the defaults, then the UID rules need to be updated
4429 // WARNING : if the app(s) for which this network request is the default are doing
4430 // traffic, this will kill their connected sockets, even if an equivalent request
4431 // is going to be reinstated right away ; unconnected traffic will go on the default
4432 // until the new default is set, which will happen very soon.
4433 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4434 // remove ranges for those requests that won't have a replacement
4435 final NetworkAgentInfo satisfier = nri.getSatisfier();
4436 if (null != satisfier) {
4437 try {
paulhu0e79d952021-06-09 16:11:35 +08004438 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4439 satisfier.network.getNetId(),
4440 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004441 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004442 } catch (RemoteException e) {
4443 loge("Exception setting network preference default network", e);
4444 }
4445 }
4446 }
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09004447 nri.decrementRequestCount();
Erik Kline0c04b742016-07-07 16:50:58 +09004448 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004449 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004450
4451 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004452 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004453 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004454 }
4455 }
4456
Chalard Jean0354d8c2021-01-12 10:58:56 +09004457 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4458 // needed for this offer.
4459 for (final NetworkOfferInfo noi : mNetworkOffers) {
4460 for (final NetworkRequest req : nri.mRequests) {
4461 if (req.isRequest() && noi.offer.neededFor(req)) {
4462 noi.offer.onNetworkUnneeded(req);
4463 }
4464 }
4465 }
James Mattisa076c532020-12-02 14:12:41 -08004466 }
4467
James Mattis3ce3d3c2021-02-09 18:18:28 -08004468 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4469 for (final NetworkRequestInfo nri : nris) {
4470 if (mDefaultRequest == nri) {
4471 // Make sure we never remove the default request.
4472 continue;
4473 }
4474 handleRemoveNetworkRequest(nri);
4475 }
4476 }
4477
James Mattisa076c532020-12-02 14:12:41 -08004478 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4479 // listens don't have a singular affected Network. Check all networks to see
4480 // if this listen request applies and remove it.
4481 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4482 nai.removeRequest(req.requestId);
4483 if (req.networkCapabilities.hasSignalStrength()
4484 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4485 updateSignalStrengthThresholds(nai, "RELEASE", req);
4486 }
4487 }
4488 }
4489
4490 /**
4491 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4492 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4493 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4494 */
4495 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4496 boolean wasKept = false;
4497 final NetworkAgentInfo nai = nri.getSatisfier();
4498 if (nai != null) {
4499 final int requestLegacyType = nri.getActiveRequest().legacyType;
4500 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4501 nai.removeRequest(nri.getActiveRequest().requestId);
4502 if (VDBG || DDBG) {
4503 log(" Removing from current network " + nai.toShortString()
4504 + ", leaving " + nai.numNetworkRequests() + " requests.");
4505 }
4506 // If there are still lingered requests on this network, don't tear it down,
4507 // but resume lingering instead.
4508 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004509 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004510 notifyNetworkLosing(nai, now);
4511 }
4512 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4513 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4514 teardownUnneededNetwork(nai);
4515 } else {
4516 wasKept = true;
4517 }
James Mattisa076c532020-12-02 14:12:41 -08004518 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4519 // Went from foreground to background.
4520 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004521 }
4522
Erik Kline0c04b742016-07-07 16:50:58 +09004523 // Maintain the illusion. When this request arrived, we might have pretended
4524 // that a network connected to serve it, even though the network was already
4525 // connected. Now that this request has gone away, we might have to pretend
4526 // that the network disconnected. LegacyTypeTracker will generate that
4527 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004528 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004529 boolean doRemove = true;
4530 if (wasKept) {
4531 // check if any of the remaining requests for this network are for the
4532 // same legacy type - if so, don't remove the nai
4533 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4534 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004535 if (otherRequest.legacyType == requestLegacyType
4536 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004537 if (DBG) log(" still have other legacy request - leaving");
4538 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004539 }
4540 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004541 }
4542
Erik Kline0c04b742016-07-07 16:50:58 +09004543 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004544 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004545 }
4546 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004547 }
4548 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004549
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004550 private PerUidCounter getRequestCounter(NetworkRequestInfo nri) {
4551 return checkAnyPermissionOf(
4552 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4553 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4554 }
4555
Lorenzo Colittid6459092016-07-04 12:55:44 +09004556 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004557 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004558 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004559 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004560 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004561 }
4562
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004563 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004564 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4565 enforceNetworkStackSettingsOrSetup();
4566 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4567 encodeBool(accept), encodeBool(always), network));
4568 }
4569
4570 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004571 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004572 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004573 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4574 }
4575
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004576 @Override
4577 public void setTestAllowBadWifiUntil(long timeMs) {
4578 enforceSettingsPermission();
4579 if (!Build.isDebuggable()) {
4580 throw new IllegalStateException("Does not support in non-debuggable build");
4581 }
4582
4583 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4584 throw new IllegalArgumentException("It should not exceed "
4585 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4586 }
4587
4588 mHandler.sendMessage(
4589 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
4590 }
4591
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004592 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4593 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4594 " accept=" + accept + " always=" + always);
4595
4596 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4597 if (nai == null) {
4598 // Nothing to do.
4599 return;
4600 }
4601
4602 if (nai.everValidated) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004603 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004604 return;
4605 }
4606
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004607 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08004608 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004609 }
4610
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004611 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4612 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004613 // If network becomes partial connectivity and user already accepted to use this
4614 // network, we should respect the user's option and don't need to popup the
4615 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004616 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004617 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004618 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004619 }
4620
4621 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004622 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004623 }
4624
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004625 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04004626 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004627 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09004628 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04004629 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004630 }
4631
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004632 }
4633
lucaslin2240ef62019-03-12 13:08:03 +08004634 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4635 boolean always) {
4636 if (DBG) {
4637 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4638 + " always=" + always);
4639 }
4640
4641 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4642 if (nai == null) {
4643 // Nothing to do.
4644 return;
4645 }
4646
4647 if (nai.lastValidated) {
4648 // The network validated while the dialog box was up. Take no action.
4649 return;
4650 }
4651
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004652 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4653 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004654 }
4655
4656 // TODO: Use the current design or save the user choice into IpMemoryStore.
4657 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004658 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08004659 }
4660
4661 if (!accept) {
4662 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004663 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08004664 // Tear down the network.
4665 teardownUnneededNetwork(nai);
4666 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08004667 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4668 // result in a partial connectivity result which will be processed by
4669 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08004670 //
4671 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4672 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004673 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08004674 }
4675 }
4676
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004677 private void handleSetAvoidUnvalidated(Network network) {
4678 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4679 if (nai == null || nai.lastValidated) {
4680 // Nothing to do. The network either disconnected or revalidated.
4681 return;
4682 }
4683 if (!nai.avoidUnvalidated) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004684 nai.avoidUnvalidated = true;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004685 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004686 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004687 }
4688 }
4689
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004690 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09004691 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004692 mHandler.sendMessageDelayed(
4693 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4694 PROMPT_UNVALIDATED_DELAY_MS);
4695 }
4696
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004697 @Override
4698 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08004699 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004700 mHandler.post(() -> {
4701 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4702 if (nai == null) return;
4703 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004704 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004705 });
4706 }
4707
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004708 /**
4709 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4710 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004711 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004712 * @param appExtras Bundle to use as intent extras for the captive portal application.
4713 * Must be treated as opaque to avoid preventing the captive portal app to
4714 * update its arguments.
4715 */
4716 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004717 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08004718 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4719 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004720
4721 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4722 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004723 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4724 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004725 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4726
lucaslin75ff7022020-12-17 04:14:35 +08004727 final long token = Binder.clearCallingIdentity();
4728 try {
4729 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4730 } finally {
4731 Binder.restoreCallingIdentity(token);
4732 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004733 }
4734
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004735 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4736 private final Network mNetwork;
4737
4738 private CaptivePortalImpl(Network network) {
4739 mNetwork = network;
4740 }
4741
4742 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004743 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004744 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
4745 enforceSettingsPermission();
4746 }
4747
Chiachang Wang938bfba2020-01-09 13:50:55 +08004748 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004749 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004750 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004751 }
4752
4753 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08004754 public void appRequest(final int request) {
4755 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4756 if (nm == null) return;
4757
4758 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08004759 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09004760 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08004761 }
4762 }
4763
4764 @Nullable
4765 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
4766 // getNetworkAgentInfoForNetwork is thread-safe
4767 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4768 if (nai == null) return null;
4769
4770 // nai.networkMonitor() is thread-safe
4771 return nai.networkMonitor();
4772 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004773 }
4774
Hugo Benichic9048bc2016-09-14 23:23:08 +00004775 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004776 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09004777 }
4778
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004779 /**
4780 * Return whether the device should maintain continuous, working connectivity by switching away
4781 * from WiFi networks having no connectivity.
4782 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
4783 */
4784 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004785 if (!checkNetworkStackPermission()) {
4786 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
4787 }
4788 return avoidBadWifi();
4789 }
4790
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004791 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09004792 ensureRunningOnConnectivityServiceThread();
4793 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004794 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09004795 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004796 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09004797 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
4798 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
4799 for (final NetworkOfferInfo noi : offersToUpdate) {
4800 updateOfferScore(noi.offer);
4801 }
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004802 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004803 }
4804
Erik Kline95ecfee2016-10-02 18:02:14 +09004805 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004806 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004807 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004808 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004809 if (!configRestrict) {
4810 pw.println("Bad Wi-Fi avoidance: unrestricted");
4811 return;
4812 }
4813
4814 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
4815 pw.increaseIndent();
4816 pw.println("Config restrict: " + configRestrict);
4817
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004818 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004819 String description;
4820 // Can't use a switch statement because strings are legal case labels, but null is not.
4821 if ("0".equals(value)) {
4822 description = "get stuck";
4823 } else if (value == null) {
4824 description = "prompt";
4825 } else if ("1".equals(value)) {
4826 description = "avoid";
4827 } else {
4828 description = value + " (?)";
4829 }
4830 pw.println("User setting: " + description);
4831 pw.println("Network overrides:");
4832 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09004833 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004834 if (nai.avoidUnvalidated) {
Chalard Jean49707572019-12-10 21:07:02 +09004835 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004836 }
4837 }
4838 pw.decreaseIndent();
4839 pw.decreaseIndent();
4840 }
4841
paulhu7746e4e2020-06-09 19:07:03 +08004842 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
4843 // unify the method.
4844 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
4845 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
4846 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
4847 return settingsComponent != null
4848 ? settingsComponent.getPackageName() : "com.android.settings";
4849 }
4850
lucaslinb1e8e382019-01-24 15:55:30 +08004851 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004852 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004853 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004854 switch (type) {
4855 case NO_INTERNET:
4856 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004857 // High priority because it is only displayed for explicitly selected networks.
4858 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004859 break;
lucasline117e2e2019-10-22 18:27:33 +08004860 case PRIVATE_DNS_BROKEN:
4861 action = Settings.ACTION_WIRELESS_SETTINGS;
4862 // High priority because we should let user know why there is no internet.
4863 highPriority = true;
4864 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004865 case LOST_INTERNET:
4866 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004867 // High priority because it could help the user avoid unexpected data usage.
4868 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004869 break;
lucaslin2240ef62019-03-12 13:08:03 +08004870 case PARTIAL_CONNECTIVITY:
4871 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004872 // Don't bother the user with a high-priority notification if the network was not
4873 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004874 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08004875 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004876 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004877 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004878 return;
4879 }
4880
4881 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08004882 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08004883 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08004884 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08004885 // Some OEMs have their own Settings package. Thus, need to get the current using
4886 // Settings package name instead of just use default name "com.android.settings".
4887 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
4888 intent.setClassName(settingsPkgName,
4889 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08004890 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004891
paulhu2af50222020-10-11 22:52:27 +08004892 PendingIntent pendingIntent = PendingIntent.getActivity(
4893 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08004894 0 /* requestCode */,
4895 intent,
paulhu2af50222020-10-11 22:52:27 +08004896 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004897
Serik Beketayevec8ad212020-12-07 22:43:07 -08004898 mNotifier.showNotification(
4899 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004900 }
4901
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004902 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
4903 // Don't prompt if the network is validated, and don't prompt on captive portals
4904 // because we're already prompting the user to sign in.
4905 if (nai.everValidated || nai.everCaptivePortalDetected) {
4906 return false;
4907 }
4908
4909 // If a network has partial connectivity, always prompt unless the user has already accepted
4910 // partial connectivity and selected don't ask again. This ensures that if the device
4911 // automatically connects to a network that has partial Internet access, the user will
4912 // always be able to use it, either because they've already chosen "don't ask again" or
4913 // because we have prompt them.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004914 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004915 return true;
4916 }
4917
4918 // If a network has no Internet access, only prompt if the network was explicitly selected
4919 // and if the user has not already told us to use the network regardless of whether it
4920 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004921 if (nai.networkAgentConfig.explicitlySelected
4922 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004923 return true;
4924 }
4925
4926 return false;
4927 }
4928
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004929 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09004930 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004931 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4932
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004933 if (nai == null || !shouldPromptUnvalidated(nai)) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004934 return;
4935 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09004936
4937 // Stop automatically reconnecting to this network in the future. Automatically connecting
4938 // to a network that provides no or limited connectivity is not useful, because the user
4939 // cannot use that network except through the notification shown by this method, and the
4940 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004941 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09004942
lucaslin2240ef62019-03-12 13:08:03 +08004943 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
4944 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
4945 // popup the notification immediately when the network is partial connectivity.
4946 if (nai.partialConnectivity) {
lucasline0118ab2019-03-21 11:59:22 +08004947 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08004948 } else {
4949 showNetworkNotification(nai, NotificationType.NO_INTERNET);
4950 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004951 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004952
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004953 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
4954 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09004955 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07004956
lucaslin2240ef62019-03-12 13:08:03 +08004957 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4958 return;
4959 }
4960
4961 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08004962 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004963 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004964 }
4965
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004966 @Override
4967 public int getMultipathPreference(Network network) {
4968 enforceAccessPermission();
4969
4970 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06004971 if (nai != null && nai.networkCapabilities
4972 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004973 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
4974 }
4975
Aaron Huang9a57acf2020-12-08 10:03:29 +08004976 final NetworkPolicyManager netPolicyManager =
4977 mContext.getSystemService(NetworkPolicyManager.class);
4978
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09004979 final long token = Binder.clearCallingIdentity();
4980 final int networkPreference;
4981 try {
4982 networkPreference = netPolicyManager.getMultipathPreference(network);
4983 } finally {
4984 Binder.restoreCallingIdentity(token);
4985 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08004986 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09004987 return networkPreference;
4988 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004989 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
4990 }
4991
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004992 @Override
4993 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09004994 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004995 }
4996
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004997 private class InternalHandler extends Handler {
4998 public InternalHandler(Looper looper) {
4999 super(looper);
5000 }
5001
5002 @Override
5003 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005004 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005005 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005006 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005007 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005008 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005009 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005010 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005011 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005012 break;
5013 }
Jason Monka69f1b02013-10-10 14:02:51 -04005014 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005015 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5016 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005017 break;
5018 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005019 case EVENT_REGISTER_NETWORK_PROVIDER: {
5020 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005021 break;
5022 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005023 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5024 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005025 break;
5026 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005027 case EVENT_REGISTER_NETWORK_OFFER: {
5028 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5029 break;
5030 }
5031 case EVENT_UNREGISTER_NETWORK_OFFER: {
5032 final NetworkOfferInfo offer =
5033 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5034 if (null != offer) {
5035 handleUnregisterNetworkOffer(offer);
5036 }
5037 break;
5038 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005039 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005040 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5041 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5042 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005043 break;
5044 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005045 case EVENT_REGISTER_NETWORK_REQUEST:
5046 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005047 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005048 break;
5049 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005050 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5051 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005052 handleRegisterNetworkRequestWithIntent(msg);
5053 break;
5054 }
Erik Kline155a59a2015-11-25 12:49:38 +09005055 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5056 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5057 handleTimedOutNetworkRequest(nri);
5058 break;
5059 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005060 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5061 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5062 break;
5063 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005064 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005065 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5066 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005067 break;
5068 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005069 case EVENT_RELEASE_NETWORK_REQUEST_AND_CALL_UNAVAILABLE: {
5070 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5071 /* callOnUnavailable */ true);
5072 break;
5073 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005074 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005075 Network network = (Network) msg.obj;
5076 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005077 break;
5078 }
lucaslin2240ef62019-03-12 13:08:03 +08005079 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5080 Network network = (Network) msg.obj;
5081 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5082 toBool(msg.arg2));
5083 break;
5084 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005085 case EVENT_SET_AVOID_UNVALIDATED: {
5086 handleSetAvoidUnvalidated((Network) msg.obj);
5087 break;
5088 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005089 case EVENT_PROMPT_UNVALIDATED: {
5090 handlePromptUnvalidated((Network) msg.obj);
5091 break;
5092 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005093 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5094 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005095 break;
5096 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005097 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005098 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005099 mKeepaliveTracker.handleStartKeepalive(msg);
5100 break;
5101 }
5102 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005103 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005104 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5105 int slot = msg.arg1;
5106 int reason = msg.arg2;
5107 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
5108 break;
5109 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005110 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5111 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5112 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005113 break;
5114 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005115 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5116 handlePrivateDnsSettingsChanged();
5117 break;
dalyk1720e542018-03-05 12:42:22 -05005118 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5119 handlePrivateDnsValidationUpdate(
5120 (PrivateDnsValidationUpdate) msg.obj);
5121 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005122 case EVENT_UID_BLOCKED_REASON_CHANGED:
5123 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005124 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005125 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5126 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5127 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005128 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005129 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5130 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005131 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005132 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005133 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005134 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005135 final Pair<List<ProfileNetworkPreferenceList.Preference>,
5136 IOnCompleteListener> arg =
5137 (Pair<List<ProfileNetworkPreferenceList.Preference>,
5138 IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005139 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005140 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005141 }
lucaslin1193a5d2021-01-21 02:04:15 +08005142 case EVENT_REPORT_NETWORK_ACTIVITY:
5143 mNetworkActivityTracker.handleReportNetworkActivity();
5144 break;
paulhu51f77dc2021-06-07 02:34:20 +00005145 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5146 handleMobileDataPreferredUidsChanged();
5147 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005148 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5149 final long timeMs = ((Long) msg.obj).longValue();
5150 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5151 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005152 }
5153 }
5154 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005155
Lorenzo Colittid6459092016-07-04 12:55:44 +09005156 @Override
markchien5776f962019-12-16 20:15:20 +08005157 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005158 public int getLastTetherError(String iface) {
markchien5776f962019-12-16 20:15:20 +08005159 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5160 Context.TETHERING_SERVICE);
5161 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005162 }
5163
Lorenzo Colittid6459092016-07-04 12:55:44 +09005164 @Override
markchien5776f962019-12-16 20:15:20 +08005165 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005166 public String[] getTetherableIfaces() {
markchien5776f962019-12-16 20:15:20 +08005167 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5168 Context.TETHERING_SERVICE);
5169 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005170 }
5171
Lorenzo Colittid6459092016-07-04 12:55:44 +09005172 @Override
markchien5776f962019-12-16 20:15:20 +08005173 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005174 public String[] getTetheredIfaces() {
markchien5776f962019-12-16 20:15:20 +08005175 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5176 Context.TETHERING_SERVICE);
5177 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005178 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005179
markchien5776f962019-12-16 20:15:20 +08005180
Lorenzo Colittid6459092016-07-04 12:55:44 +09005181 @Override
markchien5776f962019-12-16 20:15:20 +08005182 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005183 public String[] getTetheringErroredIfaces() {
markchien5776f962019-12-16 20:15:20 +08005184 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5185 Context.TETHERING_SERVICE);
5186
5187 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005188 }
5189
Lorenzo Colittid6459092016-07-04 12:55:44 +09005190 @Override
markchien5776f962019-12-16 20:15:20 +08005191 @Deprecated
5192 public String[] getTetherableUsbRegexs() {
5193 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5194 Context.TETHERING_SERVICE);
5195
5196 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005197 }
5198
Udam Saini8f7d6a72017-06-07 12:06:28 -07005199 @Override
markchien5776f962019-12-16 20:15:20 +08005200 @Deprecated
5201 public String[] getTetherableWifiRegexs() {
5202 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5203 Context.TETHERING_SERVICE);
5204 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005205 }
5206
Robert Greenwalte0b00512014-07-02 09:59:16 -07005207 // Called when we lose the default network and have no replacement yet.
5208 // This will automatically be cleared after X seconds or a new default network
5209 // becomes CONNECTED, whichever happens first. The timer is started by the
5210 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005211 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005212 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005213 if (mNetTransitionWakeLock.isHeld()) {
5214 return;
5215 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005216 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005217 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5218 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005219 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005220 mWakelockLogs.log("ACQUIRE for " + forWhom);
5221 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005222 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005223 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005224 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005225 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005226
Hugo Benichi471b62a2017-03-30 23:18:10 +09005227 // Called when we gain a new default network to release the network transition wakelock in a
5228 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5229 // message is cancelled.
5230 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005231 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005232 if (!mNetTransitionWakeLock.isHeld()) {
5233 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005234 }
5235 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005236 // Cancel self timeout on wakelock hold.
5237 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5238 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5239 mHandler.sendMessageDelayed(msg, 1000);
5240 }
5241
5242 // Called when either message of ensureNetworkTransitionWakelock or
5243 // scheduleReleaseNetworkTransitionWakelock is processed.
5244 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5245 String event = eventName(eventId);
5246 synchronized (this) {
5247 if (!mNetTransitionWakeLock.isHeld()) {
5248 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005249 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005250 return;
5251 }
5252 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005253 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5254 mTotalWakelockDurationMs += lockDuration;
5255 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5256 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005257 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005258 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005259 }
5260
Robert Greenwalt986c7412010-09-08 15:24:47 -07005261 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005262 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005263 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005264 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005265 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005266 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005267 }
5268
Lorenzo Colittid6459092016-07-04 12:55:44 +09005269 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005270 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005271 enforceAccessPermission();
5272 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005273 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005274 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005275
5276 final NetworkAgentInfo nai;
5277 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005278 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005279 } else {
5280 nai = getNetworkAgentInfoForNetwork(network);
5281 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005282
5283 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005284 mHandler.obtainMessage(
5285 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005286 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005287
Hugo Benichid6b510a2017-04-06 17:22:18 +09005288 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005289 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005290 if (nai == null
5291 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005292 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005293 return;
5294 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005295 // Revalidate if the app report does not match our current validated state.
Hugo Benichie9d321b2017-04-06 16:01:44 +09005296 if (hasConnectivity == nai.lastValidated) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005297 mConnectivityDiagnosticsHandler.sendMessage(
5298 mConnectivityDiagnosticsHandler.obtainMessage(
5299 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5300 new ReportedNetworkConnectivityInfo(
5301 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005302 return;
5303 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005304 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005305 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005306 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005307 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005308 // Validating a network that has not yet connected could result in a call to
5309 // rematchNetworkAndRequests() which is not meant to work on such networks.
5310 if (!nai.everConnected) {
5311 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005312 }
paulhu7aeba372020-12-30 00:42:19 +08005313 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5314 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005315 return;
5316 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005317
5318 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5319 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5320 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5321 // completed.
5322 mConnectivityDiagnosticsHandler.sendMessage(
5323 mConnectivityDiagnosticsHandler.obtainMessage(
5324 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5325 new ReportedNetworkConnectivityInfo(
5326 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005327 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005328 }
5329
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005330 // TODO: call into netd.
5331 private boolean queryUserAccess(int uid, Network network) {
5332 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5333 if (nai == null) return false;
5334
5335 // Any UID can use its default network.
5336 if (nai == getDefaultNetworkForUid(uid)) return true;
5337
5338 // Privileged apps can use any network.
5339 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5340 return true;
5341 }
5342
5343 // An unprivileged UID can use a VPN iff the VPN applies to it.
5344 if (nai.isVPN()) {
5345 return nai.networkCapabilities.appliesToUid(uid);
5346 }
5347
5348 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5349 // sockets, i.e., if it is the owner.
5350 final NetworkAgentInfo vpn = getVpnForUid(uid);
5351 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5352 && uid != vpn.networkCapabilities.getOwnerUid()) {
5353 return false;
5354 }
5355
5356 // The UID's permission must be at least sufficient for the network. Since the restricted
5357 // permission was already checked above, that just leaves background networks.
5358 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5359 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5360 }
5361
5362 // Unrestricted network. Anyone gets to use it.
5363 return true;
5364 }
5365
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005366 /**
5367 * Returns information about the proxy a certain network is using. If given a null network, it
5368 * it will return the proxy for the bound network for the caller app or the default proxy if
5369 * none.
5370 *
5371 * @param network the network we want to get the proxy information for.
5372 * @return Proxy information if a network has a proxy configured, or otherwise null.
5373 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005374 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005375 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005376 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005377 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005378 if (network == null) {
5379 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005380 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005381 true);
5382 if (activeNetwork == null) {
5383 return null;
5384 }
5385 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005386 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005387 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5388 // caller may not have.
5389 return getLinkPropertiesProxyInfo(network);
5390 }
5391 // No proxy info available if the calling UID does not have network access.
5392 return null;
5393 }
5394
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005395
5396 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005397 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5398 if (nai == null) return null;
5399 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005400 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5401 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005402 }
5403 }
5404
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005405 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005406 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhudf23d662021-01-25 18:53:17 +08005407 PermissionUtils.enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005408 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005409 }
5410
Chalard Jean777e2e52018-06-07 18:02:37 +09005411 @Override
5412 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005413 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005414 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005415 }
5416
Jason Monk4d5e20f2014-04-25 15:00:09 -04005417 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005418 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005419 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005420 proxy = null;
5421 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005422 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005423 }
5424
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005425 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5426 // when any network changes proxy.
5427 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5428 // multi-network world where an app might be bound to a non-default network.
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005429 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensenc0618a62014-12-10 15:12:18 -05005430 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5431 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5432
Chalard Jean7d97afc2018-06-07 17:41:29 +09005433 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005434 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005435 }
5436 }
5437
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005438 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005439 final private HashMap<Uri, Integer> mUriEventMap;
5440 final private Context mContext;
5441 final private Handler mHandler;
5442
5443 SettingsObserver(Context context, Handler handler) {
5444 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005445 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005446 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005447 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005448 }
5449
Erik Kline05f2b402015-04-30 12:58:40 +09005450 void observe(Uri uri, int what) {
5451 mUriEventMap.put(uri, what);
5452 final ContentResolver resolver = mContext.getContentResolver();
5453 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005454 }
5455
5456 @Override
5457 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005458 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005459 }
5460
5461 @Override
5462 public void onChange(boolean selfChange, Uri uri) {
5463 final Integer what = mUriEventMap.get(uri);
5464 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005465 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005466 } else {
5467 loge("No matching event to send for URI=" + uri);
5468 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005469 }
5470 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005471
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005472 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005473 Log.d(TAG, s);
5474 }
5475
5476 private static void logw(String s) {
5477 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005478 }
5479
Daniel Brightf9e945b2020-06-15 16:10:01 -07005480 private static void logwtf(String s) {
5481 Log.wtf(TAG, s);
5482 }
5483
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005484 private static void logwtf(String s, Throwable t) {
5485 Log.wtf(TAG, s, t);
5486 }
5487
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005488 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005489 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005490 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005491
Hugo Benichi39621362017-02-11 17:04:43 +09005492 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005493 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005494 }
5495
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005496 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005497 * Return the information of all ongoing VPNs.
5498 *
5499 * <p>This method is used to update NetworkStatsService.
5500 *
5501 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08005502 */
junyulai2050bed2021-01-23 09:46:34 +08005503 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005504 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09005505 if (mLockdownEnabled) {
5506 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08005507 }
junyulai2050bed2021-01-23 09:46:34 +08005508 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005509 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08005510 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005511 if (info != null) {
5512 infoList.add(info);
5513 }
5514 }
junyulai2050bed2021-01-23 09:46:34 +08005515 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08005516 }
5517
5518 /**
5519 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00005520 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08005521 */
junyulai2050bed2021-01-23 09:46:34 +08005522 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005523 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08005524 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5525 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09005526 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5527 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5528 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08005529 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5530 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00005531 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00005532 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08005533 }
5534 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005535
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005536 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005537
5538 List<String> interfaces = new ArrayList<>();
5539 for (Network network : underlyingNetworks) {
5540 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5541 if (underlyingNai == null) continue;
5542 LinkProperties lp = underlyingNai.linkProperties;
5543 for (String iface : lp.getAllInterfaceNames()) {
5544 if (!TextUtils.isEmpty(iface)) {
5545 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00005546 }
5547 }
Benedict Wong34857f82019-06-12 17:46:15 +00005548 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005549
5550 if (interfaces.isEmpty()) return null;
5551
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005552 // Must be non-null or NetworkStatsService will crash.
5553 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5554 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08005555 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08005556 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005557
junyulai2050bed2021-01-23 09:46:34 +08005558 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5559 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08005560 }
5561
James Mattisd31bdfa2020-12-23 16:37:26 -08005562 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08005563 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5564 Network[] underlyingNetworks) {
5565 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005566 if (underlyingNetworks == null && defaultNetwork != null) {
5567 // null underlying networks means to track the default.
5568 underlyingNetworks = new Network[] { defaultNetwork };
5569 }
5570 return underlyingNetworks;
5571 }
5572
5573 // Returns true iff |network| is an underlying network of |nai|.
5574 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5575 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5576 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09005577 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08005578 final Network[] underlying = underlyingNetworksOrDefault(
5579 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005580 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005581 }
5582
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005583 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005584 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005585 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005586 * When underlying networks change, such networks may have to update capabilities to reflect
5587 * things like the metered bit, their transports, and so on. The capabilities are calculated
5588 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005589 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005590 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005591 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005592 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005593 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005594 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005595 }
5596 }
5597 }
5598
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005599 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5600 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5601 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5602 // a VPN is not up.
5603 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5604 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5605 for (UidRange range : blockedUidRanges) {
5606 if (range.contains(uid)) return true;
5607 }
5608 return false;
5609 }
5610
5611 @Override
5612 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08005613 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005614 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5615 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5616 }
5617
5618 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5619 if (DBG) {
5620 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5621 + Arrays.toString(ranges));
5622 }
5623 // Cannot use a Set since the list of UID ranges might contain duplicates.
5624 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5625 for (int i = 0; i < ranges.length; i++) {
5626 if (requireVpn) {
5627 newVpnBlockedUidRanges.add(ranges[i]);
5628 } else {
5629 newVpnBlockedUidRanges.remove(ranges[i]);
5630 }
5631 }
5632
5633 try {
5634 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5635 } catch (RemoteException | ServiceSpecificException e) {
5636 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5637 + Arrays.toString(ranges) + "): netd command failed: " + e);
5638 }
5639
5640 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5641 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00005642 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5643 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005644 }
5645
5646 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5647 }
5648
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07005649 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005650 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08005651 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005652 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01005653 }
5654
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005655 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5656 return mLockdownEnabled
5657 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5658 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00005659 }
5660
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005661 private NetworkAgentInfo getLegacyLockdownNai() {
5662 if (!mLockdownEnabled) {
5663 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005664 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005665 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005666 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5667 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005668
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005669 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005670 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5671 // a local variable. There is no need to make a copy because its contents cannot change.
5672 final Network[] underlying = nai.declaredUnderlyingNetworks;
5673 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005674 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005675 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005676
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005677 // The legacy lockdown VPN always uses the default network.
5678 // If the VPN's underlying network is no longer the current default network, it means that
5679 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005680 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5681 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005682 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005683 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005684 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005685 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005686
5687 return nai;
5688 };
5689
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005690 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5691 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5692 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005693 private DetailedState getLegacyLockdownState(DetailedState origState) {
5694 if (origState != DetailedState.CONNECTED) {
5695 return origState;
5696 }
5697 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5698 ? DetailedState.CONNECTING
5699 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005700 }
5701
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005702 private void filterForLegacyLockdown(NetworkInfo ni) {
5703 if (!mLockdownEnabled || !ni.isConnected()) return;
5704 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5705 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5706 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5707 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5708 // network, this time with a state of CONNECTED.
5709 //
5710 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5711 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5712 // is not too far off the truth, since an always-on VPN, when not connected, is always
5713 // trying to reconnect.
5714 if (getLegacyLockdownNai() == null) {
5715 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5716 }
5717 }
5718
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005719 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005720 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04005721 String action) {
paulhu8e96a752019-08-12 16:25:11 +08005722 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09005723 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5724 return;
5725 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04005726 final long ident = Binder.clearCallingIdentity();
5727 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09005728 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09005729 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09005730 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04005731 } finally {
5732 Binder.restoreCallingIdentity(ident);
5733 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005734 }
Wink Savillecb117d32013-08-29 14:57:08 -07005735
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005736 @Override
5737 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01005738 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005739 final long ident = Binder.clearCallingIdentity();
5740 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005741 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09005742 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005743 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5744 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08005745 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005746 } finally {
5747 Binder.restoreCallingIdentity(ident);
5748 }
5749 }
5750
James Mattis02220e22021-03-13 19:27:21 -08005751 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005752 mPermissionMonitor.onUserAdded(user);
James Mattisae9aeb02021-03-01 17:09:11 -08005753 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5754 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5755 }
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005756 }
5757
James Mattis02220e22021-03-13 19:27:21 -08005758 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005759 mPermissionMonitor.onUserRemoved(user);
Chalard Jean0f57a492021-03-09 21:09:20 +09005760 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005761 handleSetProfileNetworkPreference(
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08005762 List.of(new ProfileNetworkPreferenceList.Preference(user, null, true)),
Chalard Jean0f57a492021-03-09 21:09:20 +09005763 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08005764 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5765 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5766 }
junyulaid91e7052020-08-28 13:44:33 +08005767 }
5768
James Mattis02220e22021-03-13 19:27:21 -08005769 private void onPackageChanged(@NonNull final String packageName) {
5770 // This is necessary in case a package is added or removed, but also when it's replaced to
5771 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5772 // as one in the preferences, then it should follow the same routing as that other package,
5773 // which means updating the rules is never to be needed in this case (whether it joins or
5774 // leaves a UID with a preference).
5775 if (isMappedInOemNetworkPreference(packageName)) {
5776 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5777 }
5778 }
5779
5780 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005781 @Override
5782 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09005783 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005784 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005785 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08005786
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005787 // User should be filled for below intents, check the existence.
5788 if (user == null) {
5789 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5790 return;
5791 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005792
Lorenzo Colitticd675292021-02-04 17:32:07 +09005793 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005794 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005795 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005796 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09005797 } else {
junyulaid91e7052020-08-28 13:44:33 +08005798 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005799 }
5800 }
5801 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07005802
James Mattis02220e22021-03-13 19:27:21 -08005803 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5804 @Override
5805 public void onReceive(Context context, Intent intent) {
5806 ensureRunningOnConnectivityServiceThread();
5807 switch (intent.getAction()) {
5808 case Intent.ACTION_PACKAGE_ADDED:
5809 case Intent.ACTION_PACKAGE_REMOVED:
5810 case Intent.ACTION_PACKAGE_REPLACED:
5811 onPackageChanged(intent.getData().getSchemeSpecificPart());
5812 break;
5813 default:
5814 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5815 }
5816 }
5817 };
5818
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005819 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005820 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005821
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005822 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005823 public final String name;
5824 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005825 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005826 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005827
lifraf3a3492021-03-10 13:58:14 +08005828 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5829 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005830 this.name = name;
5831 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005832 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005833 mDeathRecipient = deathRecipient;
5834
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005835 if (mDeathRecipient == null) {
5836 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005837 }
5838 }
5839
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005840 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005841 try {
5842 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5843 } catch (RemoteException e) {
5844 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005845 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005846 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005847 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005848
James Mattis4fce5d12020-11-12 15:53:42 -08005849 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
5850 for (int i = 0; i < requests.size(); i++) {
5851 ensureNetworkRequestHasType(requests.get(i));
5852 }
5853 }
5854
Lorenzo Colitti70964d32016-07-05 01:22:13 +09005855 private void ensureNetworkRequestHasType(NetworkRequest request) {
5856 if (request.type == NetworkRequest.Type.NONE) {
5857 throw new IllegalArgumentException(
5858 "All NetworkRequests in ConnectivityService must have a type");
5859 }
5860 }
5861
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005862 /**
5863 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08005864 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005865 */
James Mattis258ea3c2020-11-15 15:04:40 -08005866 @VisibleForTesting
5867 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08005868 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
5869 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08005870 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08005871
James Mattisa076c532020-12-02 14:12:41 -08005872 // mSatisfier and mActiveRequest rely on one another therefore set them together.
5873 void setSatisfier(
5874 @Nullable final NetworkAgentInfo satisfier,
5875 @Nullable final NetworkRequest activeRequest) {
5876 mSatisfier = satisfier;
5877 mActiveRequest = activeRequest;
5878 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005879
James Mattisd31bdfa2020-12-23 16:37:26 -08005880 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005881 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09005882 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08005883 private NetworkAgentInfo mSatisfier;
5884 NetworkAgentInfo getSatisfier() {
5885 return mSatisfier;
5886 }
5887
5888 // The request in mRequests assigned to a network agent. This is null if none of the
5889 // requests in mRequests can be satisfied. This member has the constraint of only being
5890 // accessible on the handler thread.
5891 @Nullable
5892 private NetworkRequest mActiveRequest;
5893 NetworkRequest getActiveRequest() {
5894 return mActiveRequest;
5895 }
5896
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005897 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08005898 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08005899 @Nullable
5900 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005901
5902 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08005903 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005904 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005905 final int mPid;
5906 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08005907 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005908 @Nullable
5909 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005910
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005911 // Counter keeping track of this NRI.
5912 final PerUidCounter mPerUidCounter;
5913
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005914 // Effective UID of this request. This is different from mUid when a privileged process
5915 // files a request on behalf of another UID. This UID is used to determine blocked status,
5916 // UID matching, and so on. mUid above is used for permission checks and to enforce the
5917 // maximum limit of registered callbacks per UID.
5918 final int mAsUid;
5919
paulhu48291862021-07-14 14:53:57 +08005920 // Preference order of this request.
5921 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08005922
James Mattis3ce3d3c2021-02-09 18:18:28 -08005923 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
5924 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
5925 // maintained for keying off of. This is only a concern when the original nri
5926 // mNetworkRequests changes which happens currently for apps that register callbacks to
5927 // track the default network. In those cases, the nri is updated to have mNetworkRequests
5928 // that match the per-app default nri that currently tracks the calling app's uid so that
5929 // callbacks are fired at the appropriate time. When the callbacks fire,
5930 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
5931 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
5932 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
5933 @NonNull
5934 private final NetworkRequest mNetworkRequestForCallback;
5935 NetworkRequest getNetworkRequestForCallback() {
5936 return mNetworkRequestForCallback;
5937 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005938
James Mattisd31bdfa2020-12-23 16:37:26 -08005939 /**
5940 * Get the list of UIDs this nri applies to.
5941 */
5942 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00005943 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08005944 // networkCapabilities.getUids() returns a defensive copy.
5945 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00005946 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
5947 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08005948 }
5949
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005950 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
5951 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08005952 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08005953 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08005954 }
5955
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005956 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08005957 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08005958 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005959 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08005960 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08005961 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005962 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08005963 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005964 mBinder = null;
5965 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005966 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005967 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005968 mPerUidCounter = getRequestCounter(this);
5969 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005970 /**
5971 * Location sensitive data not included in pending intent. Only included in
5972 * {@link NetworkCallback}.
5973 */
5974 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005975 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08005976 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005977 }
5978
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005979 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08005980 @Nullable final IBinder binder,
5981 @NetworkCallback.Flag int callbackFlags,
5982 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005983 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
5984 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08005985 }
5986
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005987 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08005988 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08005989 @Nullable final IBinder binder,
5990 @NetworkCallback.Flag int callbackFlags,
5991 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005992 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08005993 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08005994 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08005995 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08005996 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005997 mBinder = binder;
5998 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005999 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006000 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006001 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006002 mPerUidCounter = getRequestCounter(this);
6003 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006004 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006005 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006006 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006007 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006008 }
6009
James Mattis3ce3d3c2021-02-09 18:18:28 -08006010 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6011 @NonNull final List<NetworkRequest> r) {
6012 super();
6013 ensureAllNetworkRequestsHaveType(r);
6014 mRequests = initializeRequests(r);
6015 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006016 final NetworkAgentInfo satisfier = nri.getSatisfier();
6017 if (null != satisfier) {
6018 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6019 // The active request is necessary to figure out what callbacks to send, in
6020 // particular then a network updates its capabilities.
6021 // As this code creates a new NRI with a new set of requests, figure out which of
6022 // the list of requests should be the active request. It is always the first
6023 // request of the list that can be satisfied by the satisfier since the order of
6024 // requests is a priority order.
6025 // Note even in the presence of a satisfier there may not be an active request,
6026 // when the satisfier is the no-service network.
6027 NetworkRequest activeRequest = null;
6028 for (final NetworkRequest candidate : r) {
6029 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6030 activeRequest = candidate;
6031 break;
6032 }
6033 }
6034 setSatisfier(satisfier, activeRequest);
6035 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006036 mMessenger = nri.mMessenger;
6037 mBinder = nri.mBinder;
6038 mPid = nri.mPid;
6039 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006040 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006041 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006042 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006043 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006044 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006045 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006046 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006047 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006048 }
6049
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006050 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006051 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006052 }
6053
paulhue9913722021-05-26 15:19:20 +08006054 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006055 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006056 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006057 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006058 }
6059
James Mattis2516da32021-01-31 17:06:19 -08006060 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6061 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6062 // false.
6063 boolean isBeingSatisfied() {
6064 return (null != mSatisfier && null != mActiveRequest);
6065 }
6066
James Mattis3d229892020-11-16 16:46:28 -08006067 boolean isMultilayerRequest() {
6068 return mRequests.size() > 1;
6069 }
6070
James Mattis45d81842021-01-10 14:24:24 -08006071 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6072 // Creating a defensive copy to prevent the sender from modifying the list being
6073 // reflected in the return value of this method.
6074 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006075 return Collections.unmodifiableList(tempRequests);
6076 }
6077
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006078 void decrementRequestCount() {
6079 mPerUidCounter.decrementCount(mUid);
6080 }
6081
James Mattisb1392002021-03-31 13:57:52 -07006082 void linkDeathRecipient() {
6083 if (null != mBinder) {
6084 try {
6085 mBinder.linkToDeath(this, 0);
6086 } catch (RemoteException e) {
6087 binderDied();
6088 }
6089 }
6090 }
6091
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006092 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006093 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006094 try {
6095 mBinder.unlinkToDeath(this, 0);
6096 } catch (NoSuchElementException e) {
6097 // Temporary workaround for b/194394697 pending analysis of additional logs
6098 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6099 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006100 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006101 }
6102
paulhu48291862021-07-14 14:53:57 +08006103 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6104 // Compare two preference orders.
6105 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006106 }
6107
paulhu48291862021-07-14 14:53:57 +08006108 int getPreferenceOrderForNetd() {
6109 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6110 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6111 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006112 }
paulhu48291862021-07-14 14:53:57 +08006113 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006114 }
6115
James Mattis4fce5d12020-11-12 15:53:42 -08006116 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006117 public void binderDied() {
6118 log("ConnectivityService NetworkRequestInfo binderDied(" +
Chalard Jean524f0b12021-10-25 21:11:56 +09006119 "uid/pid:" + mUid + "/" + mPid + ", " + mRequests + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09006120 // As an immutable collection, mRequests cannot change by the time the
6121 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6122 // is acceptable. Use handleReleaseNetworkRequest and not directly
6123 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6124 // the app already unregistered the request.
6125 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6126 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006127 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006128
James Mattis4fce5d12020-11-12 15:53:42 -08006129 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006130 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006131 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6132 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006133 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006134 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006135 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006136 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006137 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006138 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006139 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006140 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006141 }
6142
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006143 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
6144 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
6145 if (badCapability != null) {
6146 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenee52d232015-06-16 15:11:58 -04006147 }
6148 }
6149
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006150 // This checks that the passed capabilities either do not request a
6151 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006152 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006153 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006154 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006155 throw new SecurityException("Insufficient permissions to request a specific SSID");
6156 }
paulhu1a407652019-03-22 16:35:06 +08006157
6158 if (nc.hasSignalStrength()
6159 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6160 throw new SecurityException(
6161 "Insufficient permissions to request a specific signal strength");
6162 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006163 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006164
junyulai2217bec2021-04-14 23:33:31 +08006165 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006166 enforceNetworkFactoryPermission();
6167 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006168 }
6169
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006170 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006171 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006172 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006173 // mNetworkRequests may contain the same value multiple times in case of
6174 // multilayer requests. It won't matter in this case because the thresholds
6175 // will then be the same and be deduplicated as they enter the `thresholds` set.
6176 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006177 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6178 for (final NetworkRequest req : nri.mRequests) {
6179 if (req.networkCapabilities.hasSignalStrength()
6180 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6181 thresholds.add(req.networkCapabilities.getSignalStrength());
6182 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006183 }
6184 }
6185 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006186 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006187 }
6188
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006189 private void updateSignalStrengthThresholds(
6190 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006191 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006192
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006193 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006194 String detail;
6195 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6196 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6197 } else {
6198 detail = reason;
6199 }
6200 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006201 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006202 }
6203
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006204 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006205 }
6206
Etan Cohen1b6d4182017-04-03 17:42:34 -07006207 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
6208 if (nc == null) {
6209 return;
6210 }
6211 NetworkSpecifier ns = nc.getNetworkSpecifier();
6212 if (ns == null) {
6213 return;
6214 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006215 if (ns instanceof MatchAllNetworkSpecifier) {
6216 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6217 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006218 }
6219
lucasline117e2e2019-10-22 18:27:33 +08006220 private void ensureValid(NetworkCapabilities nc) {
6221 ensureValidNetworkSpecifier(nc);
6222 if (nc.isPrivateDnsBroken()) {
6223 throw new IllegalArgumentException("Can't request broken private DNS");
6224 }
Chalard Jean9a30acf2021-12-13 22:53:51 +09006225 if (nc.hasAccessUids()) {
6226 throw new IllegalArgumentException("Can't request access UIDs");
6227 }
lucasline117e2e2019-10-22 18:27:33 +08006228 }
6229
Chiachang Wang3bc52762021-11-25 14:17:57 +08006230 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6231 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006232 private boolean isTargetSdkAtleast(int version, int callingUid,
6233 @NonNull String callingPackageName) {
6234 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006235 final PackageManager pm =
6236 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006237 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006238 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006239 if (callingVersion < version) return false;
6240 } catch (PackageManager.NameNotFoundException e) { }
6241 return true;
6242 }
6243
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006244 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006245 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006246 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006247 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006248 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006249 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006250 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6251 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006252 throw new SecurityException("Insufficient permissions to specify legacy type");
6253 }
markchienfac84a22020-03-18 21:16:15 +08006254 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006255 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006256 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006257 // Privileged callers can track the default network of another UID by passing in a UID.
6258 if (asUid != Process.INVALID_UID) {
6259 enforceSettingsPermission();
6260 } else {
6261 asUid = callingUid;
6262 }
junyulaiad010792021-01-11 16:53:38 +08006263 final NetworkRequest.Type reqType;
6264 try {
6265 reqType = NetworkRequest.Type.values()[reqTypeInt];
6266 } catch (ArrayIndexOutOfBoundsException e) {
6267 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6268 }
6269 switch (reqType) {
6270 case TRACK_DEFAULT:
6271 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006272 // is unused and will be replaced by ones appropriate for the UID (usually, the
6273 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006274 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006275 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006276 enforceAccessPermission();
6277 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006278 case TRACK_SYSTEM_DEFAULT:
6279 enforceSettingsPermission();
6280 networkCapabilities = new NetworkCapabilities(defaultNc);
6281 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006282 case BACKGROUND_REQUEST:
6283 enforceNetworkStackOrSettingsPermission();
6284 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006285 case REQUEST:
6286 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6287 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6288 callingAttributionTag);
6289 // TODO: this is incorrect. We mark the request as metered or not depending on
6290 // the state of the app when the request is filed, but we never change the
6291 // request if the app changes network state. http://b/29964605
6292 enforceMeteredApnPolicy(networkCapabilities);
6293 break;
junyulai1b1c8742021-03-12 20:05:08 +08006294 case LISTEN_FOR_BEST:
6295 enforceAccessPermission();
6296 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6297 break;
junyulaiad010792021-01-11 16:53:38 +08006298 default:
6299 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006300 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006301 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006302 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006303 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006304
junyulai1b1c8742021-03-12 20:05:08 +08006305 // Enforce FOREGROUND if the caller does not have permission to use background network.
6306 if (reqType == LISTEN_FOR_BEST) {
6307 restrictBackgroundRequestForCaller(networkCapabilities);
6308 }
6309
6310 // Set the UID range for this request to the single UID of the requester, unless the
6311 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006312 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6313 // are no visible methods to set the UIDs, an app could use reflection to try and get
6314 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006315 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006316 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6317 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006318
Etan Cohen85000162017-02-05 10:42:27 -08006319 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006320 throw new IllegalArgumentException("Bad timeout specified");
6321 }
lucasline117e2e2019-10-22 18:27:33 +08006322 ensureValid(networkCapabilities);
Etan Cohen9786d922015-11-18 10:56:15 -08006323
James Mattis3ce3d3c2021-02-09 18:18:28 -08006324 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006325 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006326 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006327 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006328 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006329 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006330
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006331 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6332 // copied from the default request above. (This is necessary to ensure, for example, that
6333 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6334 // changes don't alter request matching.
6335 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6336 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006337 throw new IllegalStateException(
6338 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006339 + networkCapabilities + " vs. " + defaultNc);
6340 }
6341
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006342 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006343 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006344 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006345 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006346 }
6347 return networkRequest;
6348 }
6349
James Mattis3ce3d3c2021-02-09 18:18:28 -08006350 /**
6351 * Return the nri to be used when registering a network request. Specifically, this is used with
6352 * requests registered to track the default request. If there is currently a per-app default
6353 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6354 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006355 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6356 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006357 * @param nr the network request for the nri.
6358 * @param msgr the messenger for the nri.
6359 * @param binder the binder for the nri.
6360 * @param callingAttributionTag the calling attribution tag for the nri.
6361 * @return the nri to register.
6362 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006363 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006364 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006365 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006366 @Nullable String callingAttributionTag) {
6367 final List<NetworkRequest> requests;
6368 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6369 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006370 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006371 } else {
6372 requests = Collections.singletonList(nr);
6373 }
Roshan Pius951c0032020-12-22 15:10:42 -08006374 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006375 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006376 }
6377
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006378 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
6379 String callingPackageName, String callingAttributionTag) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006380 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006381 if (!networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
6382 enforceConnectivityRestrictedNetworksPermission();
6383 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006384 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006385 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006386 }
6387 }
6388
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006389 private boolean checkConnectivityRestrictedNetworksPermission(int callerPid, int callerUid) {
6390 if (checkAnyPermissionOf(callerPid, callerUid,
6391 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)
6392 || checkAnyPermissionOf(callerPid, callerUid,
6393 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
6394 return true;
6395 }
6396 return false;
6397 }
6398
fenglu3f357402015-03-20 11:29:56 -07006399 @Override
fenglub00f4882015-04-21 17:12:05 -07006400 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006401 enforceAccessPermission();
6402 NetworkAgentInfo nai = null;
6403 if (network == null) {
6404 return false;
6405 }
6406 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006407 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006408 }
6409 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006410 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006411 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006412 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006413 Integer uidReqs = mBandwidthRequests.get(uid);
6414 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006415 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006416 }
6417 mBandwidthRequests.put(uid, ++uidReqs);
6418 }
fenglu3f357402015-03-20 11:29:56 -07006419 return true;
6420 }
6421 return false;
6422 }
6423
Felipe Leme0a5ae422016-06-20 16:36:29 -07006424 private boolean isSystem(int uid) {
6425 return uid < Process.FIRST_APPLICATION_UID;
6426 }
fenglu3f357402015-03-20 11:29:56 -07006427
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006428 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006429 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006430 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006431 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006432 return;
6433 }
Hugo Benichi39621362017-02-11 17:04:43 +09006434 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6435 // Policy already enforced.
6436 return;
6437 }
paulhuaf50d7d2020-12-24 19:47:34 +08006438 final long ident = Binder.clearCallingIdentity();
6439 try {
6440 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6441 // If UID is restricted, don't allow them to bring up metered APNs.
6442 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6443 }
6444 } finally {
6445 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006446 }
6447 }
6448
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006449 @Override
6450 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006451 PendingIntent operation, @NonNull String callingPackageName,
6452 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006453 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006454 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006455 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006456 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6457 callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006458 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006459 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006460 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006461 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006462 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6463 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09006464 ensureValid(networkCapabilities);
6465
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006466 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006467 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006468 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6469 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006470 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006471 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6472 nri));
6473 return networkRequest;
6474 }
6475
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006476 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6477 mHandler.sendMessageDelayed(
6478 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006479 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006480 }
6481
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006482 @Override
6483 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006484 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006485 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006486 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006487 }
6488
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006489 // In order to implement the compatibility measure for pre-M apps that call
6490 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6491 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6492 // This ensures it has permission to do so.
6493 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6494 if (nc == null) {
6495 return false;
6496 }
6497 int[] transportTypes = nc.getTransportTypes();
6498 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6499 return false;
6500 }
6501 try {
6502 mContext.enforceCallingOrSelfPermission(
6503 android.Manifest.permission.ACCESS_WIFI_STATE,
6504 "ConnectivityService");
6505 } catch (SecurityException e) {
6506 return false;
6507 }
6508 return true;
6509 }
6510
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006511 @Override
6512 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08006513 Messenger messenger, IBinder binder,
6514 @NetworkCallback.Flag int callbackFlags,
6515 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006516 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006517 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6518 enforceAccessPermission();
6519 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006520
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006521 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006522 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006523 Binder.getCallingPid(), callingUid, callingPackageName);
6524 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09006525 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6526 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6527 // onLost and onAvailable callbacks when networks move in and out of the background.
6528 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6529 // can't request networks.
6530 restrictBackgroundRequestForCaller(nc);
lucasline117e2e2019-10-22 18:27:33 +08006531 ensureValid(nc);
Etan Cohen89134542017-04-03 12:17:51 -07006532
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006533 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006534 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08006535 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006536 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08006537 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006538 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006539
6540 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6541 return networkRequest;
6542 }
6543
6544 @Override
6545 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08006546 PendingIntent operation, @NonNull String callingPackageName,
6547 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006548 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006549 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04006550 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6551 enforceAccessPermission();
6552 }
lucasline117e2e2019-10-22 18:27:33 +08006553 ensureValid(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006554 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006555 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006556 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006557 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006558
6559 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006560 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006561 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6562 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006563 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04006564
WeiZhang1cc3f172021-06-03 19:02:04 -05006565 mHandler.sendMessage(mHandler.obtainMessage(
6566 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006567 }
6568
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006569 /** Returns the next Network provider ID. */
6570 public final int nextNetworkProviderId() {
6571 return mNextNetworkProviderId.getAndIncrement();
6572 }
6573
Erik Kline0c04b742016-07-07 16:50:58 +09006574 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006575 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006576 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09006577 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006578 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006579 }
6580
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006581 private void releaseNetworkRequestAndCallOnUnavailable(NetworkRequest networkRequest) {
6582 ensureNetworkRequestHasType(networkRequest);
6583 mHandler.sendMessage(mHandler.obtainMessage(
6584 EVENT_RELEASE_NETWORK_REQUEST_AND_CALL_UNAVAILABLE, mDeps.getCallingUid(), 0,
6585 networkRequest));
6586 }
6587
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006588 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6589 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006590 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6591 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6592 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08006593 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006594 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006595 return;
6596 }
6597
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006598 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6599 mNetworkProviderInfos.put(npi.messenger, npi);
6600 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006601 }
6602
6603 @Override
6604 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006605 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08006606 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006607 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08006608 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006609 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6610 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006611 }
6612
6613 @Override
6614 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006615 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006616 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006617 }
6618
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006619 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09006620 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006621 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6622 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09006623 Objects.requireNonNull(score);
6624 Objects.requireNonNull(caps);
6625 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09006626 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006627 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09006628 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
6629 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006630 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6631 }
6632
Chalard Jeanbb902a52021-08-18 01:35:19 +09006633 private void updateOfferScore(final NetworkOffer offer) {
6634 final boolean yieldToBadWiFi =
6635 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
6636 final NetworkOffer newOffer = new NetworkOffer(
6637 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
6638 offer.caps, offer.callback, offer.providerId);
6639 if (offer.equals(newOffer)) return;
6640 handleRegisterNetworkOffer(newOffer);
6641 }
6642
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006643 @Override
6644 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6645 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6646 }
6647
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006648 private void handleUnregisterNetworkProvider(Messenger messenger) {
6649 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6650 if (npi == null) {
6651 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006652 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006653 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006654 // Unregister all the offers from this provider
6655 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6656 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09006657 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006658 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6659 toRemove.add(noi);
6660 }
6661 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09006662 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006663 handleUnregisterNetworkOffer(noi);
6664 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006665 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006666 }
6667
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006668 @Override
James Mattisf7027322020-12-13 16:28:14 -08006669 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006670 if (request.hasTransport(TRANSPORT_TEST)) {
6671 enforceNetworkFactoryOrTestNetworksPermission();
6672 } else {
6673 enforceNetworkFactoryPermission();
6674 }
James Mattisf7027322020-12-13 16:28:14 -08006675 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6676 if (nri != null) {
6677 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6678 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6679 mHandler.post(() -> handleReleaseNetworkRequest(
6680 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6681 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006682 }
6683
Paul Jensen1f567382015-02-13 14:18:39 -05006684 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6685 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006686 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05006687 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006688 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05006689 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006690 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006691
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09006692 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05006693 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006694 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006695
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006696 // UID ranges for users that are currently blocked by VPNs.
6697 // This array is accessed and iterated on multiple threads without holding locks, so its
6698 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6699 // (on the handler thread).
6700 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6701
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006702 // Must only be accessed on the handler thread
6703 @NonNull
6704 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6705
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006706 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006707 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006708
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006709 // Current OEM network preferences. This object must only be written to on the handler thread.
6710 // Since it is immutable and always non-null, other threads may read it if they only care
6711 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08006712 @NonNull
6713 private OemNetworkPreferences mOemNetworkPreferences =
6714 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006715 // Current per-profile network preferences. This object follows the same threading rules as
6716 // the OEM network preferences above.
6717 @NonNull
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006718 private ProfileNetworkPreferenceList mProfileNetworkPreferences =
6719 new ProfileNetworkPreferenceList();
James Mattis45d81842021-01-10 14:24:24 -08006720
paulhu51f77dc2021-06-07 02:34:20 +00006721 // A set of UIDs that should use mobile data preferentially if available. This object follows
6722 // the same threading rules as the OEM network preferences above.
6723 @NonNull
6724 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
6725
James Mattiscb1e0362021-04-06 17:07:42 -07006726 // OemNetworkPreferences activity String log entries.
6727 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6728 @NonNull
6729 private final LocalLog mOemNetworkPreferencesLogs =
6730 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6731
James Mattis02220e22021-03-13 19:27:21 -08006732 /**
6733 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6734 * @param packageName the package name to check existence of a mapping for.
6735 * @return true if a mapping exists, false otherwise
6736 */
6737 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6738 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6739 }
6740
James Mattise3ef1912020-12-20 11:09:58 -08006741 // The always-on request for an Internet-capable network that apps without a specific default
6742 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08006743 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09006744 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006745 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08006746 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08006747 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08006748 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006749 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006750
James Mattisd31bdfa2020-12-23 16:37:26 -08006751 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6752 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6753 }
6754
6755 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08006756 * Return the default network request currently tracking the given uid.
6757 * @param uid the uid to check.
6758 * @return the NetworkRequestInfo tracking the given uid.
6759 */
6760 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08006761 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08006762 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006763 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006764 // Checking the first request is sufficient as only multilayer requests will have more
6765 // than one request and for multilayer, all requests will track the same uids.
6766 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08006767 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08006768 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08006769 highestPriorityNri = nri;
6770 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006771 }
6772 }
paulhuaa0743d2021-05-26 21:56:03 +08006773 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006774 }
6775
6776 /**
6777 * Get a copy of the network requests of the default request that is currently tracking the
6778 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006779 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6780 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006781 * @param requestorUid the uid to check the default for.
6782 * @param requestorPackageName the requestor's package name.
6783 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6784 */
6785 @NonNull
6786 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006787 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006788 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006789 getDefaultRequestTrackingUid(asUid).mRequests,
6790 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006791 }
6792
6793 /**
6794 * Copy the given nri's NetworkRequest collection.
6795 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006796 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6797 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006798 * @param requestorUid the uid to set on the copied collection.
6799 * @param requestorPackageName the package name to set on the copied collection.
6800 * @return the copied NetworkRequest collection.
6801 */
6802 @NonNull
6803 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006804 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6805 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006806 final List<NetworkRequest> requests = new ArrayList<>();
6807 for (final NetworkRequest nr : requestsToCopy) {
6808 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006809 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08006810 nr.legacyType, nextNetworkRequestId(), nr.type));
6811 }
6812 return requests;
6813 }
6814
6815 @NonNull
6816 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006817 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6818 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09006819 // These capabilities are for a TRACK_DEFAULT callback, so:
6820 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6821 // mDefaultRequest and a per-UID default request.
6822 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006823 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09006824 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006825 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6826 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006827 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006828 restrictRequestUidsForCallerAndSetRequestorInfo(
6829 netCap, requestorUid, requestorPackageName);
6830 return netCap;
6831 }
6832
6833 /**
6834 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6835 * @param nr the network request to check for equality against.
6836 * @return the nri if one exists, null otherwise.
6837 */
6838 @Nullable
6839 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6840 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6841 if (nri.getNetworkRequestForCallback().equals(nr)) {
6842 return nri;
6843 }
6844 }
6845 return null;
6846 }
6847
6848 /**
6849 * Check if an nri is currently being managed by per-app default networking.
6850 * @param nri the nri to check.
6851 * @return true if this nri is currently being managed by per-app default networking.
6852 */
6853 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
6854 // nri.mRequests.get(0) is only different from the original request filed in
6855 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
6856 // functionality therefore if these two don't match, it means this particular nri is
6857 // currently being managed by a per-app default.
6858 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
6859 }
6860
6861 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08006862 * Determine if an nri is a managed default request that disallows default networking.
6863 * @param nri the request to evaluate
6864 * @return true if device-default networking is disallowed
6865 */
6866 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
6867 // Check if this nri is a managed default that supports the default network at its
6868 // lowest priority request.
6869 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
6870 final NetworkCapabilities lowestPriorityNetCap =
6871 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
6872 return isPerAppDefaultRequest(nri)
6873 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
6874 lowestPriorityNetCap));
6875 }
6876
Erik Kline05f2b402015-04-30 12:58:40 +09006877 // Request used to optionally keep mobile data active even when higher
6878 // priority networks like Wi-Fi are active.
6879 private final NetworkRequest mDefaultMobileDataRequest;
6880
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006881 // Request used to optionally keep wifi data active even when higher
6882 // priority networks like ethernet are active.
6883 private final NetworkRequest mDefaultWifiRequest;
6884
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08006885 // Request used to optionally keep vehicle internal network always active
6886 private final NetworkRequest mDefaultVehicleRequest;
6887
James Mattisd31bdfa2020-12-23 16:37:26 -08006888 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
6889 // network with no service. This NAI should never be matched against, nor should any public API
6890 // ever return the associated network. For this reason, this NAI is not in the list of available
6891 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
6892 // default requests that don't support using the device default network which will ultimately
6893 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
6894 @VisibleForTesting
6895 final NetworkAgentInfo mNoServiceNetwork;
6896
Chalard Jean5b409c72021-02-04 13:12:59 +09006897 // The NetworkAgentInfo currently satisfying the default request, if any.
6898 private NetworkAgentInfo getDefaultNetwork() {
6899 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09006900 }
6901
James Mattis2516da32021-01-31 17:06:19 -08006902 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08006903 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08006904 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6905 // Currently, all network requests will have the same uids therefore checking the first
6906 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006907 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08006908 if (null == uids) {
6909 continue;
6910 }
6911 for (final UidRange range : uids) {
6912 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08006913 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08006914 highestPriorityNri = nri;
6915 }
James Mattis2516da32021-01-31 17:06:19 -08006916 }
6917 }
6918 }
paulhuaa0743d2021-05-26 21:56:03 +08006919 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08006920 }
6921
Varun Ananddf569952019-02-06 10:13:38 -08006922 @Nullable
6923 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
6924 return nai != null ? nai.network : null;
6925 }
6926
6927 private void ensureRunningOnConnectivityServiceThread() {
6928 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
6929 throw new IllegalStateException(
6930 "Not running on ConnectivityService thread: "
6931 + Thread.currentThread().getName());
6932 }
6933 }
6934
Chalard Jean3a3f5f22019-04-10 23:07:55 +09006935 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09006936 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
6937 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006938 }
6939
Chalard Jean29d06db2018-05-02 21:14:54 +09006940 /**
6941 * Register a new agent with ConnectivityService to handle a network.
6942 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006943 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09006944 * @param networkInfo the initial info associated with this network. It can be updated later :
6945 * see {@link #updateNetworkInfo}.
6946 * @param linkProperties the initial link properties of this network. They can be updated
6947 * later : see {@link #updateLinkProperties}.
6948 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09006949 * later : see {@link #updateCapabilities}.
Chalard Jean28018572020-12-21 18:36:52 +09006950 * @param initialScore the initial score of the network. See
Chalard Jean29d06db2018-05-02 21:14:54 +09006951 * {@link NetworkAgentInfo#getCurrentScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006952 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006953 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09006954 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09006955 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006956 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09006957 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09006958 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
6959 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09006960 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
6961 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
6962 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09006963 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09006964 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09006965 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6966 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006967 } else {
6968 enforceNetworkFactoryPermission();
6969 }
6970
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006971 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006972 final long token = Binder.clearCallingIdentity();
6973 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006974 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09006975 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006976 } finally {
6977 Binder.restoreCallingIdentity(token);
6978 }
6979 }
6980
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006981 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006982 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09006983 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
6984 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006985
Chalard Jean366c5252022-01-25 18:27:53 +09006986 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
6987 // the capabilities' access UID comply with security limitations. They will be sanitized
6988 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
6989 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006990 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jean366c5252022-01-25 18:27:53 +09006991 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo),
6992 linkProperties, networkCapabilities,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09006993 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09006994 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
6995 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006996
Chalard Jeanf2da1772018-04-26 16:16:10 +09006997 final String extraInfo = networkInfo.getExtraInfo();
6998 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09006999 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007000 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007001 mDeps.getNetworkStack().makeNetworkMonitor(
7002 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007003 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7004 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007005 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007006 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007007 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007008 }
7009
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007010 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007011 if (VDBG) log("Network Monitor created for " + nai);
7012 // nai.nc and nai.lp are the same object that was passed by the network agent if the agent
7013 // lives in the same process as this code (e.g. wifi), so make sure this code doesn't
7014 // mutate their object
7015 final NetworkCapabilities nc = new NetworkCapabilities(nai.networkCapabilities);
7016 final LinkProperties lp = new LinkProperties(nai.linkProperties);
7017 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
7018 processCapabilitiesFromAgent(nai, nc);
7019 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
7020 processLinkPropertiesFromAgent(nai, lp);
7021 nai.linkProperties = lp;
7022
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007023 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007024
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007025 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007026 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007027 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007028 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007029
7030 try {
7031 networkMonitor.start();
7032 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007033 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007034 }
Chalard Jean366c5252022-01-25 18:27:53 +09007035
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007036 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007037 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007038 updateNetworkInfo(nai, networkInfo);
7039 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007040 }
7041
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007042 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7043 @NonNull public final NetworkOffer offer;
7044
7045 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7046 this.offer = offer;
7047 }
7048
7049 @Override
7050 public void binderDied() {
7051 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7052 }
7053 }
7054
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007055 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7056 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7057 if (npi.providerId == providerId) return true;
7058 }
7059 return false;
7060 }
7061
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007062 /**
7063 * Register or update a network offer.
7064 * @param newOffer The new offer. If the callback member is the same as an existing
7065 * offer, it is an update of that offer.
7066 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007067 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007068 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7069 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007070 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007071 // This may actually happen if a provider updates its score or registers and then
7072 // immediately unregisters. The offer would still be in the handler queue, but the
7073 // provider would have been removed.
7074 if (DBG) log("Received offer from an unregistered provider");
7075 return;
7076 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007077 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7078 if (null != existingOffer) {
7079 handleUnregisterNetworkOffer(existingOffer);
7080 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007081 if (DBG) {
7082 // handleUnregisterNetworkOffer has already logged the old offer
7083 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7084 }
7085 } else {
7086 if (DBG) {
7087 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7088 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007089 }
7090 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7091 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007092 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007093 } catch (RemoteException e) {
7094 noi.binderDied();
7095 return;
7096 }
7097 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007098 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007099 }
7100
7101 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7102 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007103 if (DBG) {
7104 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7105 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007106
7107 // If the provider removes the offer and dies immediately afterwards this
7108 // function may be called twice in a row, but the array will no longer contain
7109 // the offer.
7110 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007111 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007112 }
7113
7114 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7115 @NonNull final INetworkOfferCallback callback) {
7116 ensureRunningOnConnectivityServiceThread();
7117 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007118 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007119 }
7120 return null;
7121 }
7122
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007123 /**
7124 * Called when receiving LinkProperties directly from a NetworkAgent.
7125 * Stores into |nai| any data coming from the agent that might also be written to the network's
7126 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7127 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007128 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007129 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007130 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7131 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007132 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007133 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007134 }
7135
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007136 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007137 @NonNull LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007138 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007139
Lorenzo Colittid523d142020-04-01 20:16:30 +09007140 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7141 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7142 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007143 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007144
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007145 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007146
7147 // update filtering rules, need to happen after the interface update so netd knows about the
7148 // new interface (the interface name -> index map becomes initialized)
7149 updateVpnFiltering(newLp, oldLp, networkAgent);
7150
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007151 updateMtu(newLp, oldLp);
7152 // TODO - figure out what to do for clat
7153// for (LinkProperties lp : newLp.getStackedLinks()) {
7154// updateMtu(lp, null);
7155// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007156 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007157 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7158 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007159
Erik Klineb9888902016-04-05 13:30:49 +09007160 updateRoutes(newLp, oldLp, netId);
7161 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007162 // Make sure LinkProperties represents the latest private DNS status.
7163 // This does not need to be done before updateDnses because the
7164 // LinkProperties are not the source of the private DNS configuration.
7165 // updateDnses will fetch the private DNS configuration from DnsManager.
7166 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007167
Chalard Jean5b409c72021-02-04 13:12:59 +09007168 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007169 handleApplyDefaultProxy(newLp.getHttpProxy());
7170 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007171 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007172 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007173
7174 updateWakeOnLan(newLp);
7175
Hai Shalome58bdc62021-01-11 18:45:34 -08007176 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7177 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7178 // does, it needs to be merged here.
7179 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7180 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007181
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007182 // TODO - move this check to cover the whole function
7183 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007184 synchronized (networkAgent) {
7185 networkAgent.linkProperties = newLp;
7186 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007187 // Start or stop DNS64 detection and 464xlat according to network state.
7188 networkAgent.clatd.update();
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08007189 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007190 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7191 new LinkProperties(newLp, true /* parcelSensitiveFields */));
lucaslin74fa3972018-11-28 12:51:55 +08007192 if (networkAgent.everConnected) {
7193 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
7194 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007195 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007196
7197 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007198 }
7199
Hai Shalome58bdc62021-01-11 18:45:34 -08007200 /**
7201 * @param naData captive portal data from NetworkAgent
7202 * @param apiData captive portal data from capport API
7203 */
7204 @Nullable
7205 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7206 CaptivePortalData apiData) {
7207 if (naData == null || apiData == null) {
7208 return naData == null ? apiData : naData;
7209 }
7210 final CaptivePortalData.Builder captivePortalBuilder =
7211 new CaptivePortalData.Builder(naData);
7212
7213 if (apiData.isCaptive()) {
7214 captivePortalBuilder.setCaptive(true);
7215 }
7216 if (apiData.isSessionExtendable()) {
7217 captivePortalBuilder.setSessionExtendable(true);
7218 }
7219 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7220 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7221 // otherwise data would be inconsistent. Prefer the capport API info if present,
7222 // as it can generally be refreshed more often.
7223 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7224 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7225 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7226 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7227 // No source has time / bytes remaining information: surface the newest refresh time
7228 // for other fields
7229 captivePortalBuilder.setRefreshTime(
7230 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7231 }
7232
Hai Shalom7c6ab402021-02-04 19:34:06 -08007233 // Prioritize the user portal URL from the network agent if the source is authenticated.
7234 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7235 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7236 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7237 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007238 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007239 // Prioritize the venue information URL from the network agent if the source is
7240 // authenticated.
7241 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7242 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7243 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7244 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007245 }
7246 return captivePortalBuilder.build();
7247 }
7248
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007249 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007250 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007251 // marks on unsupported interfaces is harmless.
7252 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7253 return;
7254 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007255
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007256 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7257 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7258
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007259 // Mask/mark of zero will not detect anything interesting.
7260 // Don't install rules unless both values are nonzero.
7261 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007262 return;
7263 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007264
7265 final String prefix = "iface:" + iface;
7266 try {
7267 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007268 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007269 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007270 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007271 }
7272 } catch (Exception e) {
7273 loge("Exception modifying wakeup packet monitoring: " + e);
7274 }
7275
Joel Scherpelza235a812017-05-22 13:47:41 +09007276 }
7277
Chalard Jean9589e722019-11-19 19:03:53 +09007278 private void updateInterfaces(final @Nullable LinkProperties newLp,
7279 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007280 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09007281 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fa7d9e2017-08-22 16:35:52 +01007282 oldLp != null ? oldLp.getAllInterfaceNames() : null,
7283 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jean9589e722019-11-19 19:03:53 +09007284 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007285 for (final String iface : interfaceDiff.added) {
7286 try {
7287 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007288 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09007289 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007290 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7291 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007292 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007293 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007294 }
Paul Jensenbff73492014-04-28 10:33:11 -04007295 }
7296 }
Chalard Jean9589e722019-11-19 19:03:53 +09007297 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007298 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007299 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007300 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007301 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007302 } catch (Exception e) {
7303 loge("Exception removing interface: " + e);
7304 }
7305 }
7306 }
7307
Tyler Weare4314862019-12-05 14:55:30 -08007308 // TODO: move to frameworks/libs/net.
7309 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7310 final String nextHop;
7311
7312 switch (route.getType()) {
7313 case RouteInfo.RTN_UNICAST:
7314 if (route.hasGateway()) {
7315 nextHop = route.getGateway().getHostAddress();
7316 } else {
7317 nextHop = INetd.NEXTHOP_NONE;
7318 }
7319 break;
7320 case RouteInfo.RTN_UNREACHABLE:
7321 nextHop = INetd.NEXTHOP_UNREACHABLE;
7322 break;
7323 case RouteInfo.RTN_THROW:
7324 nextHop = INetd.NEXTHOP_THROW;
7325 break;
7326 default:
7327 nextHop = INetd.NEXTHOP_NONE;
7328 break;
7329 }
7330
7331 final RouteInfoParcel rip = new RouteInfoParcel();
7332 rip.ifName = route.getInterface();
7333 rip.destination = route.getDestination().toString();
7334 rip.nextHop = nextHop;
7335 rip.mtu = route.getMtu();
7336
7337 return rip;
7338 }
7339
Paul Jensene0fd4a82014-08-06 15:51:33 -04007340 /**
7341 * Have netd update routes from oldLp to newLp.
7342 * @return true if routes changed between oldLp and newLp
7343 */
7344 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007345 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007346 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7347 new CompareOrUpdateResult<>(
7348 oldLp != null ? oldLp.getAllRoutes() : null,
7349 newLp != null ? newLp.getAllRoutes() : null,
7350 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007351
7352 // add routes before removing old in case it helps with continuous connectivity
7353
Chalard Jean9dd11612018-06-04 16:52:49 +09007354 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007355 for (RouteInfo route : routeDiff.added) {
7356 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007357 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007358 try {
Tyler Weare4314862019-12-05 14:55:30 -08007359 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007360 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007361 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007362 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007363 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007364 }
7365 }
7366 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007367 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007368 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007369 try {
Tyler Weare4314862019-12-05 14:55:30 -08007370 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007371 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007372 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007373 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007374 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007375 }
7376 }
7377
7378 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007379 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007380 try {
Tyler Weare4314862019-12-05 14:55:30 -08007381 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007382 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007383 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007384 }
7385 }
Tyler Weare4314862019-12-05 14:55:30 -08007386
7387 for (RouteInfo route : routeDiff.updated) {
7388 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7389 try {
7390 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7391 } catch (Exception e) {
7392 loge("Exception in networkUpdateRouteParcel: " + e);
7393 }
7394 }
7395 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7396 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007397 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007398
Erik Klineb9888902016-04-05 13:30:49 +09007399 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7400 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7401 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007402 }
Erik Klineb9888902016-04-05 13:30:49 +09007403
Erik Kline31b4a9e2018-01-11 21:07:29 +09007404 if (DBG) {
7405 final Collection<InetAddress> dnses = newLp.getDnsServers();
7406 log("Setting DNS servers for network " + netId + " to " + dnses);
7407 }
Erik Klineb9888902016-04-05 13:30:49 +09007408 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007409 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007410 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007411 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007412 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007413 }
Erik Kline54e35c02017-04-07 15:29:29 +09007414 }
7415
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007416 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7417 NetworkAgentInfo nai) {
7418 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
7419 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
7420 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
7421 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
7422
7423 if (!wasFiltering && !needsFiltering) {
7424 // Nothing to do.
7425 return;
7426 }
7427
7428 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7429 // Nothing changed.
7430 return;
7431 }
7432
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007433 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Qingxi Libb8da982020-01-17 17:54:27 -08007434 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007435 // TODO: this create a window of opportunity for apps to receive traffic between the time
7436 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007437 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007438 // old rules are being removed.
7439 if (wasFiltering) {
7440 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7441 }
7442 if (needsFiltering) {
7443 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7444 }
7445 }
7446
Valentin Iftime9fa35092019-09-24 13:32:13 +02007447 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007448 if (mWolSupportedInterfaces == null) {
7449 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007450 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007451 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007452 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7453 }
7454
Luke Huangb913c812018-08-24 20:33:16 +08007455 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007456 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007457 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007458 }
7459 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007460 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007461 }
Luke Huangb913c812018-08-24 20:33:16 +08007462 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007463 }
7464
Chalard Jean62edfd82019-12-02 18:39:29 +09007465 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7466 @NonNull final NetworkCapabilities newNc) {
7467 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7468 final int newPermission = getNetworkPermission(newNc);
7469 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7470 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007471 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08007472 } catch (RemoteException | ServiceSpecificException e) {
7473 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09007474 }
7475 }
7476 }
7477
Paul Jensen53f08952015-06-16 14:27:36 -04007478 /**
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007479 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7480 * Stores into |nai| any data coming from the agent that might also be written to the network's
7481 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7482 * agent is not lost when updateCapabilities is called.
7483 */
7484 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
Chalard Jean15228572022-01-28 19:29:12 +09007485 if (nc.hasConnectivityManagedCapability()) {
7486 Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
7487 }
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007488 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7489 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7490 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7491 // the owner UID here and behave as if the agent had never tried to change it.
Lorenzo Colitti93401342020-12-09 18:30:52 +09007492 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7493 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7494 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7495 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7496 }
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007497 nai.declaredCapabilities = new NetworkCapabilities(nc);
Chalard Jean15228572022-01-28 19:29:12 +09007498 NetworkAgentInfo.restrictCapabilitiesFromNetworkAgent(nc, nai.creatorUid);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007499 }
7500
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007501 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007502 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09007503 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007504 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08007505 underlyingNetworks = underlyingNetworksOrDefault(
7506 agentCaps.getOwnerUid(), underlyingNetworks);
lifrade6c2a2021-03-04 14:08:08 +08007507 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007508 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7509 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007510 // metered if any underlying is metered, or originally declared metered by the agent.
7511 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007512 boolean roaming = false; // roaming if any underlying is roaming
7513 boolean congested = false; // congested if any underlying is congested
7514 boolean suspended = true; // suspended if all underlying are suspended
7515
7516 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08007517 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007518 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08007519 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007520 for (Network underlyingNetwork : underlyingNetworks) {
7521 final NetworkAgentInfo underlying =
7522 getNetworkAgentInfoForNetwork(underlyingNetwork);
7523 if (underlying == null) continue;
7524
7525 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7526 hadUnderlyingNetworks = true;
7527 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007528 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007529 }
7530
7531 // Merge capabilities of this underlying network. For bandwidth, assume the
7532 // worst case.
7533 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7534 underlyingCaps.getLinkDownstreamBandwidthKbps());
7535 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7536 underlyingCaps.getLinkUpstreamBandwidthKbps());
7537 // If this underlying network is metered, the VPN is metered (it may cost money
7538 // to send packets on this network).
7539 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7540 // If this underlying network is roaming, the VPN is roaming (the billing structure
7541 // is different than the usual, local one).
7542 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7543 // If this underlying network is congested, the VPN is congested (the current
7544 // condition of the network affects the performance of this network).
7545 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7546 // If this network is not suspended, the VPN is not suspended (the VPN
7547 // is able to transfer some data).
7548 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08007549 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007550 }
7551 }
7552 if (!hadUnderlyingNetworks) {
7553 // No idea what the underlying networks are; assume reasonable defaults
7554 metered = true;
7555 roaming = false;
7556 congested = false;
7557 suspended = false;
7558 }
7559
lifrade6c2a2021-03-04 14:08:08 +08007560 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007561 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7562 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7563 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7564 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7565 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7566 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08007567 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007568 }
7569
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007570 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007571 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7572 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7573 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04007574 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007575 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007576 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09007577 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007578 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7579 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007580 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007581 // avoid connect/teardown loops.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007582 if (nai.everConnected &&
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007583 !nai.isVPN() &&
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007584 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7585 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09007586 // does not cause any request (that is not a listen) currently matching that agent to
7587 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007588 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09007589 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007590 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09007591 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007592 }
7593
Paul Jensen53f08952015-06-16 14:27:36 -04007594 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007595 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensende49eb12015-06-25 15:30:08 -04007596 if (nai.lastValidated) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007597 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007598 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007599 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007600 }
Paul Jensende49eb12015-06-25 15:30:08 -04007601 if (nai.lastCaptivePortalDetected) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007602 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007603 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007604 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007605 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007606 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007607 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007608 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007609 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007610 }
lucaslin2240ef62019-03-12 13:08:03 +08007611 if (nai.partialConnectivity) {
7612 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7613 } else {
7614 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7615 }
lucasline117e2e2019-10-22 18:27:33 +08007616 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007617
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007618 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09007619 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7620 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007621 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09007622 }
7623
Lorenzo Colittibd079452021-07-02 11:47:57 +09007624 if (nai.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007625 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7626 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007627 }
7628
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007629 return newNc;
7630 }
7631
Lorenzo Colitti44840702021-01-11 22:27:57 +09007632 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7633 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7634 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7635 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7636 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7637 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7638 if (prevSuspended != suspended) {
7639 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7640 // onResumed have been removed.
7641 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7642 : ConnectivityManager.CALLBACK_RESUMED);
7643 }
7644 if (prevSuspended != suspended || prevRoaming != roaming) {
7645 // updateNetworkInfo will mix in the suspended info from the capabilities and
7646 // take appropriate action for the network having possibly changed state.
7647 updateNetworkInfo(nai, nai.networkInfo);
7648 }
7649 }
7650
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007651 /**
7652 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7653 *
7654 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7655 * capabilities we manage and store in {@code nai}, such as validated status and captive
7656 * portal status)
7657 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7658 * potentially triggers rematches.
7659 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7660 * change.)
7661 *
7662 * @param oldScore score of the network before any of the changes that prompted us
7663 * to call this function.
7664 * @param nai the network having its capabilities updated.
7665 * @param nc the new network capabilities.
7666 */
Chalard Jean62edfd82019-12-02 18:39:29 +09007667 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7668 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007669 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007670 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean62edfd82019-12-02 18:39:29 +09007671 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09007672 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007673
Chalard Jeanb2a49912018-01-16 18:43:05 +09007674 updateUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09007675 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007676
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007677 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007678 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7679 // the change we're processing can't affect any requests, it can only affect the listens
7680 // on this network. We might have been called by rematchNetworkAndRequests when a
7681 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09007682 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007683 } else {
7684 // If the requestable capabilities have changed or the score changed, we can't have been
7685 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09007686 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04007687 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07007688 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09007689 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007690
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007691 final boolean oldMetered = prevNc.isMetered();
7692 final boolean newMetered = newNc.isMetered();
7693 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08007694
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007695 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00007696 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7697 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007698 }
junyulaif2c67e42018-08-07 19:50:45 +08007699
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007700 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7701 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08007702
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007703 // Report changes that are interesting for network statistics tracking.
7704 if (meteredChanged || roamingChanged) {
7705 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06007706 }
7707
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007708 // This network might have been underlying another network. Propagate its capabilities.
7709 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08007710
7711 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007712 mDnsManager.updateTransportsForNetwork(
7713 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08007714 }
lucaslin53e8a262021-06-08 01:43:59 +08007715
7716 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007717 }
7718
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007719 /** Convenience method to update the capabilities for a given network. */
7720 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7721 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7722 }
7723
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007724 /**
7725 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7726 * network.
7727 *
7728 * Ingress interface filtering enforces that all apps under the given network can only receive
7729 * packets from the network's interface (and loopback). This is important for VPNs because
7730 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7731 * non-VPN interfaces.
7732 *
7733 * As a result, this method should return true iff
7734 * 1. the network is an app VPN (not legacy VPN)
7735 * 2. the VPN does not allow bypass
7736 * 3. the VPN is fully-routed
7737 * 4. the VPN interface is non-null
7738 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007739 * @see INetd#firewallAddUidInterfaceRules
7740 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007741 */
7742 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7743 LinkProperties lp) {
7744 if (nc == null || lp == null) return false;
7745 return nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007746 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08007747 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007748 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08007749 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7750 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007751 }
7752
Chiachang Wang28afaff2020-12-10 22:24:47 +08007753 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7754 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7755 int index = 0;
7756 for (UidRange range : ranges) {
7757 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7758 index++;
7759 }
7760 return stableRanges;
7761 }
7762
Chalard Jeane6c95272022-01-25 21:04:21 +09007763 private static UidRangeParcel[] intsToUidRangeStableParcels(
7764 final @NonNull ArraySet<Integer> uids) {
7765 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
7766 int index = 0;
7767 for (int uid : uids) {
7768 stableRanges[index] = new UidRangeParcel(uid, uid);
7769 index++;
7770 }
7771 return stableRanges;
7772 }
7773
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007774 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7775 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7776 for (int i = 0; i < ranges.length; i++) {
7777 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7778 }
7779 return stableRanges;
7780 }
7781
Ken Chen5e65a852020-12-24 12:59:10 +08007782 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7783 int[] exemptUids) {
7784 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7785 try {
7786 mNetd.socketDestroy(ranges, exemptUids);
7787 } catch (Exception e) {
7788 loge("Exception in socket destroy: ", e);
7789 }
7790 }
7791 }
7792
paulhuaa0743d2021-05-26 21:56:03 +08007793 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08007794 int[] exemptUids = new int[2];
7795 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7796 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7797 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7798 exemptUids[0] = VPN_UID;
7799 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7800 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7801
7802 maybeCloseSockets(nai, ranges, exemptUids);
7803 try {
7804 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08007805 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007806 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08007807 } else {
paulhu0e79d952021-06-09 16:11:35 +08007808 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007809 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08007810 }
7811 } catch (Exception e) {
7812 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7813 " on netId " + nai.network.netId + ". " + e);
7814 }
7815 maybeCloseSockets(nai, ranges, exemptUids);
7816 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007817
lucaslin53e8a262021-06-08 01:43:59 +08007818 private boolean isProxySetOnAnyDefaultNetwork() {
7819 ensureRunningOnConnectivityServiceThread();
7820 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7821 final NetworkAgentInfo nai = nri.getSatisfier();
7822 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
7823 return true;
7824 }
7825 }
7826 return false;
7827 }
7828
7829 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7830 NetworkCapabilities newNc) {
7831 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
7832 // the proxy might be changed since the default network satisfied by the apps might also
7833 // changed.
7834 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
7835 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09007836 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
7837 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
7838 if (nai.isVPN() && nai.everConnected && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08007839 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
7840 mProxyTracker.sendProxyBroadcast();
7841 }
7842 }
7843
Chalard Jeane6c95272022-01-25 21:04:21 +09007844 private void updateUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
7845 @Nullable NetworkCapabilities newNc) {
7846 updateVpnUids(nai, prevNc, newNc);
7847 updateAccessUids(nai, prevNc, newNc);
7848 }
7849
7850 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
7851 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007852 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7853 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007854 if (null == prevRanges) prevRanges = new ArraySet<>();
7855 if (null == newRanges) newRanges = new ArraySet<>();
7856 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
7857
7858 prevRanges.removeAll(newRanges);
7859 newRanges.removeAll(prevRangesCopy);
7860
7861 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007862 // When updating the VPN uid routing rules, add the new range first then remove the old
7863 // range. If old range were removed first, there would be a window between the old
7864 // range being removed and the new range being added, during which UIDs contained
7865 // in both ranges are not subject to any VPN routing rules. Adding new range before
7866 // removing old range works because, unlike the filtering rules below, it's possible to
7867 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08007868 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
7869 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
7870 // [1-5] & [1-2],[4-5] == [3]
7871 // Then we can do:
7872 // maybeCloseSockets([3])
7873 // mNetd.networkAddUidRanges([1-2],[4-5])
7874 // mNetd.networkRemoveUidRanges([1-5])
7875 // maybeCloseSockets([3])
7876 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
7877 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09007878 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08007879 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007880 }
7881 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08007882 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007883 }
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007884 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
7885 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
7886 final String iface = nai.linkProperties.getInterfaceName();
7887 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09007888 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007889 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
7890 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
7891 // were added first and then newRanges got removed later, there would be only one uid
7892 // 10013 left. A consequence of removing old ranges before adding new ranges is that
7893 // there is now a window of opportunity when the UIDs are not subject to any filtering.
7894 // Note that this is in contrast with the (more robust) update of VPN routing rules
7895 // above, where the addition of new ranges happens before the removal of old ranges.
7896 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
7897 // to be removed will never overlap with the new range to be added.
7898 if (wasFiltering && !prevRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08007899 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007900 }
7901 if (shouldFilter && !newRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08007902 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007903 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09007904 } catch (Exception e) {
7905 // Never crash!
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007906 loge("Exception in updateUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007907 }
7908 }
7909
Chalard Jeane6c95272022-01-25 21:04:21 +09007910 private void updateAccessUids(@NonNull NetworkAgentInfo nai,
7911 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
7912 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
7913 final boolean prevEmpty = null == prevNc || prevNc.getAccessUidsNoCopy().isEmpty();
7914 final boolean newEmpty = null == newNc || newNc.getAccessUidsNoCopy().isEmpty();
7915 if (prevEmpty && newEmpty) return;
7916
7917 final ArraySet<Integer> prevUids =
7918 null == prevNc ? new ArraySet<>() : prevNc.getAccessUidsNoCopy();
7919 final ArraySet<Integer> newUids =
7920 null == newNc ? new ArraySet<>() : newNc.getAccessUidsNoCopy();
7921
7922 if (prevUids.equals(newUids)) return;
7923
7924 // This implementation is very simple and vastly faster for sets of Integers than
7925 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
7926 // a key computed from the value and has storage for that.
7927 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
7928 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
7929 toRemove.removeAll(newUids);
7930 toAdd.removeAll(prevUids);
7931
7932 try {
7933 if (!toAdd.isEmpty()) {
7934 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
7935 nai.network.netId,
7936 intsToUidRangeStableParcels(toAdd),
7937 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
7938 }
7939 if (!toRemove.isEmpty()) {
7940 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
7941 nai.network.netId,
7942 intsToUidRangeStableParcels(toRemove),
7943 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
7944 }
7945 } catch (RemoteException e) {
7946 // Netd died. This usually causes a runtime restart anyway.
7947 }
7948 }
7949
Hugo Benichi9d35b752017-09-01 01:23:32 +00007950 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09007951 ensureRunningOnConnectivityServiceThread();
7952
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007953 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00007954 // Ignore updates for disconnected networks
7955 return;
7956 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007957 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09007958 log("Update of LinkProperties for " + nai.toShortString()
7959 + "; created=" + nai.created
7960 + "; everConnected=" + nai.everConnected);
Hugo Benichi9d35b752017-09-01 01:23:32 +00007961 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007962 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
7963 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08007964 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00007965 }
7966
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007967 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
7968 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007969 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007970 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08007971 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08007972 // If apps could file multi-layer requests with PendingIntents, they'd need to know
7973 // which of the layer is satisfied alongside with some ID for the request. Hence, if
7974 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09007975 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
7976 // need to be sent as a separate extra.
7977 final NetworkRequest req = nri.isMultilayerRequest()
7978 ? nri.getActiveRequest()
7979 // Non-multilayer listen requests do not have an active request
7980 : nri.mRequests.get(0);
7981 if (req == null) {
7982 Log.wtf(TAG, "No request in NRI " + nri);
7983 }
7984 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007985 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007986 sendIntent(nri.mPendingIntent, intent);
7987 }
7988 // else not handled
7989 }
7990
7991 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
7992 mPendingIntentWakeLock.acquire();
7993 try {
7994 if (DBG) log("Sending " + pendingIntent);
7995 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
7996 } catch (PendingIntent.CanceledException e) {
7997 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
7998 mPendingIntentWakeLock.release();
7999 releasePendingNetworkRequest(pendingIntent);
8000 }
8001 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8002 }
8003
8004 @Override
8005 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8006 String resultData, Bundle resultExtras) {
8007 if (DBG) log("Finished sending " + pendingIntent);
8008 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008009 // Release with a delay so the receiving client has an opportunity to put in its
8010 // own request.
8011 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008012 }
8013
James Mattis212df9e2020-12-03 19:57:41 -08008014 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
8015 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
8016 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008017 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008018 // Default request has no msgr. Also prevents callbacks from being invoked for
8019 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8020 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8021 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008022 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008023 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008024 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008025 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008026 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008027 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008028 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008029 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8030 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008031 }
Roshan Pius951c0032020-12-22 15:10:42 -08008032 final boolean includeLocationSensitiveInfo =
8033 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008034 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008035 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008036 final NetworkCapabilities nc =
8037 networkCapabilitiesRestrictedForCallerPermissions(
8038 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8039 putParcelable(
8040 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008041 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008042 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008043 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008044 nri.mCallingAttributionTag));
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008045 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8046 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008047 // For this notification, arg1 contains the blocked status.
8048 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008049 break;
8050 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008051 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008052 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008053 break;
8054 }
8055 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008056 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008057 final NetworkCapabilities netCap =
8058 networkCapabilitiesRestrictedForCallerPermissions(
8059 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8060 putParcelable(
8061 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008062 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008063 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008064 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008065 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008066 break;
8067 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008068 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008069 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8070 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008071 break;
8072 }
junyulaif2c67e42018-08-07 19:50:45 +08008073 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008074 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008075 msg.arg1 = arg1;
8076 break;
8077 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008078 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008079 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008080 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008081 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008082 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008083 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008084 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008085 }
James Mattis45d81842021-01-10 14:24:24 -08008086 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008087 } catch (RemoteException e) {
8088 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008089 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008090 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008091 }
8092
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008093 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8094 bundle.putParcelable(t.getClass().getSimpleName(), t);
8095 }
8096
Chalard Jean0702f982021-09-16 21:50:07 +09008097 /**
8098 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8099 *
8100 * When a request should be assigned to a new network, it is normally lingered to give
8101 * time for apps to gracefully migrate their connections. When both networks are on the same
8102 * radio, but that radio can't do time-sharing efficiently, this may end up being
8103 * counter-productive because any traffic on the old network may drastically reduce the
8104 * performance of the new network.
8105 * The stack supports a configuration to let modem vendors state that their radio can't
8106 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8107 * from one cell network to another can't be done gracefully.
8108 *
8109 * @param oldNai the old network serving the request
8110 * @param newNai the new network serving the request
8111 * @return whether the switch can be graceful
8112 */
8113 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8114 @NonNull final NetworkAgentInfo newSatisfier) {
8115 if (mCellularRadioTimesharingCapable) return true;
8116 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8117 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8118 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8119 }
8120
Paul Jensenaf94b982014-09-30 15:37:41 -04008121 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008122 if (nai.numRequestNetworkRequests() != 0) {
8123 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8124 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008125 // Ignore listening and track default requests.
8126 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008127 loge("Dead network still had at least " + nr);
8128 break;
8129 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008130 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008131 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008132 }
8133
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008134 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8135 if (oldNetwork == null) {
8136 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8137 return;
8138 }
Chalard Jean49707572019-12-10 21:07:02 +09008139 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008140
8141 // If we get here it means that the last linger timeout for this network expired. So there
8142 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008143 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008144
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008145 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008146 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008147 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008148 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008149 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008150 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008151 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008152 }
8153
James Mattise3ef1912020-12-20 11:09:58 -08008154 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8155 boolean isDefaultChanged = false;
8156 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8157 final NetworkReassignment.RequestReassignment reassignment =
8158 changes.getReassignment(defaultRequestInfo);
8159 if (null == reassignment) {
8160 continue;
8161 }
8162 // reassignment only contains those instances where the satisfying network changed.
8163 isDefaultChanged = true;
8164 // Notify system services of the new default.
8165 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8166 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008167
James Mattise3ef1912020-12-20 11:09:58 -08008168 if (isDefaultChanged) {
8169 // Hold a wakelock for a short time to help apps in migrating to a new default.
8170 scheduleReleaseNetworkTransitionWakelock();
8171 }
8172 }
8173
8174 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8175 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8176 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8177 if (DBG) {
8178 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8179 }
Chalard Jean8e382112019-12-03 20:45:30 +09008180
James Mattisd31bdfa2020-12-23 16:37:26 -08008181 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8182 if (newDefaultNetwork != null) {
8183 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008184 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008185
James Mattisd31bdfa2020-12-23 16:37:26 -08008186 // Set an app level managed default and return since further processing only applies to the
8187 // default network.
8188 if (mDefaultRequest != nri) {
8189 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8190 return;
8191 }
8192
8193 makeDefaultNetwork(newDefaultNetwork);
8194
James Mattise3ef1912020-12-20 11:09:58 -08008195 if (oldDefaultNetwork != null) {
8196 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8197 }
8198 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008199 handleApplyDefaultProxy(null != newDefaultNetwork
8200 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8201 updateTcpBufferSizes(null != newDefaultNetwork
8202 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008203 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008204 }
8205
James Mattisd31bdfa2020-12-23 16:37:26 -08008206 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8207 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8208 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8209 try {
8210 if (VDBG) {
8211 log("Setting default network for " + nri
8212 + " using UIDs " + nri.getUids()
8213 + " with old network " + (oldDefaultNetwork != null
8214 ? oldDefaultNetwork.network().getNetId() : "null")
8215 + " and new network " + (newDefaultNetwork != null
8216 ? newDefaultNetwork.network().getNetId() : "null"));
8217 }
8218 if (nri.getUids().isEmpty()) {
8219 throw new IllegalStateException("makeDefaultForApps called without specifying"
8220 + " any applications to set as the default." + nri);
8221 }
8222 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008223 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008224 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008225 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008226 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008227 }
8228 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008229 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008230 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008231 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008232 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008233 }
8234 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008235 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008236 }
8237 }
8238
8239 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8240 try {
8241 if (null != newDefaultNetwork) {
8242 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8243 } else {
8244 mNetd.networkClearDefault();
8245 }
8246 } catch (RemoteException | ServiceSpecificException e) {
8247 loge("Exception setting default network :" + e);
8248 }
8249 }
8250
Chalard Jean05cbe972019-12-09 11:50:38 +09008251 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008252 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09008253 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09008254 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09008255 processNewlySatisfiedListenRequests(nai);
8256 }
8257
8258 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008259 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8260 if (nri.isMultilayerRequest()) {
8261 continue;
8262 }
8263 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008264 if (!nr.isListen()) continue;
8265 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08008266 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008267 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
8268 }
8269 }
Chalard Jeancd397a22019-11-22 22:33:33 +09008270 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008271
Chalard Jeancd397a22019-11-22 22:33:33 +09008272 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008273 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8274 if (nri.isMultilayerRequest()) {
8275 continue;
8276 }
8277 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008278 if (!nr.isListen()) continue;
8279 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
8280 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09008281 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008282 }
8283 }
8284 }
8285
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008286 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008287 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008288 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08008289 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09008290 @Nullable public final NetworkRequest mOldNetworkRequest;
8291 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008292 @Nullable public final NetworkAgentInfo mOldNetwork;
8293 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08008294 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008295 @Nullable final NetworkRequest oldNetworkRequest,
8296 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008297 @Nullable final NetworkAgentInfo oldNetwork,
8298 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008299 mNetworkRequestInfo = networkRequestInfo;
8300 mOldNetworkRequest = oldNetworkRequest;
8301 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008302 mOldNetwork = oldNetwork;
8303 mNewNetwork = newNetwork;
8304 }
Chalard Jean49707572019-12-10 21:07:02 +09008305
8306 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09008307 final NetworkRequest requestToShow = null != mNewNetworkRequest
8308 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
8309 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08008310 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
8311 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09008312 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008313 }
8314
Chalard Jean46a62372019-12-10 21:25:24 +09008315 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008316
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008317 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09008318 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008319 }
8320
8321 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09008322 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09008323 // The code is never supposed to add two reassignments of the same request. Make
8324 // sure this stays true, but without imposing this expensive check on all
8325 // reassignments on all user devices.
8326 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08008327 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09008328 throw new IllegalStateException("Trying to reassign ["
8329 + reassignment + "] but already have ["
8330 + existing + "]");
8331 }
8332 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09008333 }
Chalard Jean46a62372019-12-10 21:25:24 +09008334 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008335 }
8336
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008337 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09008338 // the passed request.
8339 @Nullable
8340 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008341 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008342 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008343 }
8344 return null;
8345 }
Chalard Jean49707572019-12-10 21:07:02 +09008346
8347 public String toString() {
8348 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8349 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09008350 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008351 for (final RequestReassignment rr : getRequestReassignments()) {
8352 sj.add(rr.toString());
8353 }
8354 return sj.toString();
8355 }
8356
8357 public String debugString() {
8358 final StringBuilder sb = new StringBuilder();
8359 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09008360 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008361 for (final RequestReassignment rr : getRequestReassignments()) {
8362 sb.append("\n ").append(rr);
8363 }
8364 return sb.append("\n").toString();
8365 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008366 }
8367
Chalard Jean24344d72019-12-04 13:32:31 +09008368 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008369 @Nullable final NetworkRequest previousRequest,
8370 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09008371 @Nullable final NetworkAgentInfo previousSatisfier,
8372 @Nullable final NetworkAgentInfo newSatisfier,
8373 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08008374 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09008375 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09008376 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008377 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008378 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09008379 }
James Mattisa076c532020-12-02 14:12:41 -08008380 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean0702f982021-09-16 21:50:07 +09008381 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)) {
8382 // If this network switch can't be supported gracefully, the request is not
8383 // lingered. This allows letting go of the network sooner to reclaim some
8384 // performance on the new network, since the radio can't do both at the same
8385 // time while preserving good performance.
8386 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8387 }
Chalard Jean24344d72019-12-04 13:32:31 +09008388 } else {
8389 if (VDBG || DDBG) log(" accepting network in place of null");
8390 }
junyulai0ac374f2020-12-14 18:41:52 +08008391
8392 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8393 // and immediately satisfies a request then remove the timer. This will happen for
8394 // all networks except in the case of an underlying network for a VCN.
8395 if (newSatisfier.isNascent()) {
8396 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08008397 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008398 }
8399
Chalard Jean5d6e23b2021-03-01 22:00:20 +09008400 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08008401 newSatisfier.unlingerRequest(newRequest.requestId);
8402 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008403 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08008404 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008405 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09008406 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008407 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008408 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08008409 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008410 }
James Mattisa076c532020-12-02 14:12:41 -08008411 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008412 }
James Mattisa076c532020-12-02 14:12:41 -08008413 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008414 }
8415
James Mattisa076c532020-12-02 14:12:41 -08008416 /**
8417 * This function is triggered when something can affect what network should satisfy what
8418 * request, and it computes the network reassignment from the passed collection of requests to
8419 * network match to the one that the system should now have. That data is encoded in an
8420 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8421 * satisfier.
8422 *
8423 * After the reassignment is computed, it is applied to the state objects.
8424 *
8425 * @param networkRequests the nri objects to evaluate for possible network reassignment
8426 * @return NetworkReassignment listing of proposed network assignment changes
8427 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008428 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08008429 private NetworkReassignment computeNetworkReassignment(
8430 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09008431 final NetworkReassignment changes = new NetworkReassignment();
8432
Chalard Jeanc81d4c32021-04-07 17:06:19 +09008433 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09008434 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008435 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattisa076c532020-12-02 14:12:41 -08008436 if (!nai.everConnected) {
8437 continue;
8438 }
Chalard Jean857a1712019-12-10 21:08:07 +09008439 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09008440 }
Chalard Jean857a1712019-12-10 21:08:07 +09008441
James Mattisa076c532020-12-02 14:12:41 -08008442 for (final NetworkRequestInfo nri : networkRequests) {
8443 // Non-multilayer listen requests can be ignored.
8444 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8445 continue;
8446 }
8447 NetworkAgentInfo bestNetwork = null;
8448 NetworkRequest bestRequest = null;
8449 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09008450 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08008451 // Stop evaluating as the highest possible priority request is satisfied.
8452 if (null != bestNetwork) {
8453 bestRequest = req;
8454 break;
8455 }
8456 }
James Mattisd31bdfa2020-12-23 16:37:26 -08008457 if (null == bestNetwork && isDefaultBlocked(nri)) {
8458 // Remove default networking if disallowed for managed default requests.
8459 bestNetwork = mNoServiceNetwork;
8460 }
8461 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09008462 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09008463 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08008464 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09008465 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008466 }
8467 return changes;
8468 }
8469
James Mattisa076c532020-12-02 14:12:41 -08008470 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8471 return new HashSet<>(mNetworkRequests.values());
8472 }
8473
Paul Jensenc88b39b2015-06-16 14:27:36 -04008474 /**
James Mattisa076c532020-12-02 14:12:41 -08008475 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04008476 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04008477 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008478 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08008479 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8480 }
8481
8482 /**
8483 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8484 * being disconnected.
8485 */
8486 private void rematchNetworksAndRequests(
8487 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8488 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09008489 // TODO: This may be slow, and should be optimized.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008490 final long now = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08008491 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jean49707572019-12-10 21:07:02 +09008492 if (VDBG || DDBG) {
8493 log(changes.debugString());
8494 } else if (DBG) {
8495 log(changes.toString()); // Shorter form, only one line of log
8496 }
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008497 applyNetworkReassignment(changes, now);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008498 issueNetworkNeeds();
Chalard Jeand7f762d2019-12-10 19:01:29 +09008499 }
Chalard Jean64520dc2019-12-04 19:55:32 +09008500
Chalard Jeand7f762d2019-12-10 19:01:29 +09008501 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008502 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008503 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09008504
8505 // Since most of the time there are only 0 or 1 background networks, it would probably
8506 // be more efficient to just use an ArrayList here. TODO : measure performance
8507 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8508 for (final NetworkAgentInfo nai : nais) {
8509 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8510 }
8511
Chalard Jeand7f762d2019-12-10 19:01:29 +09008512 // First, update the lists of satisfied requests in the network agents. This is necessary
8513 // because some code later depends on this state to be correct, most prominently computing
8514 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09008515 for (final NetworkReassignment.RequestReassignment event :
8516 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008517 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8518 event.mOldNetworkRequest, event.mNewNetworkRequest,
8519 event.mOldNetwork, event.mNewNetwork,
8520 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09008521 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008522
James Mattise3ef1912020-12-20 11:09:58 -08008523 // Process default network changes if applicable.
8524 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008525
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008526 // Notify requested networks are available after the default net is switched, but
8527 // before LegacyTypeTracker sends legacy broadcasts
8528 for (final NetworkReassignment.RequestReassignment event :
8529 changes.getRequestReassignments()) {
8530 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008531 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008532 } else {
James Mattisa076c532020-12-02 14:12:41 -08008533 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008534 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008535 }
8536 }
8537
junyulai0ac374f2020-12-14 18:41:52 +08008538 // Update the inactivity state before processing listen callbacks, because the background
8539 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008540 // just yet though, because they have to be sent after the listens are processed to keep
8541 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08008542 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09008543 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08008544 // Rematching may have altered the inactivity state of some networks, so update all
8545 // inactivity timers. updateInactivityState reads the state from the network agent
8546 // and does nothing if the state has not changed : the source of truth is controlled
8547 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8548 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08008549 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08008550 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008551 }
8552 }
8553
Chalard Jeanb10ab412019-12-11 14:12:30 +09008554 for (final NetworkAgentInfo nai : nais) {
8555 if (!nai.everConnected) continue;
8556 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008557 // Process listen requests and update capabilities if the background state has
8558 // changed for this network. For consistency with previous behavior, send onLost
8559 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09008560 processNewlyLostListenRequests(nai);
8561 if (oldBackground != nai.isBackgroundNetwork()) {
8562 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008563 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09008564 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008565 }
8566
junyulai0ac374f2020-12-14 18:41:52 +08008567 for (final NetworkAgentInfo nai : inactiveNetworks) {
8568 // For nascent networks, if connecting with no foreground request, skip broadcasting
8569 // LOSING for backward compatibility. This is typical when mobile data connected while
8570 // wifi connected with mobile data always-on enabled.
8571 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008572 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008573 }
8574
James Mattise3ef1912020-12-20 11:09:58 -08008575 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09008576
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008577 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008578 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008579 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08008580 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008581 // This network has active linger timers and no requests, but is not
8582 // lingering. Linger it.
8583 //
8584 // One way (the only way?) this can happen if this network is unvalidated
8585 // and became unneeded due to another network improving its score to the
8586 // point where this network will no longer be able to satisfy any requests
8587 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08008588 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008589 notifyNetworkLosing(nai, now);
8590 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09008591 } else {
Chalard Jean49707572019-12-10 21:07:02 +09008592 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09008593 teardownUnneededNetwork(nai);
8594 }
8595 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04008596 }
8597 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008598
Chalard Jean62edfd82019-12-02 18:39:29 +09008599 /**
8600 * Apply a change in background state resulting from rematching networks with requests.
8601 *
8602 * During rematch, a network may change background states by starting to satisfy or stopping
8603 * to satisfy a foreground request. Listens don't count for this. When a network changes
8604 * background states, its capabilities need to be updated and callbacks fired for the
8605 * capability change.
8606 *
8607 * @param nai The network that changed background states
8608 */
8609 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8610 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8611 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8612 updateNetworkPermissions(nai, newNc);
8613 nai.getAndSetNetworkCapabilities(newNc);
8614 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8615 }
8616
Chalard Jeanf0344532019-11-19 19:23:38 +09008617 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08008618 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008619 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09008620 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8621 changes.getReassignment(mDefaultRequest);
8622 final NetworkAgentInfo oldDefaultNetwork =
8623 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8624 final NetworkAgentInfo newDefaultNetwork =
8625 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08008626
Chalard Jean5b409c72021-02-04 13:12:59 +09008627 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008628 // Maintain the illusion : since the legacy API only understands one network at a time,
8629 // if the default network changed, apps should see a disconnected broadcast for the
8630 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09008631 if (oldDefaultNetwork != null) {
8632 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8633 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008634 }
Chalard Jean5b409c72021-02-04 13:12:59 +09008635 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008636 // The new default network can be newly null if and only if the old default
8637 // network doesn't satisfy the default request any more because it lost a
8638 // capability.
Chalard Jean5b409c72021-02-04 13:12:59 +09008639 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08008640 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09008641 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008642 }
8643 }
8644
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008645 // Now that all the callbacks have been sent, send the legacy network broadcasts
8646 // as needed. This is necessary so that legacy requests correctly bind dns
8647 // requests to this network. The legacy users are listening for this broadcast
8648 // and will generally do a dns request so they can ensureRouteToHost and if
8649 // they do that before the callbacks happen they'll use the default network.
8650 //
8651 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8652 // callbacks, but if apps can receive the broadcast before the callback, they still might
8653 // have an inconsistent view of networking.
8654 //
8655 // This *does* introduce a race where if the user uses the new api
8656 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8657 // they may get old info. Reverse this after the old startUsing api is removed.
8658 // This is on top of the multiple intent sequencing referenced in the todo above.
8659 for (NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008660 if (nai.everConnected) {
8661 addNetworkToLegacyTypeTracker(nai);
8662 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08008663 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008664 }
8665
Chalard Jean0354d8c2021-01-12 10:58:56 +09008666 private void issueNetworkNeeds() {
8667 ensureRunningOnConnectivityServiceThread();
8668 for (final NetworkOfferInfo noi : mNetworkOffers) {
8669 issueNetworkNeeds(noi);
8670 }
8671 }
8672
8673 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8674 ensureRunningOnConnectivityServiceThread();
8675 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8676 informOffer(nri, noi.offer, mNetworkRanker);
8677 }
8678 }
8679
8680 /**
8681 * Inform a NetworkOffer about any new situation of a request.
8682 *
8683 * This function handles updates to offers. A number of events may happen that require
8684 * updating the registrant for this offer about the situation :
8685 * • The offer itself was updated. This may lead the offer to no longer being able
8686 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8687 * or conversely being strengthened enough to beat the satisfier (and therefore
8688 * start being needed)
8689 * • The network satisfying a request changed (including cases where the request
8690 * starts or stops being satisfied). The new network may be a stronger or weaker
8691 * match than the old one, possibly affecting whether the offer is needed.
8692 * • The network satisfying a request updated their score. This may lead the offer
8693 * to no longer be able to beat it if the current satisfier got better, or
8694 * conversely start being a good choice if the current satisfier got weaker.
8695 *
8696 * @param nri The request
8697 * @param offer The offer. This may be an updated offer.
8698 */
8699 private static void informOffer(@NonNull NetworkRequestInfo nri,
8700 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
8701 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
8702 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09008703
8704 // Multi-layer requests have a currently active request, the one being satisfied.
8705 // Since the system will try to bring up a better network than is currently satisfying
8706 // the request, NetworkProviders need to be told the offers matching the requests *above*
8707 // the currently satisfied one are needed, that the ones *below* the satisfied one are
8708 // not needed, and the offer is needed for the active request iff the offer can beat
8709 // the satisfier.
8710 // For non-multilayer requests, the logic above gracefully degenerates to only the
8711 // last case.
8712 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
8713 // providers that the offer is needed for this request, until the active request is found.
8714 // In a second phase, deal with the currently active request. In a third phase, inform
8715 // the providers that offer is unneeded for the remaining requests.
8716
8717 // First phase : inform providers of all requests above the active request.
8718 int i;
8719 for (i = 0; nri.mRequests.size() > i; ++i) {
8720 final NetworkRequest request = nri.mRequests.get(i);
8721 if (activeRequest == request) break; // Found the active request : go to phase 2
8722 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8723 // Since this request is higher-priority than the one currently satisfied, if the
8724 // offer can satisfy it, the provider should try and bring up the network for sure ;
8725 // no need to even ask the ranker – an offer that can satisfy is always better than
8726 // no network. Hence tell the provider so unless it already knew.
8727 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
8728 offer.onNetworkNeeded(request);
8729 }
8730 }
8731
8732 // Second phase : deal with the active request (if any)
8733 if (null != activeRequest && activeRequest.isRequest()) {
8734 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00008735 // If an offer can satisfy the request, it is considered needed if it is currently
8736 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09008737 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00008738 && satisfier.factorySerialNumber == offer.providerId
8739 && activeRequest.canBeSatisfiedBy(offer.caps);
8740 final boolean newNeeded = currentlyServing
8741 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008742 if (newNeeded != oldNeeded) {
8743 if (newNeeded) {
8744 offer.onNetworkNeeded(activeRequest);
8745 } else {
8746 // The offer used to be able to beat the satisfier. Now it can't.
8747 offer.onNetworkUnneeded(activeRequest);
8748 }
8749 }
8750 }
8751
8752 // Third phase : inform the providers that the offer isn't needed for any request
8753 // below the active one.
8754 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
8755 final NetworkRequest request = nri.mRequests.get(i);
8756 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8757 // Since this request is lower-priority than the one currently satisfied, if the
8758 // offer can satisfy it, the provider should not try and bring up the network.
8759 // Hence tell the provider so unless it already knew.
8760 if (offer.neededFor(request)) {
8761 offer.onNetworkUnneeded(request);
8762 }
8763 }
8764 }
8765
Chalard Jean61c79252019-11-07 23:07:32 +09008766 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8767 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8768 NetworkRequest nr = nai.requestAt(i);
8769 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8770 // legacy type tracker filters out repeat adds
8771 mLegacyTypeTracker.add(nr.legacyType, nai);
8772 }
8773 }
8774
8775 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09008776 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09008777 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8778 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8779 if (nai.isVPN()) {
8780 mLegacyTypeTracker.add(TYPE_VPN, nai);
8781 }
8782 }
8783
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008784 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04008785 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittia8de5ca2014-12-17 11:14:42 +09008786 if (!nai.everValidated) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09008787 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04008788 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09008789 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008790
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008791 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008792 // Don't repeat publish.
8793 if (newInetCondition == mDefaultInetConditionPublished) return;
8794
8795 mDefaultInetConditionPublished = newInetCondition;
8796 sendInetConditionBroadcast(nai.networkInfo);
8797 }
8798
Chalard Jeand61375d2020-01-14 22:46:36 +09008799 @NonNull
8800 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8801 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008802 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09008803 final boolean suspended =
8804 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8805 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8806 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8807 // state. This is because the network could have been suspended before connecting,
8808 // or it could be disconnecting while being suspended, and in both these cases
8809 // the state should not be overridden. Note that the only detailed state that
8810 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8811 // worry about multiple different substates of CONNECTED.
8812 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8813 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08008814 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8815 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8816 // network agent is created, then goes to suspended, then goes out of suspended without
8817 // ever setting connected. Check if network agent is ever connected to update the state.
8818 newInfo.setDetailedState(nai.everConnected
8819 ? NetworkInfo.DetailedState.CONNECTED
8820 : NetworkInfo.DetailedState.CONNECTING,
8821 info.getReason(),
8822 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09008823 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008824 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09008825 return newInfo;
8826 }
8827
8828 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8829 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8830
Erik Kline99f301b2017-02-15 19:59:17 +09008831 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008832 NetworkInfo oldInfo = null;
8833 synchronized (networkAgent) {
8834 oldInfo = networkAgent.networkInfo;
8835 networkAgent.networkInfo = newInfo;
8836 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008837
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008838 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008839 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8840 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008841 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07008842
Robin Leea8c0b6e2016-05-01 23:00:00 +01008843 if (!networkAgent.created
8844 && (state == NetworkInfo.State.CONNECTED
8845 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008846
8847 // A network that has just connected has zero requests and is thus a foreground network.
8848 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8849
Luke Huangfdd11f82019-04-09 18:41:49 +08008850 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09008851 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008852 // Initialize the network's capabilities to their starting values according to the
8853 // underlying networks. This ensures that the capabilities are correct before
8854 // anything happens to the network.
8855 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09008856 }
Paul Jensen74940202014-08-04 12:21:19 -04008857 networkAgent.created = true;
Chiachang Wang3f6cc072021-03-24 18:39:17 +08008858 networkAgent.onNetworkCreated();
Robin Leea8c0b6e2016-05-01 23:00:00 +01008859 }
8860
8861 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
8862 networkAgent.everConnected = true;
8863
lucaslin45e639b2019-04-03 17:09:28 +08008864 // NetworkCapabilities need to be set before sending the private DNS config to
8865 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09008866 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
8867
Erik Kline9a62f012018-03-21 07:18:33 -07008868 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08008869 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
8870 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008871
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008872 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
8873 // command must be sent after updating LinkProperties to maximize chances of
8874 // NetworkMonitor seeing the correct LinkProperties when starting.
8875 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008876 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09008877 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008878 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09008879 networkAgent.networkMonitor().notifyNetworkConnected(
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008880 new LinkProperties(networkAgent.linkProperties,
8881 true /* parcelSensitiveFields */),
8882 networkAgent.networkCapabilities);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09008883 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008884
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008885 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
8886 // be communicated to a particular NetworkAgent depends only on the network's immutable,
8887 // capabilities, so it only needs to be done once on initial connect, not every time the
8888 // network's capabilities change. Note that we do this before rematching the network,
8889 // so we could decide to tear it down immediately afterwards. That's fine though - on
8890 // disconnection NetworkAgents should stop any signal strength monitoring they have been
8891 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09008892 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008893
junyulai0ac374f2020-12-14 18:41:52 +08008894 // Before first rematching networks, put an inactivity timer without any request, this
8895 // allows {@code updateInactivityState} to update the state accordingly and prevent
8896 // tearing down for any {@code unneeded} evaluation in this period.
8897 // Note that the timer will not be rescheduled since the expiry time is
8898 // fixed after connection regardless of the network satisfying other requests or not.
8899 // But it will be removed as soon as the network satisfies a request for the first time.
8900 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
8901 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08008902 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008903
Paul Jensen05e85ee2014-09-11 11:00:39 -04008904 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008905 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008906
8907 // This has to happen after matching the requests, because callbacks are just requests.
8908 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008909 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008910 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04008911 if (networkAgent.isVPN()) {
Chalard Jeanb2a49912018-01-16 18:43:05 +09008912 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04008913 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09008914 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00008915 if (networkAgent.isVPN()) {
8916 // As the active or bound network changes for apps, broadcast the default proxy, as
8917 // apps may need to update their proxy data. This is called after disconnecting from
8918 // VPN to make sure we do not broadcast the old proxy data.
8919 // TODO(b/122649188): send the broadcast only to VPN users.
8920 mProxyTracker.sendProxyBroadcast();
8921 }
Yintang Gu5014b522019-06-18 14:24:32 +08008922 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
8923 state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008924 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008925 }
8926 }
8927
Chalard Jean28018572020-12-21 18:36:52 +09008928 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09008929 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
8930 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008931 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07008932 }
8933
Erik Kline99f301b2017-02-15 19:59:17 +09008934 // Notify only this one new request of the current state. Transfer all the
8935 // current state by calling NetworkCapabilities and LinkProperties callbacks
8936 // so that callers can be guaranteed to have as close to atomicity in state
8937 // transfer as can be supported by this current API.
8938 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07008939 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09008940 if (nri.mPendingIntent != null) {
8941 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
8942 // Attempt no subsequent state pushes where intents are involved.
8943 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008944 }
Erik Kline99f301b2017-02-15 19:59:17 +09008945
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008946 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08008947 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008948 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
8949 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
8950 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08008951 }
8952
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008953 // Notify the requests on this NAI that the network is now lingered.
8954 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08008955 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008956 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
8957 }
8958
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008959 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
8960 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
8961 return vpnBlocked
8962 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
8963 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
8964 }
8965
8966 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
8967 if (blockedReasons == BLOCKED_REASON_NONE) {
8968 mUidBlockedReasons.delete(uid);
8969 } else {
8970 mUidBlockedReasons.put(uid, blockedReasons);
8971 }
8972 }
8973
junyulaif2c67e42018-08-07 19:50:45 +08008974 /**
8975 * Notify of the blocked state apps with a registered callback matching a given NAI.
8976 *
8977 * Unlike other callbacks, blocked status is different between each individual uid. So for
8978 * any given nai, all requests need to be considered according to the uid who filed it.
8979 *
8980 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008981 * @param oldMetered True if the previous network capabilities were metered.
8982 * @param newMetered True if the current network capabilities are metered.
8983 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
8984 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08008985 */
8986 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00008987 boolean newMetered, List<UidRange> oldBlockedUidRanges,
8988 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08008989
8990 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8991 NetworkRequest nr = nai.requestAt(i);
8992 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008993
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008994 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8995 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
8996 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008997 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008998 : oldVpnBlocked;
8999
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009000 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9001 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9002 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009003 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009004 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009005 }
9006 }
9007 }
9008
9009 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009010 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009011 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009012 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009013 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009014 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009015 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009016 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009017 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009018
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009019 final int oldBlockedState = getBlockedState(
9020 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9021 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9022 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009023 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009024 }
junyulaif2c67e42018-08-07 19:50:45 +08009025 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9026 NetworkRequest nr = nai.requestAt(i);
9027 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009028 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009029 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
9030 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009031 }
9032 }
9033 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009034 }
9035
Chalard Jean3a3f5f22019-04-10 23:07:55 +09009036 @VisibleForTesting
9037 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09009038 // The NetworkInfo we actually send out has no bearing on the real
9039 // state of affairs. For example, if the default connection is mobile,
9040 // and a request for HIPRI has just gone away, we need to pretend that
9041 // HIPRI has just disconnected. So we need to set the type to HIPRI and
9042 // the state to DISCONNECTED, even though the network is of type MOBILE
9043 // and is still connected.
9044 NetworkInfo info = new NetworkInfo(nai.networkInfo);
9045 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09009046 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009047 if (state != DetailedState.DISCONNECTED) {
9048 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09009049 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009050 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009051 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07009052 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
9053 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
9054 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
9055 if (info.isFailover()) {
9056 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
9057 nai.networkInfo.setFailover(false);
9058 }
9059 if (info.getReason() != null) {
9060 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
9061 }
9062 if (info.getExtraInfo() != null) {
9063 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
9064 }
9065 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09009066 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08009067 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07009068 if (newDefaultAgent != null) {
9069 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
9070 newDefaultAgent.networkInfo);
9071 } else {
9072 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
9073 }
9074 }
9075 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
9076 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09009077 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009078 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09009079 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009080 }
9081 }
9082 }
9083
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009084 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009085 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009086 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09009087 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09009088 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009089 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
9090 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009091 NetworkRequestInfo nri = mNetworkRequests.get(nr);
9092 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009093 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009094 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009095 } else {
9096 sendPendingIntentForRequest(nri, networkAgent, notifyType);
9097 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009098 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009099 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009100
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009101 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
9102 notifyNetworkCallbacks(networkAgent, notifyType, 0);
9103 }
9104
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009105 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09009106 * Returns the list of all interfaces that could be used by network traffic that does not
9107 * explicitly specify a network. This includes the default network, but also all VPNs that are
9108 * currently connected.
9109 *
9110 * Must be called on the handler thread.
9111 */
junyulaie7c7d2a2021-01-26 15:29:15 +08009112 @NonNull
9113 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009114 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08009115 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08009116 final Set<Integer> activeNetIds = new ArraySet<>();
9117 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9118 if (nri.isBeingSatisfied()) {
9119 activeNetIds.add(nri.getSatisfier().network().netId);
9120 }
9121 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009122 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattis2516da32021-01-31 17:06:19 -08009123 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09009124 defaultNetworks.add(nai.network);
9125 }
9126 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009127 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09009128 }
9129
9130 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09009131 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
9132 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009133 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08009134 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009135 ensureRunningOnConnectivityServiceThread();
9136 String activeIface = null;
9137 LinkProperties activeLinkProperties = getActiveLinkProperties();
9138 if (activeLinkProperties != null) {
9139 activeIface = activeLinkProperties.getInterfaceName();
9140 }
Benedict Wong9308cd32019-06-12 17:46:31 +00009141
junyulai2050bed2021-01-23 09:46:34 +08009142 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009143 try {
junyulaide41fc22021-01-22 22:46:01 +08009144 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
junyulai69114da2021-03-05 14:46:25 +08009145 for (final NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaide41fc22021-01-22 22:46:01 +08009146 snapshots.add(snapshot);
9147 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009148 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
9149 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009150 } catch (Exception ignored) {
9151 }
9152 }
9153
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07009154 @Override
Udam Sainicd645462016-01-04 12:16:14 -08009155 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08009156 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009157 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009158 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009159
9160 if (!TextUtils.isEmpty(settingUrl)) {
9161 return settingUrl;
9162 }
9163
9164 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009165 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009166 if (!TextUtils.isEmpty(settingUrl)) {
9167 return settingUrl;
9168 }
9169
9170 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009171 }
9172
9173 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009174 public void startNattKeepalive(Network network, int intervalSeconds,
9175 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009176 enforceKeepalivePermission();
9177 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009178 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai070f9ff2019-01-16 20:23:34 +08009179 intervalSeconds, cb,
junyulai011b1f12019-01-03 18:50:15 +08009180 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009181 }
9182
9183 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009184 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009185 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulaid05a1922019-01-15 11:32:44 +08009186 String dstAddr) {
Josh Gao461a1222020-06-16 15:58:11 -07009187 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009188 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009189 mKeepaliveTracker.startNattKeepalive(
9190 getNetworkAgentInfoForNetwork(network), fd, resourceId,
9191 intervalSeconds, cb,
9192 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
9193 } finally {
9194 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9195 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009196 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9197 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009198 }
9199 }
junyulaid05a1922019-01-15 11:32:44 +08009200 }
9201
9202 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009203 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009204 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009205 try {
9206 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08009207 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009208 mKeepaliveTracker.startTcpKeepalive(
9209 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
9210 } finally {
9211 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9212 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009213 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9214 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009215 }
9216 }
junyulai0835a1e2019-01-08 20:04:33 +08009217 }
9218
9219 @Override
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009220 public void stopKeepalive(Network network, int slot) {
9221 mHandler.sendMessage(mHandler.obtainMessage(
junyulai011b1f12019-01-03 18:50:15 +08009222 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009223 }
9224
9225 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07009226 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08009227 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07009228
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009229 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08009230 final long token = Binder.clearCallingIdentity();
9231 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009232 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
9233 UserHandle.getUserHandleForUid(uid))) {
9234 return;
9235 }
9236
Heemin Seogdb8489d2019-06-12 09:21:44 -07009237 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
9238 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009239
9240 // Turn airplane mode off
9241 setAirplaneMode(false);
9242
9243 // restore private DNS settings to default mode (opportunistic)
9244 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
9245 UserHandle.getUserHandleForUid(uid))) {
9246 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
9247 PRIVATE_DNS_MODE_OPPORTUNISTIC);
9248 }
9249
9250 Settings.Global.putString(mContext.getContentResolver(),
9251 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08009252 } finally {
9253 Binder.restoreCallingIdentity(token);
9254 }
Stuart Scottd5463642015-04-02 18:00:02 -07009255 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04009256
Ricky Wai7097cc92018-01-23 04:09:45 +00009257 @Override
9258 public byte[] getNetworkWatchlistConfigHash() {
9259 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
9260 if (nwm == null) {
9261 loge("Unable to get NetworkWatchlistManager");
9262 return null;
9263 }
9264 // Redirect it to network watchlist service to access watchlist file and calculate hash.
9265 return nwm.getWatchlistConfigHash();
9266 }
9267
Hugo Benichibe0c7652016-05-31 16:28:06 +09009268 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09009269 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08009270 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09009271 }
Hugo Benichif4210292017-04-21 15:07:12 +09009272
9273 private static boolean toBool(int encodedBoolean) {
9274 return encodedBoolean != 0; // Only 0 means false.
9275 }
9276
9277 private static int encodeBool(boolean b) {
9278 return b ? 1 : 0;
9279 }
mswest4632928412018-03-12 10:34:34 -07009280
9281 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009282 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
9283 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
9284 @NonNull String[] args) {
9285 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
9286 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07009287 }
9288
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009289 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07009290 @Override
9291 public int onCommand(String cmd) {
9292 if (cmd == null) {
9293 return handleDefaultCommands(cmd);
9294 }
9295 final PrintWriter pw = getOutPrintWriter();
9296 try {
9297 switch (cmd) {
9298 case "airplane-mode":
9299 final String action = getNextArg();
9300 if ("enable".equals(action)) {
9301 setAirplaneMode(true);
9302 return 0;
9303 } else if ("disable".equals(action)) {
9304 setAirplaneMode(false);
9305 return 0;
9306 } else if (action == null) {
9307 final ContentResolver cr = mContext.getContentResolver();
9308 final int enabled = Settings.Global.getInt(cr,
9309 Settings.Global.AIRPLANE_MODE_ON);
9310 pw.println(enabled == 0 ? "disabled" : "enabled");
9311 return 0;
9312 } else {
9313 onHelp();
9314 return -1;
9315 }
9316 default:
9317 return handleDefaultCommands(cmd);
9318 }
9319 } catch (Exception e) {
9320 pw.println(e);
9321 }
9322 return -1;
9323 }
9324
9325 @Override
9326 public void onHelp() {
9327 PrintWriter pw = getOutPrintWriter();
9328 pw.println("Connectivity service commands:");
9329 pw.println(" help");
9330 pw.println(" Print this help text.");
9331 pw.println(" airplane-mode [enable|disable]");
9332 pw.println(" Turn airplane mode on or off.");
9333 pw.println(" airplane-mode");
9334 pw.println(" Get airplane mode.");
9335 }
9336 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009337
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09009338 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009339 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
9340 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
9341 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +08009342 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009343 }
9344
9345 /**
9346 * @param connectionInfo the connection to resolve.
9347 * @return {@code uid} if the connection is found and the app has permission to observe it
9348 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
9349 * connection is not found.
9350 */
9351 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009352 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
9353 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
9354 }
9355
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09009356 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009357 connectionInfo.local, connectionInfo.remote);
9358
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009359 if (uid == INVALID_UID) return uid; // Not found.
9360
9361 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
9362 // VPN, if any, that applies to the UID that owns the connection.
9363 if (checkNetworkStackPermission()) return uid;
9364
9365 final NetworkAgentInfo vpn = getVpnForUid(uid);
9366 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09009367 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009368 return INVALID_UID;
9369 }
9370
9371 return uid;
9372 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +00009373
Benedict Wong493e04b2018-11-09 14:45:34 -08009374 /**
9375 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
9376 *
9377 * <p>The TestNetworkService must be run in the system server due to TUN creation.
9378 */
9379 @Override
9380 public IBinder startOrGetTestNetworkService() {
9381 synchronized (mTNSLock) {
9382 TestNetworkService.enforceTestNetworkPermissions(mContext);
9383
9384 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +08009385 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -08009386 }
9387
9388 return mTNS;
9389 }
9390 }
Cody Kestingd199a9d2019-12-17 12:55:28 -08009391
Cody Kesting73708bf2019-12-18 10:57:50 -08009392 /**
9393 * Handler used for managing all Connectivity Diagnostics related functions.
9394 *
9395 * @see android.net.ConnectivityDiagnosticsManager
9396 *
9397 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9398 */
9399 @VisibleForTesting
9400 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009401 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9402
Cody Kesting73708bf2019-12-18 10:57:50 -08009403 /**
9404 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9405 * android.net.ConnectivityDiagnosticsManager}.
9406 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9407 * NetworkRequestInfo to be registered
9408 */
9409 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9410
9411 /**
9412 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9413 * android.net.ConnectivityDiagnosticsManager}.
9414 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9415 * arg1 = the uid of the caller
9416 */
9417 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9418
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009419 /**
9420 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
9421 * after processing {@link #EVENT_NETWORK_TESTED} events.
9422 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9423 * NetworkMonitor.
9424 * data = PersistableBundle of extras passed from NetworkMonitor.
9425 *
9426 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
9427 */
9428 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
9429
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009430 /**
9431 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9432 * been detected on the network.
9433 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9434 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9435 * arg2 = NetID.
9436 * data = PersistableBundle of extras passed from NetworkMonitor.
9437 */
9438 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9439
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009440 /**
9441 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9442 * the platform. This event will invoke {@link
9443 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9444 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -07009445 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009446 */
9447 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9448
Cody Kesting73708bf2019-12-18 10:57:50 -08009449 private ConnectivityDiagnosticsHandler(Looper looper) {
9450 super(looper);
9451 }
9452
9453 @Override
9454 public void handleMessage(Message msg) {
9455 switch (msg.what) {
9456 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9457 handleRegisterConnectivityDiagnosticsCallback(
9458 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9459 break;
9460 }
9461 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9462 handleUnregisterConnectivityDiagnosticsCallback(
9463 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9464 break;
9465 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009466 case EVENT_NETWORK_TESTED: {
9467 final ConnectivityReportEvent reportEvent =
9468 (ConnectivityReportEvent) msg.obj;
9469
Aaron Huang959d3642021-01-21 15:47:41 +08009470 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009471 break;
9472 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009473 case EVENT_DATA_STALL_SUSPECTED: {
9474 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +08009475 final Pair<Long, PersistableBundle> arg =
9476 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009477 if (nai == null) break;
9478
Aaron Huang959d3642021-01-21 15:47:41 +08009479 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009480 break;
9481 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009482 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -07009483 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009484 break;
9485 }
9486 default: {
9487 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9488 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009489 }
9490 }
9491 }
9492
9493 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9494 @VisibleForTesting
9495 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9496 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9497 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009498 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009499
9500 @VisibleForTesting
9501 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009502 @NonNull IConnectivityDiagnosticsCallback cb,
9503 @NonNull NetworkRequestInfo nri,
9504 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009505 mCb = cb;
9506 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009507 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009508 }
9509
9510 @Override
9511 public void binderDied() {
9512 log("ConnectivityDiagnosticsCallback IBinder died.");
9513 unregisterConnectivityDiagnosticsCallback(mCb);
9514 }
9515 }
9516
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009517 /**
9518 * Class used for sending information from {@link
9519 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9520 */
9521 private static class NetworkTestedResults {
9522 private final int mNetId;
9523 private final int mTestResult;
9524 private final long mTimestampMillis;
9525 @Nullable private final String mRedirectUrl;
9526
9527 private NetworkTestedResults(
9528 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9529 mNetId = netId;
9530 mTestResult = testResult;
9531 mTimestampMillis = timestampMillis;
9532 mRedirectUrl = redirectUrl;
9533 }
9534 }
9535
9536 /**
9537 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9538 * ConnectivityDiagnosticsHandler}.
9539 */
9540 private static class ConnectivityReportEvent {
9541 private final long mTimestampMillis;
9542 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +08009543 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009544
Aaron Huang959d3642021-01-21 15:47:41 +08009545 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9546 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009547 mTimestampMillis = timestampMillis;
9548 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +08009549 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009550 }
9551 }
9552
Cody Kestingf1120be2020-08-03 18:01:40 -07009553 /**
9554 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
9555 * ConnectivityDiagnosticsHandler}.
9556 */
9557 private static class ReportedNetworkConnectivityInfo {
9558 public final boolean hasConnectivity;
9559 public final boolean isNetworkRevalidating;
9560 public final int reporterUid;
9561 @NonNull public final NetworkAgentInfo nai;
9562
9563 private ReportedNetworkConnectivityInfo(
9564 boolean hasConnectivity,
9565 boolean isNetworkRevalidating,
9566 int reporterUid,
9567 @NonNull NetworkAgentInfo nai) {
9568 this.hasConnectivity = hasConnectivity;
9569 this.isNetworkRevalidating = isNetworkRevalidating;
9570 this.reporterUid = reporterUid;
9571 this.nai = nai;
9572 }
9573 }
9574
Cody Kesting73708bf2019-12-18 10:57:50 -08009575 private void handleRegisterConnectivityDiagnosticsCallback(
9576 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9577 ensureRunningOnConnectivityServiceThread();
9578
9579 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -08009580 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009581 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9582
James Mattis64b8b0f2020-11-24 17:40:49 -08009583 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9584 // confusing for these networks to change when an NRI is satisfied in another layer.
9585 if (nri.isMultilayerRequest()) {
9586 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9587 + "network requests.");
9588 }
9589
Cody Kesting73708bf2019-12-18 10:57:50 -08009590 // This means that the client registered the same callback multiple times. Do
9591 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -08009592 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009593 if (VDBG) log("Diagnostics callback is already registered");
9594
9595 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9596 // incremented when the NetworkRequestInfo is created as part of
9597 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009598 nri.decrementRequestCount();
Cody Kesting73708bf2019-12-18 10:57:50 -08009599 return;
9600 }
9601
Cody Kesting31f1ff62020-03-05 10:46:02 -08009602 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -08009603
9604 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -08009605 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009606 } catch (RemoteException e) {
9607 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -08009608 return;
9609 }
9610
9611 // Once registered, provide ConnectivityReports for matching Networks
9612 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9613 synchronized (mNetworkForNetId) {
9614 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9615 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -08009616 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9617 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -08009618 matchingNetworks.add(nai);
9619 }
9620 }
9621 }
9622 for (final NetworkAgentInfo nai : matchingNetworks) {
9623 final ConnectivityReport report = nai.getConnectivityReport();
9624 if (report == null) {
9625 continue;
9626 }
9627 if (!checkConnectivityDiagnosticsPermissions(
9628 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9629 continue;
9630 }
9631
9632 try {
9633 cb.onConnectivityReportAvailable(report);
9634 } catch (RemoteException e) {
9635 // Exception while sending the ConnectivityReport. Move on to the next network.
9636 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009637 }
9638 }
9639
9640 private void handleUnregisterConnectivityDiagnosticsCallback(
9641 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9642 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009643 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009644
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009645 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9646 mConnectivityDiagnosticsCallbacks.remove(iCb);
9647 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009648 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9649 return;
9650 }
9651
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009652 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -08009653
Cody Kesting70fa2b22020-12-02 12:16:56 -08009654 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9655 // (if the Binder died)
9656 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9657 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -08009658 return;
9659 }
9660
Cody Kesting46cb1672020-03-04 13:35:20 -08009661 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9662 // incremented when the NetworkRequestInfo is created as part of
9663 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009664 nri.decrementRequestCount();
Cody Kesting46cb1672020-03-04 13:35:20 -08009665
Cody Kesting31f1ff62020-03-05 10:46:02 -08009666 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009667 }
9668
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009669 private void handleNetworkTestedWithExtras(
9670 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9671 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -08009672 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009673 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009674 final ConnectivityReport report =
9675 new ConnectivityReport(
9676 reportEvent.mNai.network,
9677 reportEvent.mTimestampMillis,
9678 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009679 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009680 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -08009681 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -07009682
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009683 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009684 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009685 for (final IConnectivityDiagnosticsCallback cb : results) {
9686 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -08009687 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009688 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -07009689 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009690 }
9691 }
9692 }
9693
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009694 private void handleDataStallSuspected(
9695 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9696 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -08009697 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009698 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009699 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -08009700 new DataStallReport(
9701 nai.network,
9702 timestampMillis,
9703 detectionMethod,
9704 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009705 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -08009706 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009707 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009708 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009709 for (final IConnectivityDiagnosticsCallback cb : results) {
9710 try {
9711 cb.onDataStallSuspected(report);
9712 } catch (RemoteException ex) {
9713 loge("Error invoking onDataStallSuspected", ex);
9714 }
9715 }
9716 }
9717
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009718 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -07009719 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
9720 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
9721 final ConnectivityReport cachedReport = nai.getConnectivityReport();
9722
9723 // If the Network is being re-validated as a result of this call to
9724 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
9725 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009726 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009727 getMatchingPermissionedCallbacks(
9728 nai,
9729 reportedNetworkConnectivityInfo.isNetworkRevalidating
9730 ? Process.INVALID_UID
9731 : reportedNetworkConnectivityInfo.reporterUid);
9732
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009733 for (final IConnectivityDiagnosticsCallback cb : results) {
9734 try {
Cody Kestingf1120be2020-08-03 18:01:40 -07009735 cb.onNetworkConnectivityReported(
9736 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009737 } catch (RemoteException ex) {
9738 loge("Error invoking onNetworkConnectivityReported", ex);
9739 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009740
9741 // If the Network isn't re-validating, also provide the cached report. If there is no
9742 // cached report, the Network is still being validated and a report will be sent once
9743 // validation is complete. Note that networks which never undergo validation will still
9744 // have a cached ConnectivityReport with RESULT_SKIPPED.
9745 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
9746 try {
9747 cb.onConnectivityReportAvailable(cachedReport);
9748 } catch (RemoteException ex) {
9749 loge("Error invoking onConnectivityReportAvailable", ex);
9750 }
9751 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009752 }
9753 }
9754
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009755 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +09009756 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9757 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009758 sanitized.setUids(null);
9759 sanitized.setAdministratorUids(new int[0]);
9760 sanitized.setOwnerUid(Process.INVALID_UID);
9761 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -08009762 }
9763
Cody Kestingf1120be2020-08-03 18:01:40 -07009764 /**
9765 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
9766 *
9767 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
9768 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009769 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -07009770 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009771 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009772 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009773 mConnectivityDiagnosticsCallbacks.entrySet()) {
9774 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9775 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -07009776
James Mattis64b8b0f2020-11-24 17:40:49 -08009777 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -07009778 if (!nai.satisfies(nri.mRequests.get(0))) {
9779 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009780 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009781
9782 // UID for this callback must either be:
9783 // - INVALID_UID (which sends callbacks to all UIDs), or
9784 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
9785 // notified as a result)
9786 if (uid != Process.INVALID_UID && uid != nri.mUid) {
9787 continue;
9788 }
9789
9790 if (!checkConnectivityDiagnosticsPermissions(
9791 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9792 continue;
9793 }
9794
9795 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009796 }
9797 return results;
9798 }
9799
Cody Kesting7474f672021-05-11 14:22:40 -07009800 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
9801 @NonNull NetworkAgentInfo nai) {
9802 // TODO(b/188483916): replace with a transport-agnostic location-aware check
9803 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
9804 }
9805
Cody Kesting160ef392021-05-05 13:17:22 -07009806 private boolean hasLocationPermission(String packageName, int uid) {
9807 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9808 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9809 // call in a try-catch.
9810 try {
9811 if (!mLocationPermissionChecker.checkLocationPermission(
9812 packageName, null /* featureId */, uid, null /* message */)) {
9813 return false;
9814 }
9815 } catch (SecurityException e) {
9816 return false;
9817 }
9818
9819 return true;
9820 }
9821
9822 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
9823 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +09009824 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -07009825 && virtual.networkCapabilities.getOwnerUid() == uid
9826 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
9827 return true;
9828 }
9829 }
9830
9831 return false;
9832 }
9833
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009834 @VisibleForTesting
9835 boolean checkConnectivityDiagnosticsPermissions(
9836 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9837 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9838 return true;
9839 }
9840
Cody Kesting160ef392021-05-05 13:17:22 -07009841 // Administrator UIDs also contains the Owner UID
9842 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
9843 if (!CollectionUtils.contains(administratorUids, callbackUid)
9844 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009845 return false;
9846 }
9847
Cody Kesting7474f672021-05-11 14:22:40 -07009848 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
9849 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009850 }
9851
Cody Kestingd199a9d2019-12-17 12:55:28 -08009852 @Override
9853 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009854 @NonNull IConnectivityDiagnosticsCallback callback,
9855 @NonNull NetworkRequest request,
9856 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -07009857 Objects.requireNonNull(callback, "callback must not be null");
9858 Objects.requireNonNull(request, "request must not be null");
9859 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
9860
Cody Kesting73708bf2019-12-18 10:57:50 -08009861 if (request.legacyType != TYPE_NONE) {
9862 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
9863 + " Please use NetworkCapabilities instead.");
9864 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009865 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -08009866 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009867
9868 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
9869 // and administrator uids to be safe.
9870 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08009871 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009872
9873 final NetworkRequest requestWithId =
9874 new NetworkRequest(
9875 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
9876
9877 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
9878 //
9879 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
9880 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
9881 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009882 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -08009883 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009884 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009885
9886 mConnectivityDiagnosticsHandler.sendMessage(
9887 mConnectivityDiagnosticsHandler.obtainMessage(
9888 ConnectivityDiagnosticsHandler
9889 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9890 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -08009891 }
9892
9893 @Override
9894 public void unregisterConnectivityDiagnosticsCallback(
9895 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +08009896 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -08009897 mConnectivityDiagnosticsHandler.sendMessage(
9898 mConnectivityDiagnosticsHandler.obtainMessage(
9899 ConnectivityDiagnosticsHandler
9900 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009901 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -08009902 0,
9903 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -08009904 }
Cody Kestingf53a0752020-04-15 12:33:28 -07009905
9906 @Override
9907 public void simulateDataStall(int detectionMethod, long timestampMillis,
9908 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -07009909 Objects.requireNonNull(network, "network must not be null");
9910 Objects.requireNonNull(extras, "extras must not be null");
9911
Cody Kestingf53a0752020-04-15 12:33:28 -07009912 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
9913 android.Manifest.permission.NETWORK_STACK);
9914 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
9915 if (!nc.hasTransport(TRANSPORT_TEST)) {
Chalard Jean15228572022-01-28 19:29:12 +09009916 throw new SecurityException("Data Stall simulation is only possible for test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -07009917 }
9918
9919 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009920 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -07009921 throw new SecurityException("Data Stall simulation is only possible for network "
9922 + "creators");
9923 }
9924
Cody Kesting652e3ec2020-05-21 12:08:21 -07009925 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
9926 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
9927 // Data Stall information as a DataStallReportParcelable and passing to
9928 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
9929 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -07009930 final DataStallReportParcelable p = new DataStallReportParcelable();
9931 p.timestampMillis = timestampMillis;
9932 p.detectionMethod = detectionMethod;
9933
9934 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
9935 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
9936 }
9937 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
9938 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
9939 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
9940 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
9941 }
9942
Serik Beketayevec8ad212020-12-07 22:43:07 -08009943 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -07009944 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009945
lucaslin66f44212021-02-23 01:12:55 +08009946 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
9947 @Override
lucaslin87b58aa2021-02-25 15:10:29 +08009948 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +08009949 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +08009950 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +08009951 }
lucaslin37a16d92021-01-21 19:48:09 +08009952
9953 @Override
9954 public void onInterfaceLinkStateChanged(String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +08009955 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +08009956 nai.clatd.interfaceLinkStateChanged(iface, up);
9957 }
9958 }
9959
9960 @Override
9961 public void onInterfaceRemoved(String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +08009962 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +08009963 nai.clatd.interfaceRemoved(iface);
9964 }
lucaslin66f44212021-02-23 01:12:55 +08009965 }
9966 }
9967
lucaslin1a8b4c62021-01-21 02:02:55 +08009968 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
9969
9970 /**
9971 * Class used for updating network activity tracking with netd and notify network activity
9972 * changes.
9973 */
9974 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +08009975 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +08009976 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +08009977 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +08009978 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
9979 new RemoteCallbackList<>();
9980 // Indicate the current system default network activity is active or not.
9981 @GuardedBy("mActiveIdleTimers")
9982 private boolean mNetworkActive;
9983 @GuardedBy("mActiveIdleTimers")
9984 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
9985 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +08009986
lucaslin1193a5d2021-01-21 02:04:15 +08009987 private class IdleTimerParams {
9988 public final int timeout;
9989 public final int transportType;
9990
9991 IdleTimerParams(int timeout, int transport) {
9992 this.timeout = timeout;
9993 this.transportType = transport;
9994 }
9995 }
9996
9997 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +08009998 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +08009999 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080010000 mNetd = netd;
10001 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010002 }
10003
lucaslin66f44212021-02-23 01:12:55 +080010004 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
10005 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
10006 synchronized (mActiveIdleTimers) {
10007 mNetworkActive = active;
10008 // If there are no idle timers, it means that system is not monitoring
10009 // activity, so the system default network for those default network
10010 // unspecified apps is always considered active.
10011 //
10012 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
10013 // any network activity change event. Whenever this event is received,
10014 // the mActiveIdleTimers should be always not empty. The legacy behavior
10015 // is no-op. Remove to refer to mNetworkActive only.
10016 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
10017 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
10018 }
10019 }
10020 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010021
lucaslin1193a5d2021-01-21 02:04:15 +080010022 // The network activity should only be updated from ConnectivityService handler thread
10023 // when mActiveIdleTimers lock is held.
10024 @GuardedBy("mActiveIdleTimers")
10025 private void reportNetworkActive() {
10026 final int length = mNetworkActivityListeners.beginBroadcast();
10027 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
10028 try {
10029 for (int i = 0; i < length; i++) {
10030 try {
10031 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
10032 } catch (RemoteException | RuntimeException e) {
10033 loge("Fail to send network activie to listener " + e);
10034 }
10035 }
10036 } finally {
10037 mNetworkActivityListeners.finishBroadcast();
10038 }
10039 }
10040
10041 @GuardedBy("mActiveIdleTimers")
10042 public void handleReportNetworkActivity() {
10043 synchronized (mActiveIdleTimers) {
10044 reportNetworkActive();
10045 }
10046 }
10047
lucaslin1a8b4c62021-01-21 02:02:55 +080010048 // This is deprecated and only to support legacy use cases.
10049 private int transportTypeToLegacyType(int type) {
10050 switch (type) {
10051 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010052 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080010053 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010054 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080010055 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010056 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080010057 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010058 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080010059 default:
10060 loge("Unexpected transport in transportTypeToLegacyType: " + type);
10061 }
10062 return ConnectivityManager.TYPE_NONE;
10063 }
10064
10065 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
10066 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
10067 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
10068 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
10069 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
10070 final long ident = Binder.clearCallingIdentity();
10071 try {
10072 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
10073 RECEIVE_DATA_ACTIVITY_CHANGE,
10074 null /* resultReceiver */,
10075 null /* scheduler */,
10076 0 /* initialCode */,
10077 null /* initialData */,
10078 null /* initialExtra */);
10079 } finally {
10080 Binder.restoreCallingIdentity(ident);
10081 }
10082 }
10083
10084 /**
10085 * Setup data activity tracking for the given network.
10086 *
10087 * Every {@code setupDataActivityTracking} should be paired with a
10088 * {@link #removeDataActivityTracking} for cleanup.
10089 */
10090 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
10091 final String iface = networkAgent.linkProperties.getInterfaceName();
10092
10093 final int timeout;
10094 final int type;
10095
10096 if (networkAgent.networkCapabilities.hasTransport(
10097 NetworkCapabilities.TRANSPORT_CELLULAR)) {
10098 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010099 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080010100 10);
10101 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10102 } else if (networkAgent.networkCapabilities.hasTransport(
10103 NetworkCapabilities.TRANSPORT_WIFI)) {
10104 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010105 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080010106 15);
10107 type = NetworkCapabilities.TRANSPORT_WIFI;
10108 } else {
10109 return; // do not track any other networks
10110 }
10111
lucaslinb961efc2021-01-21 02:03:17 +080010112 updateRadioPowerState(true /* isActive */, type);
10113
lucaslin1a8b4c62021-01-21 02:02:55 +080010114 if (timeout > 0 && iface != null) {
10115 try {
lucaslin1193a5d2021-01-21 02:04:15 +080010116 synchronized (mActiveIdleTimers) {
10117 // Networks start up.
10118 mNetworkActive = true;
10119 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
10120 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
10121 reportNetworkActive();
10122 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010123 } catch (Exception e) {
10124 // You shall not crash!
10125 loge("Exception in setupDataActivityTracking " + e);
10126 }
10127 }
10128 }
10129
10130 /**
10131 * Remove data activity tracking when network disconnects.
10132 */
10133 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
10134 final String iface = networkAgent.linkProperties.getInterfaceName();
10135 final NetworkCapabilities caps = networkAgent.networkCapabilities;
10136
lucaslinb961efc2021-01-21 02:03:17 +080010137 if (iface == null) return;
10138
10139 final int type;
10140 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
10141 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10142 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
10143 type = NetworkCapabilities.TRANSPORT_WIFI;
10144 } else {
10145 return; // do not track any other networks
10146 }
10147
10148 try {
10149 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080010150 synchronized (mActiveIdleTimers) {
10151 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
10152 // The call fails silently if no idle timer setup for this interface
10153 mNetd.idletimerRemoveInterface(iface, params.timeout,
10154 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080010155 }
lucaslinb961efc2021-01-21 02:03:17 +080010156 } catch (Exception e) {
10157 // You shall not crash!
10158 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080010159 }
10160 }
10161
10162 /**
10163 * Update data activity tracking when network state is updated.
10164 */
10165 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
10166 NetworkAgentInfo oldNetwork) {
10167 if (newNetwork != null) {
10168 setupDataActivityTracking(newNetwork);
10169 }
10170 if (oldNetwork != null) {
10171 removeDataActivityTracking(oldNetwork);
10172 }
10173 }
lucaslinb961efc2021-01-21 02:03:17 +080010174
10175 private void updateRadioPowerState(boolean isActive, int transportType) {
10176 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
10177 switch (transportType) {
10178 case NetworkCapabilities.TRANSPORT_CELLULAR:
10179 bs.reportMobileRadioPowerState(isActive, NO_UID);
10180 break;
10181 case NetworkCapabilities.TRANSPORT_WIFI:
10182 bs.reportWifiRadioPowerState(isActive, NO_UID);
10183 break;
10184 default:
10185 logw("Untracked transport type:" + transportType);
10186 }
10187 }
lucaslin1193a5d2021-01-21 02:04:15 +080010188
10189 public boolean isDefaultNetworkActive() {
10190 synchronized (mActiveIdleTimers) {
10191 // If there are no idle timers, it means that system is not monitoring activity,
10192 // so the default network is always considered active.
10193 //
10194 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
10195 // tracking is disabled (negative idle timer value configured), or no active default
10196 // network. In the latter case, this reports active but it should report inactive.
10197 return mNetworkActive || mActiveIdleTimers.isEmpty();
10198 }
10199 }
10200
10201 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
10202 mNetworkActivityListeners.register(l);
10203 }
10204
10205 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
10206 mNetworkActivityListeners.unregister(l);
10207 }
lucaslin012f7a12021-01-21 02:04:35 +080010208
10209 public void dump(IndentingPrintWriter pw) {
10210 synchronized (mActiveIdleTimers) {
10211 pw.print("mNetworkActive="); pw.println(mNetworkActive);
10212 pw.println("Idle timers:");
10213 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
10214 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
10215 final IdleTimerParams params = ent.getValue();
10216 pw.print(" timeout="); pw.print(params.timeout);
10217 pw.print(" type="); pw.println(params.transportType);
10218 }
10219 }
10220 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010221 }
James Mattis47db0582021-01-01 14:13:35 -080010222
Daniel Brightf9e945b2020-06-15 16:10:01 -070010223 /**
10224 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
10225 *
10226 * @param socketInfo the socket information
10227 * @param callback the callback to register
10228 */
10229 @Override
10230 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
10231 @NonNull final IQosCallback callback) {
10232 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
10233 if (nai == null || nai.networkCapabilities == null) {
10234 try {
10235 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
10236 } catch (final RemoteException ex) {
10237 loge("registerQosCallbackInternal: RemoteException", ex);
10238 }
10239 return;
10240 }
10241 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
10242 }
10243
10244 /**
10245 * Register a {@link IQosCallback} with base {@link QosFilter}.
10246 *
10247 * @param filter the filter to register
10248 * @param callback the callback to register
10249 * @param nai the agent information related to the filter's network
10250 */
10251 @VisibleForTesting
10252 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
10253 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
10254 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
10255 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
10256
10257 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
10258 enforceConnectivityRestrictedNetworksPermission();
10259 }
10260 mQosCallbackTracker.registerCallback(callback, filter, nai);
10261 }
10262
10263 /**
10264 * Unregisters the given callback.
10265 *
10266 * @param callback the callback to unregister
10267 */
10268 @Override
10269 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010270 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010271 mQosCallbackTracker.unregisterCallback(callback);
10272 }
James Mattis47db0582021-01-01 14:13:35 -080010273
James Mattis45d81842021-01-10 14:24:24 -080010274 /**
Chalard Jeanfa45a682021-02-25 17:23:40 +090010275 * Request that a user profile is put by default on a network matching a given preference.
10276 *
10277 * See the documentation for the individual preferences for a description of the supported
10278 * behaviors.
10279 *
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010280 * @param profile the user profile for whih the preference is being set.
10281 * @param preferences the list of profile network preferences for the
10282 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010283 * @param listener an optional listener to listen for completion of the operation.
10284 */
10285 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010286 public void setProfileNetworkPreferences(
10287 @NonNull final UserHandle profile,
10288 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090010289 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010290 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010291 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010292
10293 if (preferences.size() == 0) {
10294 preferences.add((new ProfileNetworkPreference.Builder()).build());
10295 }
10296
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010297 PermissionUtils.enforceNetworkStackPermission(mContext);
10298 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010299 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010300 }
10301 if (profile.getIdentifier() < 0) {
10302 throw new IllegalArgumentException("Must explicitly specify a user handle ("
10303 + "UserHandle.CURRENT not supported)");
10304 }
Chalard Jeana21ef9b2021-04-02 19:24:44 +090010305 final UserManager um = mContext.getSystemService(UserManager.class);
10306 if (!um.isManagedProfile(profile.getIdentifier())) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010307 throw new IllegalArgumentException("Profile must be a managed profile");
10308 }
paulhuaa0743d2021-05-26 21:56:03 +080010309
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010310 final List<ProfileNetworkPreferenceList.Preference> preferenceList =
10311 new ArrayList<ProfileNetworkPreferenceList.Preference>();
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010312 boolean allowFallback = true;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010313 for (final ProfileNetworkPreference preference : preferences) {
10314 final NetworkCapabilities nc;
10315 switch (preference.getPreference()) {
10316 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
10317 nc = null;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010318 if (preference.getPreferenceEnterpriseId() != 0) {
10319 throw new IllegalArgumentException(
10320 "Invalid enterprise identifier in setProfileNetworkPreferences");
10321 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010322 break;
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010323 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
10324 allowFallback = false;
10325 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010326 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010327 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
10328 throw new IllegalArgumentException(
10329 "Invalid enterprise identifier in setProfileNetworkPreferences");
10330 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010331 final Set<UidRange> uidRangeSet =
10332 getUidListToBeAppliedForNetworkPreference(profile, preference);
10333 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
10334 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
10335 } else {
10336 throw new IllegalArgumentException(
10337 "Overlapping uid range in setProfileNetworkPreferences");
10338 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010339 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010340 nc.addEnterpriseId(
10341 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010342 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10343 break;
10344 default:
10345 throw new IllegalArgumentException(
10346 "Invalid preference in setProfileNetworkPreferences");
10347 }
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010348 preferenceList.add(new ProfileNetworkPreferenceList.Preference(
10349 profile, nc, allowFallback));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010350 }
10351 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010352 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010353 }
10354
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010355 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
10356 @NonNull final UserHandle profile,
10357 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
10358 final UidRange profileUids = UidRange.createForUser(profile);
10359 Set<UidRange> uidRangeSet = UidRangeUtils.convertListToUidRange(
10360 profileNetworkPreference.getIncludedUids());
10361 if (uidRangeSet.size() > 0) {
10362 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
10363 throw new IllegalArgumentException(
10364 "Allow uid range is outside the uid range of profile.");
10365 }
10366 } else {
10367 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertListToUidRange(
10368 profileNetworkPreference.getExcludedUids());
10369 if (disallowUidRangeSet.size() > 0) {
10370 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
10371 throw new IllegalArgumentException(
10372 "disallow uid range is outside the uid range of profile.");
10373 }
10374 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
10375 disallowUidRangeSet);
10376 } else {
10377 uidRangeSet = new ArraySet<UidRange>();
10378 uidRangeSet.add(profileUids);
10379 }
10380 }
10381 return uidRangeSet;
10382 }
10383
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010384 private boolean isEnterpriseIdentifierValid(
10385 @NetworkCapabilities.EnterpriseId int identifier) {
10386 if ((identifier >= NET_ENTERPRISE_ID_1)
10387 && (identifier <= NET_ENTERPRISE_ID_5)) {
10388 return true;
10389 }
10390 return false;
10391 }
10392
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010393 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
10394 @Nullable final NetworkCapabilities nc) {
10395 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
10396 ensureRequestableCapabilities(nc);
10397 }
10398
10399 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010400 @NonNull final ProfileNetworkPreferenceList prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010401 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010402 for (final ProfileNetworkPreferenceList.Preference pref : prefs.preferences) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010403 // The NRI for a user should contain the request for capabilities.
10404 // If fallback to default network is needed then NRI should include
10405 // the request for the default network. Create an image of it to
10406 // have the correct UIDs in it (also a request can only be part of one NRI, because
10407 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010408 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
10409 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010410 if (pref.allowFallback) {
10411 nrs.add(createDefaultInternetRequestForTransport(
10412 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10413 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010414 if (VDBG) {
10415 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
10416 pref.capabilities.getUids()));
10417 }
10418
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010419 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080010420 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080010421 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010422 result.add(nri);
10423 }
10424 return result;
10425 }
10426
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010427 /**
10428 * Compare if the given UID range sets have the same UIDs.
10429 *
10430 */
10431 private boolean isRangeAlreadyInPreferenceList(
10432 @NonNull List<ProfileNetworkPreferenceList.Preference> preferenceList,
10433 @NonNull Set<UidRange> uidRangeSet) {
10434 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
10435 return false;
10436 }
10437 for (ProfileNetworkPreferenceList.Preference pref : preferenceList) {
10438 if (UidRangeUtils.doesRangeSetOverlap(
10439 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
10440 return true;
10441 }
10442 }
10443 return false;
10444 }
10445
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010446 private void handleSetProfileNetworkPreference(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010447 @NonNull final List<ProfileNetworkPreferenceList.Preference> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010448 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010449 for (final ProfileNetworkPreferenceList.Preference preference : preferenceList) {
10450 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
10451 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
10452 }
paulhu74128522021-09-28 02:29:03 +000010453 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
10454 addPerAppDefaultNetworkRequests(
10455 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010456 // Finally, rematch.
10457 rematchAllNetworksAndRequests();
10458
10459 if (null != listener) {
10460 try {
10461 listener.onComplete();
10462 } catch (RemoteException e) {
10463 loge("Listener for setProfileNetworkPreference has died");
10464 }
10465 }
10466 }
10467
paulhu51f77dc2021-06-07 02:34:20 +000010468 @VisibleForTesting
10469 @NonNull
10470 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
10471 @NonNull final Set<Integer> uids) {
10472 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10473 if (uids.size() == 0) {
10474 // Should not create NetworkRequestInfo if no preferences. Without uid range in
10475 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
10476 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
10477 return nris;
10478 }
10479
10480 final List<NetworkRequest> requests = new ArrayList<>();
10481 // The NRI should be comprised of two layers:
10482 // - The request for the mobile network preferred.
10483 // - The request for the default network, for fallback.
10484 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090010485 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000010486 requests.add(createDefaultInternetRequestForTransport(
10487 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10488 final Set<UidRange> ranges = new ArraySet<>();
10489 for (final int uid : uids) {
10490 ranges.add(new UidRange(uid, uid));
10491 }
10492 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080010493 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080010494 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000010495 return nris;
10496 }
10497
10498 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000010499 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000010500 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
10501 addPerAppDefaultNetworkRequests(
10502 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000010503 // Finally, rematch.
10504 rematchAllNetworksAndRequests();
10505 }
10506
James Mattis45d81842021-01-10 14:24:24 -080010507 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080010508 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
10509 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080010510 }
10511
10512 /**
10513 * Used by automotive devices to set the network preferences used to direct traffic at an
10514 * application level as per the given OemNetworkPreferences. An example use-case would be an
10515 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
10516 * vehicle via a particular network.
10517 *
10518 * Calling this will overwrite the existing preference.
10519 *
James Mattisda32cfe2021-01-26 16:23:52 -080010520 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090010521 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080010522 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080010523 */
James Mattis47db0582021-01-01 14:13:35 -080010524 @Override
James Mattis45d81842021-01-10 14:24:24 -080010525 public void setOemNetworkPreference(
10526 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010527 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080010528
James Mattisfa270db2021-05-31 17:11:10 -070010529 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10530 // Only bypass the permission/device checks if this is a valid test request.
10531 if (isValidTestOemNetworkPreference(preference)) {
10532 enforceManageTestNetworksPermission();
10533 } else {
10534 enforceAutomotiveDevice();
10535 enforceOemNetworkPreferencesPermission();
10536 validateOemNetworkPreferences(preference);
10537 }
James Mattis45d81842021-01-10 14:24:24 -080010538
James Mattis45d81842021-01-10 14:24:24 -080010539 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
10540 new Pair<>(preference, listener)));
10541 }
10542
James Mattisfa270db2021-05-31 17:11:10 -070010543 /**
10544 * Check the validity of an OEM network preference to be used for testing purposes.
10545 * @param preference the preference to validate
10546 * @return true if this is a valid OEM network preference test request.
10547 */
10548 private boolean isValidTestOemNetworkPreference(
10549 @NonNull final OemNetworkPreferences preference) {
10550 // Allow for clearing of an existing OemNetworkPreference used for testing.
10551 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
10552 // changes after this check is complete. This is an unlikely scenario as calling of this API
10553 // is controlled by the OEM therefore the added complexity is not worth adding given those
10554 // circumstances. That said, it is an edge case to be aware of hence this comment.
10555 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
10556 && isTestOemNetworkPreference(mOemNetworkPreferences);
10557 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
10558 }
10559
10560 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
10561 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
10562 return prefMap.size() == 1
10563 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
10564 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
10565 }
10566
James Mattis45d81842021-01-10 14:24:24 -080010567 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
10568 for (@OemNetworkPreferences.OemNetworkPreference final int pref
10569 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070010570 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
10571 throw new IllegalArgumentException(
10572 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
10573 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080010574 }
10575 }
10576 }
10577
10578 private void handleSetOemNetworkPreference(
10579 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010580 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080010581 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10582 if (DBG) {
10583 log("set OEM network preferences :" + preference.toString());
10584 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010585
James Mattiscb1e0362021-04-06 17:07:42 -070010586 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000010587 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
10588 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
10589 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080010590 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080010591
10592 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010593 try {
10594 listener.onComplete();
10595 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080010596 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010597 }
James Mattis45d81842021-01-10 14:24:24 -080010598 }
10599 }
10600
paulhu74128522021-09-28 02:29:03 +000010601 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080010602 // Skip the requests which are set by other network preference. Because the uid range rules
10603 // should stay in netd.
10604 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080010605 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080010606 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080010607 }
10608
James Mattis3ce3d3c2021-02-09 18:18:28 -080010609 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
10610 ensureRunningOnConnectivityServiceThread();
10611 mDefaultNetworkRequests.addAll(nris);
10612 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
10613 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080010614 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000010615 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
10616 nrisToRegister.addAll(
10617 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
10618 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010619 }
10620
10621 /**
10622 * All current requests that are tracking the default network need to be assessed as to whether
10623 * or not the current set of per-application default requests will be changing their default
10624 * network. If so, those requests will need to be updated so that they will send callbacks for
10625 * default network changes at the appropriate time. Additionally, those requests tracking the
10626 * default that were previously updated by this flow will need to be reassessed.
10627 * @return the nris which will need to be updated.
10628 */
10629 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
10630 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
10631 // Get the distinct nris to check since for multilayer requests, it is possible to have the
10632 // same nri in the map's values for each of its NetworkRequest objects.
10633 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080010634 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010635 // Include this nri if it is currently being tracked.
10636 if (isPerAppTrackedNri(nri)) {
10637 defaultCallbackRequests.add(nri);
10638 continue;
10639 }
10640 // We only track callbacks for requests tracking the default.
10641 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
10642 continue;
10643 }
10644 // Include this nri if it will be tracked by the new per-app default requests.
10645 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010646 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080010647 if (isNriGoingToBeTracked) {
10648 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080010649 }
10650 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080010651 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080010652 }
10653
James Mattis3ce3d3c2021-02-09 18:18:28 -080010654 /**
10655 * Create nris for those network requests that are currently tracking the default network that
10656 * are being controlled by a per-application default.
10657 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
10658 * foundation when creating the nri. Important items include the calling uid's original
10659 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
10660 * requests are assumed to have already been validated as needing to be updated.
10661 * @return the Set of nris to use when registering network requests.
10662 */
10663 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
10664 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
10665 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
10666 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
10667 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010668 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010669
Chalard Jean9473c982021-07-29 20:03:04 +090010670 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080010671 if (trackingNri == mDefaultRequest) {
10672 callbackRequestsToRegister.add(new NetworkRequestInfo(
10673 callbackRequest,
10674 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
10675 continue;
10676 }
10677
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010678 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010679 callbackRequestsToRegister.add(new NetworkRequestInfo(
10680 callbackRequest,
10681 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010682 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090010683 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080010684 }
10685 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080010686 }
10687
Chalard Jean17215832021-03-01 14:06:28 +090010688 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
10689 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090010690 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010691 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090010692 }
10693 }
10694
James Mattis45d81842021-01-10 14:24:24 -080010695 /**
10696 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
10697 */
10698 @VisibleForTesting
10699 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010700 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080010701 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010702 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080010703 final SparseArray<Set<Integer>> uids =
10704 createUidsFromOemNetworkPreferences(preference);
10705 for (int i = 0; i < uids.size(); i++) {
10706 final int key = uids.keyAt(i);
10707 final Set<Integer> value = uids.valueAt(i);
10708 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
10709 // No need to add an nri without any requests.
10710 if (0 == nri.mRequests.size()) {
10711 continue;
10712 }
10713 nris.add(nri);
10714 }
10715
10716 return nris;
10717 }
10718
10719 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
10720 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070010721 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080010722 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080010723 final List<UserHandle> users =
10724 mContext.getSystemService(UserManager.class).getUserHandles(true);
10725 if (null == users || users.size() == 0) {
10726 if (VDBG || DDBG) {
10727 log("No users currently available for setting the OEM network preference.");
10728 }
James Mattisb6b6a432021-06-01 22:30:36 -070010729 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080010730 }
James Mattis45d81842021-01-10 14:24:24 -080010731 for (final Map.Entry<String, Integer> entry :
10732 preference.getNetworkPreferences().entrySet()) {
10733 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070010734 // Add the rules for all users as this policy is device wide.
10735 for (final UserHandle user : users) {
10736 try {
10737 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
10738 if (!prefToUids.contains(pref)) {
10739 prefToUids.put(pref, new ArraySet<>());
10740 }
10741 prefToUids.get(pref).add(uid);
10742 } catch (PackageManager.NameNotFoundException e) {
10743 // Although this may seem like an error scenario, it is ok that uninstalled
10744 // packages are sent on a network preference as the system will watch for
10745 // package installations associated with this network preference and update
10746 // accordingly. This is done to minimize race conditions on app install.
10747 continue;
James Mattis45d81842021-01-10 14:24:24 -080010748 }
James Mattis45d81842021-01-10 14:24:24 -080010749 }
10750 }
James Mattisb6b6a432021-06-01 22:30:36 -070010751 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080010752 }
10753
10754 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10755 @OemNetworkPreferences.OemNetworkPreference final int preference,
10756 @NonNull final Set<Integer> uids) {
10757 final List<NetworkRequest> requests = new ArrayList<>();
10758 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10759 switch (preference) {
10760 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10761 requests.add(createUnmeteredNetworkRequest());
10762 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070010763 requests.add(createDefaultInternetRequestForTransport(
10764 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080010765 break;
10766 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10767 requests.add(createUnmeteredNetworkRequest());
10768 requests.add(createOemPaidNetworkRequest());
10769 break;
10770 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10771 requests.add(createOemPaidNetworkRequest());
10772 break;
10773 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10774 requests.add(createOemPrivateNetworkRequest());
10775 break;
James Mattisfa270db2021-05-31 17:11:10 -070010776 case OEM_NETWORK_PREFERENCE_TEST:
10777 requests.add(createUnmeteredNetworkRequest());
10778 requests.add(createTestNetworkRequest());
10779 requests.add(createDefaultRequest());
10780 break;
10781 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
10782 requests.add(createTestNetworkRequest());
10783 break;
James Mattis45d81842021-01-10 14:24:24 -080010784 default:
10785 // This should never happen.
10786 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10787 + " called with invalid preference of " + preference);
10788 }
10789
James Mattisfa270db2021-05-31 17:11:10 -070010790 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090010791 for (final int uid : uids) {
10792 ranges.add(new UidRange(uid, uid));
10793 }
10794 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080010795 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080010796 }
10797
10798 private NetworkRequest createUnmeteredNetworkRequest() {
10799 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10800 .addCapability(NET_CAPABILITY_NOT_METERED)
10801 .addCapability(NET_CAPABILITY_VALIDATED);
10802 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10803 }
10804
10805 private NetworkRequest createOemPaidNetworkRequest() {
10806 // NET_CAPABILITY_OEM_PAID is a restricted capability.
10807 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10808 .addCapability(NET_CAPABILITY_OEM_PAID)
10809 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10810 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10811 }
10812
10813 private NetworkRequest createOemPrivateNetworkRequest() {
10814 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
10815 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10816 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
10817 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10818 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10819 }
10820
10821 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070010822 final NetworkCapabilities netcap = new NetworkCapabilities();
10823 netcap.addCapability(NET_CAPABILITY_INTERNET);
10824 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
10825 return netcap;
10826 }
10827
10828 private NetworkRequest createTestNetworkRequest() {
10829 final NetworkCapabilities netcap = new NetworkCapabilities();
10830 netcap.clearAll();
10831 netcap.addTransportType(TRANSPORT_TEST);
10832 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080010833 }
James Mattis47db0582021-01-01 14:13:35 -080010834 }
markchien738ad912021-12-09 18:15:45 +080010835
10836 @Override
10837 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
10838 enforceNetworkStackOrSettingsPermission();
10839
10840 try {
10841 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080010842 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080010843 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080010844 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080010845 }
Wayne Ma2fde98c2022-01-17 18:04:05 +080010846 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080010847 throw new IllegalStateException(e);
10848 }
10849 }
10850
10851 @Override
10852 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
10853 enforceNetworkStackOrSettingsPermission();
10854
10855 try {
10856 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080010857 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080010858 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080010859 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080010860 }
Wayne Ma2fde98c2022-01-17 18:04:05 +080010861 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080010862 throw new IllegalStateException(e);
10863 }
10864 }
markchiene1561fa2021-12-09 22:00:56 +080010865
10866 @Override
10867 public void updateFirewallRule(final int chain, final int uid, final boolean allow) {
10868 enforceNetworkStackOrSettingsPermission();
10869
10870 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080010871 mBpfNetMaps.setUidRule(chain, uid,
markchiene1561fa2021-12-09 22:00:56 +080010872 allow ? INetd.FIREWALL_RULE_ALLOW : INetd.FIREWALL_RULE_DENY);
Wayne Ma2fde98c2022-01-17 18:04:05 +080010873 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080010874 throw new IllegalStateException(e);
10875 }
10876 }
markchien98a6f952022-01-13 23:43:53 +080010877
10878 @Override
10879 public void setFirewallChainEnabled(final int chain, final boolean enable) {
10880 enforceNetworkStackOrSettingsPermission();
10881
10882 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080010883 mBpfNetMaps.setChildChain(chain, enable);
10884 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080010885 throw new IllegalStateException(e);
10886 }
10887 }
10888
markchien00a0bed2022-01-13 23:46:13 +080010889 @Override
10890 public void replaceFirewallChain(final int chain, final int[] uids) {
10891 enforceNetworkStackOrSettingsPermission();
10892
10893 try {
10894 switch (chain) {
10895 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
Wayne Ma2fde98c2022-01-17 18:04:05 +080010896 mBpfNetMaps.replaceUidChain("fw_dozable", true /* isAllowList */, uids);
markchien00a0bed2022-01-13 23:46:13 +080010897 break;
10898 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Wayne Ma2fde98c2022-01-17 18:04:05 +080010899 mBpfNetMaps.replaceUidChain("fw_standby", false /* isAllowList */, uids);
markchien00a0bed2022-01-13 23:46:13 +080010900 break;
10901 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
Wayne Ma2fde98c2022-01-17 18:04:05 +080010902 mBpfNetMaps.replaceUidChain("fw_powersave", true /* isAllowList */, uids);
markchien00a0bed2022-01-13 23:46:13 +080010903 break;
10904 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
Wayne Ma2fde98c2022-01-17 18:04:05 +080010905 mBpfNetMaps.replaceUidChain("fw_restricted", true /* isAllowList */, uids);
markchien00a0bed2022-01-13 23:46:13 +080010906 break;
10907 default:
10908 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
10909 + chain);
10910 }
Wayne Ma2fde98c2022-01-17 18:04:05 +080010911 } catch (ServiceSpecificException e) {
markchien00a0bed2022-01-13 23:46:13 +080010912 throw new IllegalStateException(e);
10913 }
10914 }
markchien9c806112022-01-11 23:28:23 +080010915
10916 @Override
10917 public void swapActiveStatsMap() {
10918 enforceNetworkStackOrSettingsPermission();
10919 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080010920 mBpfNetMaps.swapActiveStatsMap();
10921 } catch (ServiceSpecificException e) {
markchien9c806112022-01-11 23:28:23 +080010922 throw new IllegalStateException(e);
10923 }
10924 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070010925}