blob: 198190a5452b69ec4ca2080bda0bf48ba48d4bd9 [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 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001342 * @see CarrierPrivilegeAuthenticator
1343 */
1344 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1345 @NonNull final Context context, @NonNull final TelephonyManager tm) {
1346 if (SdkLevel.isAtLeastT()) {
1347 return new CarrierPrivilegeAuthenticator(context, tm);
1348 } else {
1349 return null;
1350 }
1351 }
1352
1353 /**
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001354 * @see DeviceConfigUtils#isFeatureEnabled
1355 */
1356 public boolean isFeatureEnabled(Context context, String name, boolean defaultEnabled) {
1357 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, name,
1358 TETHERING_MODULE_NAME, defaultEnabled);
1359 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001360
1361 /**
1362 * Get the BpfNetMaps implementation to use in ConnectivityService.
1363 * @param netd
1364 * @return BpfNetMaps implementation.
1365 */
1366 public BpfNetMaps getBpfNetMaps(INetd netd) {
1367 return new BpfNetMaps(netd);
1368 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001369 }
1370
junyulaie7c7d2a2021-01-26 15:29:15 +08001371 public ConnectivityService(Context context) {
1372 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001373 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1374 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001375 }
1376
1377 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001378 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1379 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001380 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001381
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001382 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001383 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001384 mSystemProperties = mDeps.getSystemProperties();
1385 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001386 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001387 mResources = deps.getResources(mContext);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001388 mNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_UID);
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09001389 mSystemNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001390
Hugo Benichi208c0102016-07-28 17:53:06 +09001391 mMetricsLog = logger;
Chalard Jean96a4f4b2019-12-10 22:16:53 +09001392 mNetworkRanker = new NetworkRanker();
James Mattis45d81842021-01-10 14:24:24 -08001393 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1394 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001395 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001396 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001397 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001398 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1399 mDefaultNetworkRequests.add(mDefaultRequest);
1400 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001401
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001402 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001403 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001404
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001405 // The default WiFi request is a background request so that apps using WiFi are
1406 // migrated to a better network (typically ethernet) when one comes up, instead
1407 // of staying on WiFi forever.
1408 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1409 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1410
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001411 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1412 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1413 NetworkRequest.Type.BACKGROUND_REQUEST);
1414
Chalard Jean0702f982021-09-16 21:50:07 +09001415 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1416 // TODO: Consider making the timer customizable.
1417 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1418 mCellularRadioTimesharingCapable =
1419 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1420
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001421 mHandlerThread = mDeps.makeHandlerThread();
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001422 mHandlerThread.start();
1423 mHandler = new InternalHandler(mHandlerThread.getLooper());
1424 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001425 mConnectivityDiagnosticsHandler =
1426 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001427
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001428 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001429 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001430
junyulaie7c7d2a2021-01-26 15:29:15 +08001431 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001432 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001433 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001434 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001435
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001436 mNetd = netd;
Wayne Ma2fde98c2022-01-17 18:04:05 +08001437 mBpfNetMaps = mDeps.getBpfNetMaps(netd);
Wink Saville32506bc2013-06-29 21:10:57 -07001438 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001439 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001440 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001441 mCarrierPrivilegeAuthenticator =
1442 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001443
Sudheer Shanka9967d462021-03-18 19:09:25 +00001444 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001445 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1446 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001447 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001448
1449 final PowerManager powerManager = (PowerManager) context.getSystemService(
1450 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001451 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001452 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001453
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001454 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1455 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001456 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001457 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001458 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001459 mProtectedNetworks.add(p);
1460 } else {
1461 if (DBG) loge("Ignoring protectedNetwork " + p);
1462 }
1463 }
1464
soma, kawata29444ae2019-05-23 09:30:40 +09001465 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1466
Wayne Ma2fde98c2022-01-17 18:04:05 +08001467 mPermissionMonitor = new PermissionMonitor(mContext, mNetd, mBpfNetMaps);
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -07001468
James Mattis02220e22021-03-13 19:27:21 -08001469 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001470 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001471 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001472 final IntentFilter userIntentFilter = new IntentFilter();
1473 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1474 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1475 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1476 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001477
James Mattis02220e22021-03-13 19:27:21 -08001478 // Listen to package add/removes for netd
1479 final IntentFilter packageIntentFilter = new IntentFilter();
1480 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1481 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1482 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1483 packageIntentFilter.addDataScheme("package");
1484 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001485 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001486
lucaslind5c2d072021-02-20 18:59:47 +08001487 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001488
lucaslin66f44212021-02-23 01:12:55 +08001489 mNetdCallback = new NetdCallback();
1490 try {
1491 mNetd.registerUnsolicitedEventListener(mNetdCallback);
1492 } catch (RemoteException | ServiceSpecificException e) {
1493 loge("Error registering event listener :" + e);
1494 }
1495
Erik Kline05f2b402015-04-30 12:58:40 +09001496 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1497 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001498
junyulai7e06ad42019-03-04 22:45:36 +08001499 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001500 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001501 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001502
1503 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001504 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001505 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1506 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001507 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001508 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1509 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001510
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001511 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001512 mContext, mHandler, () -> updateAvoidBadWifi());
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001513 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001514
Chiachang Wangc1215d32020-10-20 15:38:58 +08001515 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001516 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001517
Chalard Jean28018572020-12-21 18:36:52 +09001518 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1519 // request that doesn't allow fallback to the default network. It should never be visible
1520 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1521 // arguments like the handler or the DnsResolver.
1522 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001523 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001524 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001525 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001526 new LinkProperties(), new NetworkCapabilities(),
1527 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001528 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1529 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001530
1531 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001532 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1533 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1534 // Even if it could, running on S would at least require mocking out the BPF map,
1535 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1536 // the bpf syscall. http://aosp/1907693
1537 if (SdkLevel.isAtLeastT()) {
1538 mDscpPolicyTracker = new DscpPolicyTracker();
1539 }
Tyler Wear72388212021-09-09 14:49:02 -07001540 } catch (ErrnoException e) {
1541 loge("Unable to create DscpPolicyTracker");
1542 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001543 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001544
Chalard Jean46adcf32018-04-18 20:18:38 +09001545 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001546 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1547 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001548 }
1549
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001550 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1551 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001552 final NetworkCapabilities netCap = new NetworkCapabilities();
1553 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001554 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001555 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001556 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001557 return netCap;
1558 }
1559
James Mattis45d81842021-01-10 14:24:24 -08001560 private NetworkRequest createDefaultRequest() {
1561 return createDefaultInternetRequestForTransport(
1562 TYPE_NONE, NetworkRequest.Type.REQUEST);
1563 }
1564
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001565 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001566 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001567 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001568 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001569 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001570 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001571 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001572 netCap.addTransportType(transportType);
1573 }
James Mattis45d81842021-01-10 14:24:24 -08001574 return createNetworkRequest(type, netCap);
1575 }
1576
1577 private NetworkRequest createNetworkRequest(
1578 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001579 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001580 }
1581
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001582 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1583 NetworkRequest.Type type) {
1584 final NetworkCapabilities netCap = new NetworkCapabilities();
1585 netCap.clearAll();
1586 netCap.addCapability(capability);
1587 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1588 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1589 }
1590
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001591 // Used only for testing.
1592 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001593 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001594 // changing ContentResolver to make registerContentObserver non-final).
1595 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1596 // by subclassing SettingsObserver.
1597 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001598 void updateAlwaysOnNetworks() {
1599 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001600 }
1601
Erik Kline9a62f012018-03-21 07:18:33 -07001602 // See FakeSettingsProvider comment above.
1603 @VisibleForTesting
1604 void updatePrivateDnsSettings() {
1605 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1606 }
1607
paulhu51f77dc2021-06-07 02:34:20 +00001608 @VisibleForTesting
1609 void updateMobileDataPreferredUids() {
1610 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1611 }
1612
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09001613 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, int id) {
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001614 final boolean enable = mContext.getResources().getBoolean(id);
1615 handleAlwaysOnNetworkRequest(networkRequest, enable);
1616 }
1617
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001618 private void handleAlwaysOnNetworkRequest(
1619 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001620 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001621 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001622 handleAlwaysOnNetworkRequest(networkRequest, enable);
1623 }
1624
1625 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001626 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001627 if (enable == isEnabled) {
1628 return; // Nothing to do.
1629 }
1630
1631 if (enable) {
1632 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001633 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001634 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001635 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001636 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001637 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1638 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001639 }
1640 }
1641
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001642 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001643 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1644 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1645 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1646 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001647 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1648 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001649 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001650 }
1651
paulhu51f77dc2021-06-07 02:34:20 +00001652 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001653 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001654 private void registerSettingsCallbacks() {
1655 // Watch for global HTTP proxy changes.
1656 mSettingsObserver.observe(
1657 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1658 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1659
1660 // Watch for whether or not to keep mobile data always on.
1661 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001662 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001663 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1664
1665 // Watch for whether or not to keep wifi always on.
1666 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001667 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001668 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001669
1670 // Watch for mobile data preferred uids changes.
1671 mSettingsObserver.observe(
1672 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1673 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001674 }
1675
Erik Kline31b4a9e2018-01-11 21:07:29 +09001676 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001677 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1678 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001679 }
1680 }
1681
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001682 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001683 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1684 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001685 return mNextNetworkRequestId++;
1686 }
1687
junyulai74f9a8b2018-06-13 15:00:37 +08001688 @VisibleForTesting
1689 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001690 if (network == null) {
1691 return null;
1692 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001693 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001694 }
1695
1696 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001697 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001698 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001699 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001700 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001701
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001702 // TODO: determine what to do when more than one VPN applies to |uid|.
1703 private NetworkAgentInfo getVpnForUid(int uid) {
1704 synchronized (mNetworkForNetId) {
1705 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1706 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
1707 if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) {
1708 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001709 }
1710 }
1711 }
1712 return null;
1713 }
1714
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001715 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001716 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001717 final NetworkAgentInfo nai = getVpnForUid(uid);
1718 if (nai != null) return nai.declaredUnderlyingNetworks;
1719 return null;
1720 }
1721
Lorenzo Colittia7574052021-01-19 01:33:05 +09001722 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001723 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001724
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001725 final Network[] networks = getVpnUnderlyingNetworks(uid);
1726 if (networks != null) {
1727 // getUnderlyingNetworks() returns:
1728 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1729 // empty array => the VPN explicitly said "no default network".
1730 // non-empty array => the VPN specified one or more default networks; we use the
1731 // first one.
1732 if (networks.length > 0) {
1733 nai = getNetworkAgentInfoForNetwork(networks[0]);
1734 } else {
1735 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001736 }
1737 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001738 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001739 }
1740
1741 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001742 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001743 */
paulhu7aeba372020-12-30 00:42:19 +08001744 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1745 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001746 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001747 if (ignoreBlocked) {
1748 return false;
1749 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001750 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001751 final long ident = Binder.clearCallingIdentity();
1752 try {
1753 final boolean metered = nc == null ? true : nc.isMetered();
1754 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1755 } finally {
1756 Binder.restoreCallingIdentity(ident);
1757 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001758 }
1759
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001760 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001761 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1762 return;
1763 }
Hugo Benichi47011212017-03-30 10:46:05 +09001764 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001765 synchronized (mBlockedAppUids) {
1766 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001767 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001768 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001769 blocked = false;
1770 } else {
1771 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001772 }
1773 }
Hugo Benichi47011212017-03-30 10:46:05 +09001774 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1775 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1776 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001777 }
1778
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001779 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001780 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1781 return;
1782 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001783 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001784 final int requestId = nri.getActiveRequest() != null
1785 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001786 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001787 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001788 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001789 }
1790
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001791 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001792 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001793 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001794 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001795 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001796 @NonNull
1797 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1798 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001799 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1800 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1801 // but only exists if an app asks about them or requests them. Ensure the requesting app
1802 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001803 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001804 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1805 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1806 null /* extraInfo */);
1807 }
1808 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001809 return filtered;
1810 }
1811
1812 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1813 boolean ignoreBlocked) {
1814 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1815 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001816 }
1817
1818 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001819 * Return NetworkInfo for the active (i.e., connected) network interface.
1820 * It is assumed that at most one network is active at a time. If more
1821 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001822 * @return the info for the active network, or {@code null} if none is
1823 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001824 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001825 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001826 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001827 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001828 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001829 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1830 if (nai == null) return null;
1831 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1832 maybeLogBlockedNetworkInfo(networkInfo, uid);
1833 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001834 }
1835
Paul Jensen1f567382015-02-13 14:18:39 -05001836 @Override
1837 public Network getActiveNetwork() {
1838 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001839 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00001840 }
1841
1842 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001843 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001844 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001845 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001846 }
1847
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001848 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001849 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1850 if (vpnNai != null) {
1851 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1852 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1853 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09001854 }
Paul Jensen1f567382015-02-13 14:18:39 -05001855 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001856
James Mattis2516da32021-01-31 17:06:19 -08001857 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001858 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1859 ignoreBlocked)) {
1860 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001861 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001862 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05001863 }
1864
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001865 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001866 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001867 PermissionUtils.enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001868 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1869 if (nai == null) return null;
1870 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001871 }
1872
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001873 /** Returns a NetworkInfo object for a network that doesn't exist. */
1874 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1875 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1876 getNetworkTypeName(networkType), "" /* subtypeName */);
1877 info.setIsAvailable(true);
1878 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1879 // background data is restricted.
1880 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1881 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1882 ? DetailedState.BLOCKED
1883 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001884 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1885 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001886 return info;
1887 }
1888
Lorenzo Colittia7574052021-01-19 01:33:05 +09001889 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001890 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1891 return null;
1892 }
1893 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001894 if (nai == null) {
1895 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001896 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001897 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1898 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001899 }
1900
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001901 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001902 public NetworkInfo getNetworkInfo(int networkType) {
1903 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001904 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001905 if (getVpnUnderlyingNetworks(uid) != null) {
1906 // A VPN is active, so we may need to return one of its underlying networks. This
1907 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09001908 // getNetworkAgentInfoForUid.
1909 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1910 if (nai == null) return null;
1911 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1912 if (networkInfo.getType() == networkType) {
1913 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001914 }
1915 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001916 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001917 }
1918
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001919 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001920 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001921 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001922 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001923 if (nai == null) return null;
1924 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001925 }
1926
1927 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001928 public NetworkInfo[] getAllNetworkInfo() {
1929 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08001930 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04001931 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1932 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001933 NetworkInfo info = getNetworkInfo(networkType);
1934 if (info != null) {
1935 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001936 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001937 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001938 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001939 }
1940
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001941 @Override
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001942 public Network getNetworkForType(int networkType) {
1943 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001944 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1945 return null;
1946 }
1947 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1948 if (nai == null) {
1949 return null;
1950 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001951 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001952 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
1953 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001954 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001955 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001956 }
1957
1958 @Override
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001959 public Network[] getAllNetworks() {
1960 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001961 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04001962 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001963 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04001964 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001965 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04001966 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001967 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001968 }
1969
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001970 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08001971 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001972 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001973 // The basic principle is: if an app's traffic could possibly go over a
1974 // network, without the app doing anything multinetwork-specific,
1975 // (hence, by "default"), then include that network's capabilities in
1976 // the array.
1977 //
1978 // In the normal case, app traffic only goes over the system's default
1979 // network connection, so that's the only network returned.
1980 //
1981 // With a VPN in force, some app traffic may go into the VPN, and thus
1982 // over whatever underlying networks the VPN specifies, while other app
1983 // traffic may go over the system default network (e.g.: a split-tunnel
1984 // VPN, or an app disallowed by the VPN), so the set of networks
1985 // returned includes the VPN's underlying networks and the system
1986 // default.
1987 enforceAccessPermission();
1988
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001989 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001990
James Mattis2516da32021-01-31 17:06:19 -08001991 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
1992 if (!nri.isBeingSatisfied()) {
1993 continue;
1994 }
1995 final NetworkAgentInfo nai = nri.getSatisfier();
1996 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
1997 if (null != nc
1998 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
1999 && !result.containsKey(nai.network)) {
2000 result.put(
2001 nai.network,
2002 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002003 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002004 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2005 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002006 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002007 }
2008
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002009 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002010 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002011 if (null != networks) {
2012 for (final Network network : networks) {
2013 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2014 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002015 result.put(
2016 network,
2017 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002018 nc,
2019 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002020 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002021 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002022 }
2023 }
2024 }
2025
2026 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2027 out = result.values().toArray(out);
2028 return out;
2029 }
2030
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002031 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002032 public boolean isNetworkSupported(int networkType) {
2033 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002034 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002035 }
2036
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002037 /**
2038 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002039 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002040 * @return the ip properties for the active network, or {@code null} if
2041 * none is active
2042 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002043 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002044 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002045 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002046 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002047 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2048 if (nai == null) return null;
2049 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002050 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002051 }
2052
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002053 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002054 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002055 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002056 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002057 final LinkProperties lp = getLinkProperties(nai);
2058 if (lp == null) return null;
2059 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002060 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002061 }
2062
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002063 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002064 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002065 public LinkProperties getLinkProperties(Network network) {
2066 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002067 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2068 if (lp == null) return null;
2069 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002070 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002071 }
2072
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002073 @Nullable
2074 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002075 if (nai == null) {
2076 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002077 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002078 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002079 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002080 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002081 }
2082
Qingxi Lib2748102020-01-08 12:51:49 -08002083 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2084 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2085 }
2086
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002087 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002088 if (nai == null) return null;
2089 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002090 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002091 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002092 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002093 }
2094
2095 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002096 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2097 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002098 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002099 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002100 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002101 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002102 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002103 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002104 }
2105
Qingxi Libb8da982020-01-17 17:54:27 -08002106 @VisibleForTesting
2107 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002108 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002109 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002110 if (!checkSettingsPermission(callerPid, callerUid)) {
2111 newNc.setUids(null);
2112 newNc.setSSID(null);
lucaslin6adf5ac2021-10-19 15:04:56 +08002113 newNc.setUnderlyingNetworks(null);
Chalard Jean46adcf32018-04-18 20:18:38 +09002114 }
Etan Cohen107ae952018-12-30 17:59:59 -08002115 if (newNc.getNetworkSpecifier() != null) {
2116 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2117 }
Cody Kesting5ab1f552020-03-16 18:15:28 -07002118 newNc.setAdministratorUids(new int[0]);
Benedict Wong53de25f2021-03-24 14:01:51 -07002119 if (!checkAnyPermissionOf(
2120 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09002121 newNc.setAccessUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002122 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002123 }
Qingxi Libb8da982020-01-17 17:54:27 -08002124
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002125 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002126 }
2127
Roshan Pius98f59ec2021-02-23 08:47:39 -08002128 /**
2129 * Wrapper used to cache the permission check results performed for the corresponding
2130 * app. This avoid performing multiple permission checks for different fields in
2131 * NetworkCapabilities.
2132 * Note: This wrapper does not support any sort of invalidation and thus must not be
2133 * persistent or long-lived. It may only be used for the time necessary to
2134 * compute the redactions required by one particular NetworkCallback or
2135 * synchronous call.
2136 */
2137 private class RedactionPermissionChecker {
2138 private final int mCallingPid;
2139 private final int mCallingUid;
2140 @NonNull private final String mCallingPackageName;
2141 @Nullable private final String mCallingAttributionTag;
2142
2143 private Boolean mHasLocationPermission = null;
2144 private Boolean mHasLocalMacAddressPermission = null;
2145 private Boolean mHasSettingsPermission = null;
2146
2147 RedactionPermissionChecker(int callingPid, int callingUid,
2148 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2149 mCallingPid = callingPid;
2150 mCallingUid = callingUid;
2151 mCallingPackageName = callingPackageName;
2152 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002153 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002154
2155 private boolean hasLocationPermissionInternal() {
2156 final long token = Binder.clearCallingIdentity();
2157 try {
2158 return mLocationPermissionChecker.checkLocationPermission(
2159 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2160 null /* message */);
2161 } finally {
2162 Binder.restoreCallingIdentity(token);
2163 }
2164 }
2165
2166 /**
2167 * Returns whether the app holds location permission or not (might return cached result
2168 * if the permission was already checked before).
2169 */
2170 public boolean hasLocationPermission() {
2171 if (mHasLocationPermission == null) {
2172 // If there is no cached result, perform the check now.
2173 mHasLocationPermission = hasLocationPermissionInternal();
2174 }
2175 return mHasLocationPermission;
2176 }
2177
2178 /**
2179 * Returns whether the app holds local mac address permission or not (might return cached
2180 * result if the permission was already checked before).
2181 */
2182 public boolean hasLocalMacAddressPermission() {
2183 if (mHasLocalMacAddressPermission == null) {
2184 // If there is no cached result, perform the check now.
2185 mHasLocalMacAddressPermission =
2186 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2187 }
2188 return mHasLocalMacAddressPermission;
2189 }
2190
2191 /**
2192 * Returns whether the app holds settings permission or not (might return cached
2193 * result if the permission was already checked before).
2194 */
2195 public boolean hasSettingsPermission() {
2196 if (mHasSettingsPermission == null) {
2197 // If there is no cached result, perform the check now.
2198 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2199 }
2200 return mHasSettingsPermission;
2201 }
2202 }
2203
2204 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2205 @NetworkCapabilities.NetCapability long redaction) {
2206 return (redactions & redaction) != 0;
2207 }
2208
2209 /**
2210 * Use the provided |applicableRedactions| to check the receiving app's
2211 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2212 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2213 * before being sent to the corresponding app.
2214 */
2215 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2216 @NetworkCapabilities.RedactionType long applicableRedactions,
2217 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2218 boolean includeLocationSensitiveInfo) {
2219 long redactions = applicableRedactions;
2220 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2221 if (includeLocationSensitiveInfo
2222 && redactionPermissionChecker.hasLocationPermission()) {
2223 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2224 }
2225 }
2226 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2227 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2228 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2229 }
2230 }
2231 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2232 if (redactionPermissionChecker.hasSettingsPermission()) {
2233 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2234 }
2235 }
2236 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002237 }
2238
Qingxi Lib2748102020-01-08 12:51:49 -08002239 @VisibleForTesting
2240 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002241 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002242 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002243 int callingPid, int callingUid, @NonNull String callingPkgName,
2244 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002245 if (nc == null) {
2246 return null;
2247 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002248 // Avoid doing location permission check if the transport info has no location sensitive
2249 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002250 final RedactionPermissionChecker redactionPermissionChecker =
2251 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2252 callingAttributionTag);
2253 final long redactions = retrieveRequiredRedactions(
2254 nc.getApplicableRedactions(), redactionPermissionChecker,
2255 includeLocationSensitiveInfo);
2256 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002257 // Reset owner uid if not destined for the owner app.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002258 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002259 newNc.setOwnerUid(INVALID_UID);
2260 return newNc;
2261 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002262 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2263 if (nc.hasTransport(TRANSPORT_VPN)) {
2264 // Owner UIDs already checked above. No need to re-check.
2265 return newNc;
2266 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002267 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2268 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002269 // compatibility for older apps.
2270 if (!includeLocationSensitiveInfo
2271 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002272 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002273 newNc.setOwnerUid(INVALID_UID);
2274 return newNc;
2275 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002276 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002277 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002278 newNc.setOwnerUid(INVALID_UID);
2279 }
Qingxi Lib2748102020-01-08 12:51:49 -08002280 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002281 }
2282
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002283 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2284 LinkProperties lp, int callerPid, int callerUid) {
2285 if (lp == null) return new LinkProperties();
2286
2287 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2288 final boolean needsSanitization =
2289 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2290 if (!needsSanitization) {
2291 return new LinkProperties(lp);
2292 }
2293
2294 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002295 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002296 }
2297
2298 final LinkProperties newLp = new LinkProperties(lp);
2299 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2300 // object gets parceled.
2301 newLp.setCaptivePortalApiUrl(null);
2302 newLp.setCaptivePortalData(null);
2303 return newLp;
2304 }
2305
Roshan Pius08c94fb2020-01-16 12:17:17 -08002306 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2307 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002308 // There is no need to track the effective UID of the request here. If the caller
2309 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002310 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002311 // Unprivileged apps can only pass in null or their own UID.
2312 if (nc.getUids() == null) {
2313 // If the caller passes in null, the callback will also match networks that do not
2314 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2315 // In this case, redact everything in the request immediately. This ensures that the
2316 // app is not able to get any redacted information by filing an unredacted request
2317 // and observing whether the request matches something.
2318 if (nc.getNetworkSpecifier() != null) {
2319 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2320 }
2321 } else {
2322 nc.setSingleUid(callerUid);
2323 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002324 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002325 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002326 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002327
2328 // Clear owner UID; this can never come from an app.
2329 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002330 }
2331
Chalard Jean38354d12018-03-20 19:13:57 +09002332 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002333 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002334 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2335 }
2336 }
2337
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002338 @Override
2339 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2340 enforceAccessPermission();
2341 final int callerUid = Binder.getCallingUid();
2342 final long token = Binder.clearCallingIdentity();
2343 try {
2344 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2345 } finally {
2346 Binder.restoreCallingIdentity(token);
2347 }
2348 }
2349
junyulaiebd15162021-03-03 12:09:05 +08002350 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002351 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002352 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002353 // This contains IMSI details, so make sure the caller is privileged.
paulhudf23d662021-01-25 18:53:17 +08002354 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002355
Serik Beketayev05130302021-01-15 16:47:25 -08002356 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002357 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002358 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2359 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002360 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002361 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002362 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002363 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2364 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002365 }
2366 }
2367 return result.toArray(new NetworkState[result.size()]);
2368 }
2369
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002370 @Override
junyulaiebd15162021-03-03 12:09:05 +08002371 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002372 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002373 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002374 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002375
2376 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2377 for (Network network : getAllNetworks()) {
2378 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Junyu Laiddecb662021-08-17 08:44:36 +00002379 if (nai != null && nai.everConnected) {
junyulaiebd15162021-03-03 12:09:05 +08002380 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2381 // NetworkCapabilities, which may contain UIDs of apps to which the
2382 // network applies. Should the UIDs be cleared so as not to leak or
2383 // interfere ?
2384 result.add(nai.getNetworkStateSnapshot());
2385 }
2386 }
2387 return result;
2388 }
2389
2390 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002391 public boolean isActiveNetworkMetered() {
2392 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002393
Qingxi Lib2748102020-01-08 12:51:49 -08002394 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002395 if (caps != null) {
2396 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2397 } else {
2398 // Always return the most conservative value
2399 return true;
2400 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002401 }
2402
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002403 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002404 * Ensures that the system cannot call a particular method.
2405 */
2406 private boolean disallowedBecauseSystemCaller() {
2407 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002408 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2409 // for devices launched with Q and above. However, existing devices upgrading to Q and
2410 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002411 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002412 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002413 log("This method exists only for app backwards compatibility"
2414 + " and must not be called by system services.");
2415 return true;
2416 }
2417 return false;
2418 }
2419
paulhub2c28682021-08-18 18:35:54 +08002420 private int getAppUid(final String app, final UserHandle user) {
2421 final PackageManager pm =
2422 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2423 final long token = Binder.clearCallingIdentity();
2424 try {
2425 return pm.getPackageUid(app, 0 /* flags */);
2426 } catch (PackageManager.NameNotFoundException e) {
2427 return -1;
2428 } finally {
2429 Binder.restoreCallingIdentity(token);
2430 }
2431 }
2432
2433 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2434 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2435 if (getAppUid(packageName, user) != callingUid) {
2436 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2437 }
2438 }
2439
Lorenzo Colitti23862912018-09-28 11:31:55 +09002440 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002441 * Ensure that a network route exists to deliver traffic to the specified
2442 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002443 * @param networkType the type of the network over which traffic to the
2444 * specified host is to be routed
2445 * @param hostAddress the IP address of the host to which the route is
2446 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002447 * @return {@code true} on success, {@code false} on failure
2448 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002449 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002450 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2451 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002452 if (disallowedBecauseSystemCaller()) {
2453 return false;
2454 }
paulhub2c28682021-08-18 18:35:54 +08002455 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002456 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002457 if (mProtectedNetworks.contains(networkType)) {
paulhu8e96a752019-08-12 16:25:11 +08002458 enforceConnectivityRestrictedNetworksPermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002459 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002460
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002461 InetAddress addr;
2462 try {
2463 addr = InetAddress.getByAddress(hostAddress);
2464 } catch (UnknownHostException e) {
2465 if (DBG) log("requestRouteToHostAddress got " + e.toString());
2466 return false;
2467 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002468
The Android Open Source Project28527d22009-03-03 19:31:44 -08002469 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002470 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002471 return false;
2472 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002473
2474 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2475 if (nai == null) {
2476 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
2477 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2478 } else {
2479 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2480 }
2481 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002482 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002483
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002484 DetailedState netState;
2485 synchronized (nai) {
2486 netState = nai.networkInfo.getDetailedState();
2487 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002488
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002489 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002490 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002491 log("requestRouteToHostAddress on down network "
2492 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002493 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002494 }
2495 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002496 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002497
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002498 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002499 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002500 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002501 LinkProperties lp;
2502 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002503 synchronized (nai) {
2504 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002505 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002506 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002507 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002508 if (DBG) {
2509 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2510 }
Wink Saville32506bc2013-06-29 21:10:57 -07002511 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002512 } finally {
2513 Binder.restoreCallingIdentity(token);
2514 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002515 }
2516
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002517 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002518 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002519 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002520 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002521 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002522 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002523 if (bestRoute.getGateway().equals(addr)) {
2524 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002525 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002526 } else {
2527 // if we will connect to this through another route, add a direct route
2528 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002529 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002530 }
2531 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002532 if (DBG) log("Adding legacy route " + bestRoute +
2533 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002534
2535 final String dst = bestRoute.getDestinationLinkAddress().toString();
2536 final String nextHop = bestRoute.hasGateway()
2537 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002538 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002539 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2540 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002541 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002542 return false;
2543 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002544 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002545 }
2546
paulhu7c0a2e62021-01-08 00:51:49 +08002547 class DnsResolverUnsolicitedEventCallback extends
2548 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002549 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002550 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002551 try {
2552 mHandler.sendMessage(mHandler.obtainMessage(
2553 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002554 new PrivateDnsValidationUpdate(event.netId,
2555 InetAddresses.parseNumericAddress(event.ipAddress),
2556 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002557 } catch (IllegalArgumentException e) {
2558 loge("Error parsing ip address in validation event");
2559 }
2560 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002561
2562 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002563 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2564 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002565 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2566 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2567 // event callback for certain nai. e.g. cellular. Register here to pass to
2568 // NetworkMonitor instead.
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002569 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allow one
2570 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2571 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002572 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002573 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002574 }
2575 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002576
2577 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002578 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2579 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2580 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002581 }
dalyk1720e542018-03-05 12:42:22 -05002582
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002583 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002584 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002585 return this.VERSION;
2586 }
2587
2588 @Override
2589 public String getInterfaceHash() {
2590 return this.HASH;
2591 }
paulhu7c0a2e62021-01-08 00:51:49 +08002592 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002593
2594 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002595 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2596 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002597
paulhu7c0a2e62021-01-08 00:51:49 +08002598 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002599 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002600 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002601 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002602 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002603 }
2604 }
2605
Sudheer Shanka9967d462021-03-18 19:09:25 +00002606 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002607 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002608 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002609 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2610 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002611 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002612 };
2613
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002614 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002615 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002616 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002617 }
2618
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002619 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002620 for (String permission : permissions) {
2621 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002622 return true;
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002623 }
2624 }
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002625 return false;
2626 }
2627
paulhu1a407652019-03-22 16:35:06 +08002628 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2629 for (String permission : permissions) {
2630 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2631 return true;
2632 }
2633 }
2634 return false;
2635 }
2636
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002637 private void enforceAnyPermissionOf(String... permissions) {
2638 if (!checkAnyPermissionOf(permissions)) {
2639 throw new SecurityException("Requires one of the following permissions: "
2640 + String.join(", ", permissions) + ".");
2641 }
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002642 }
2643
Paul Jensen83f5d572014-08-29 09:54:01 -04002644 private void enforceInternetPermission() {
2645 mContext.enforceCallingOrSelfPermission(
2646 android.Manifest.permission.INTERNET,
2647 "ConnectivityService");
2648 }
2649
The Android Open Source Project28527d22009-03-03 19:31:44 -08002650 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002651 mContext.enforceCallingOrSelfPermission(
2652 android.Manifest.permission.ACCESS_NETWORK_STATE,
2653 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002654 }
2655
paulhua6ee2122021-02-22 15:40:43 +08002656 /**
2657 * Performs a strict and comprehensive check of whether a calling package is allowed to
2658 * change the state of network, as the condition differs for pre-M, M+, and
2659 * privileged/preinstalled apps. The caller is expected to have either the
2660 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2661 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2662 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2663 * permission and cannot be revoked. See http://b/23597341
2664 *
2665 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2666 * of this app will be updated to the current time.
2667 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002668 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002669 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2670 == PackageManager.PERMISSION_GRANTED) {
2671 return;
2672 }
2673
2674 if (callingPkg == null) {
2675 throw new SecurityException("Calling package name is null.");
2676 }
2677
2678 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2679 final int uid = mDeps.getCallingUid();
2680 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2681 callingPkg, callingAttributionTag, null /* message */);
2682
2683 if (mode == AppOpsManager.MODE_ALLOWED) {
2684 return;
2685 }
2686
2687 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2688 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2689 return;
2690 }
2691
2692 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2693 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2694 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002695 }
2696
Charles He9369e612017-05-15 17:07:18 +01002697 private void enforceSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002698 enforceAnyPermissionOf(
Charles He9369e612017-05-15 17:07:18 +01002699 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002700 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002701 }
2702
paulhu8e96a752019-08-12 16:25:11 +08002703 private void enforceNetworkFactoryPermission() {
paulhub6ba8e82020-03-04 09:43:41 +08002704 enforceAnyPermissionOf(
paulhu8e96a752019-08-12 16:25:11 +08002705 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002706 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002707 }
2708
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002709 private void enforceNetworkFactoryOrSettingsPermission() {
2710 enforceAnyPermissionOf(
2711 android.Manifest.permission.NETWORK_SETTINGS,
2712 android.Manifest.permission.NETWORK_FACTORY,
2713 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2714 }
2715
2716 private void enforceNetworkFactoryOrTestNetworksPermission() {
2717 enforceAnyPermissionOf(
2718 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2719 android.Manifest.permission.NETWORK_FACTORY,
2720 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2721 }
2722
Chalard Jean9a396cc2018-02-21 18:43:54 +09002723 private boolean checkSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002724 return checkAnyPermissionOf(
2725 android.Manifest.permission.NETWORK_SETTINGS,
2726 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002727 }
2728
2729 private boolean checkSettingsPermission(int pid, int uid) {
2730 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002731 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2732 || PERMISSION_GRANTED == mContext.checkPermission(
2733 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002734 }
2735
paulhu8e96a752019-08-12 16:25:11 +08002736 private void enforceNetworkStackOrSettingsPermission() {
2737 enforceAnyPermissionOf(
2738 android.Manifest.permission.NETWORK_SETTINGS,
2739 android.Manifest.permission.NETWORK_STACK,
2740 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2741 }
2742
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002743 private void enforceNetworkStackSettingsOrSetup() {
2744 enforceAnyPermissionOf(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002745 android.Manifest.permission.NETWORK_SETTINGS,
2746 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002747 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002748 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002749 }
2750
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002751 private void enforceAirplaneModePermission() {
2752 enforceAnyPermissionOf(
2753 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2754 android.Manifest.permission.NETWORK_SETTINGS,
2755 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2756 android.Manifest.permission.NETWORK_STACK,
2757 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2758 }
2759
James Mattis8378aec2021-01-26 14:05:36 -08002760 private void enforceOemNetworkPreferencesPermission() {
2761 mContext.enforceCallingOrSelfPermission(
2762 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2763 "ConnectivityService");
2764 }
2765
James Mattisfa270db2021-05-31 17:11:10 -07002766 private void enforceManageTestNetworksPermission() {
2767 mContext.enforceCallingOrSelfPermission(
2768 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2769 "ConnectivityService");
2770 }
2771
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002772 private boolean checkNetworkStackPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002773 return checkAnyPermissionOf(
2774 android.Manifest.permission.NETWORK_STACK,
2775 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002776 }
2777
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002778 private boolean checkNetworkStackPermission(int pid, int uid) {
2779 return checkAnyPermissionOf(pid, uid,
2780 android.Manifest.permission.NETWORK_STACK,
2781 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2782 }
2783
paulhu1a407652019-03-22 16:35:06 +08002784 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2785 return checkAnyPermissionOf(pid, uid,
2786 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002787 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2788 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002789 }
2790
Hugo Benichibd0cc762016-07-19 15:59:27 +09002791 private void enforceConnectivityRestrictedNetworksPermission() {
2792 try {
2793 mContext.enforceCallingOrSelfPermission(
2794 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2795 "ConnectivityService");
2796 return;
2797 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
paulhu8e96a752019-08-12 16:25:11 +08002798 // TODO: Remove this fallback check after all apps have declared
2799 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2800 mContext.enforceCallingOrSelfPermission(
2801 android.Manifest.permission.CONNECTIVITY_INTERNAL,
2802 "ConnectivityService");
Hugo Benichibd0cc762016-07-19 15:59:27 +09002803 }
2804
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002805 private void enforceKeepalivePermission() {
Lorenzo Colittif25beee2015-09-08 13:21:48 +09002806 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002807 }
2808
Roshan Pius98f59ec2021-02-23 08:47:39 -08002809 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2810 return PERMISSION_GRANTED == mContext.checkPermission(
2811 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2812 }
2813
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002814 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002815 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002816 }
2817
2818 private void sendInetConditionBroadcast(NetworkInfo info) {
2819 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2820 }
2821
Wink Saville4f0de1e2011-08-04 15:01:58 -07002822 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002823 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002824 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002825 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002826 if (info.isFailover()) {
2827 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2828 info.setFailover(false);
2829 }
2830 if (info.getReason() != null) {
2831 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2832 }
2833 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002834 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2835 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002836 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002837 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002838 return intent;
2839 }
2840
2841 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2842 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2843 }
2844
Chiachang Wang3bc52762021-11-25 14:17:57 +08002845 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
2846 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002847 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09002848 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09002849 if (!mSystemReady
2850 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002851 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002852 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002853 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002854 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002855 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002856 }
2857
Dianne Hackborn66dd0332015-12-09 17:22:26 -08002858 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07002859 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002860 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07002861 final NetworkInfo ni = intent.getParcelableExtra(
2862 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08002863 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2864 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2865 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08002866 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002867 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07002868 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00002869 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002870 } finally {
2871 Binder.restoreCallingIdentity(ident);
2872 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002873 }
2874 }
2875
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002876 /**
Aaron Huang96011892020-06-27 07:18:23 +08002877 * Called by SystemServer through ConnectivityManager when the system is ready.
2878 */
2879 @Override
2880 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002881 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08002882 throw new SecurityException("Calling Uid is not system uid.");
2883 }
2884 systemReadyInternal();
2885 }
2886
2887 /**
2888 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002889 */
2890 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08002891 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09002892 // Load flags after PackageManager is ready to query module version
2893 mFlags.loadFlags(mDeps, mContext);
2894
Aaron Huang9a57acf2020-12-08 10:03:29 +08002895 // Since mApps in PermissionMonitor needs to be populated first to ensure that
2896 // listening network request which is sent by MultipathPolicyTracker won't be added
2897 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
2898 // be called after PermissionMonitor#startMonitoring().
2899 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
2900 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
2901 // to ensure the tracking will be initialized correctly.
paulhuc62d3c22019-11-19 17:55:31 +08002902 mPermissionMonitor.startMonitoring();
Chalard Jeane4f9bd92018-06-08 12:47:42 +09002903 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08002904 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002905
Hugo Benichie5220992017-04-26 14:53:28 +09002906 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002907 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002908 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07002909 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002910 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002911 }
2912 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002913
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002914 // Create network requests for always-on networks.
2915 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00002916
2917 // Update mobile data preference if necessary.
2918 // Note that empty uid list can be skip here only because no uid rules applied before system
2919 // ready. Normally, the empty uid list means to clear the uids rules on netd.
2920 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
2921 updateMobileDataPreferredUids();
2922 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002923 }
2924
The Android Open Source Project28527d22009-03-03 19:31:44 -08002925 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002926 * Start listening for default data network activity state changes.
2927 */
2928 @Override
2929 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08002930 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002931 }
2932
2933 /**
2934 * Stop listening for default data network activity state changes.
2935 */
2936 @Override
2937 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08002938 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002939 }
2940
2941 /**
2942 * Check whether the default network radio is currently active.
2943 */
2944 @Override
2945 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08002946 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002947 }
2948
2949 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09002950 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09002951 * and set it on it's iface.
2952 */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002953 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2954 final String iface = newLp.getInterfaceName();
2955 final int mtu = newLp.getMtu();
Pierre Imai07c53a32016-02-08 16:01:40 +09002956 if (oldLp == null && mtu == 0) {
2957 // Silently ignore unset MTU value.
2958 return;
2959 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002960 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2961 if (VDBG) log("identical MTU - not setting");
2962 return;
2963 }
paulhucbbc3db2019-03-08 16:35:20 +08002964 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002965 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002966 return;
2967 }
sy.yun4aa73922013-09-02 05:24:09 +09002968
w19976e714f1d2014-08-05 15:18:11 -07002969 // Cannot set MTU without interface name
2970 if (TextUtils.isEmpty(iface)) {
2971 loge("Setting MTU size with null iface.");
2972 return;
2973 }
2974
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002975 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09002976 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08002977 mNetd.interfaceSetMtu(iface, mtu);
2978 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08002979 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002980 }
2981 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002982
Chenbo Feng15416292018-11-08 17:36:21 -08002983 @VisibleForTesting
2984 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04002985
lucaslin821c9782018-11-28 19:27:52 +08002986 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002987 String[] values = null;
2988 if (tcpBufferSizes != null) {
2989 values = tcpBufferSizes.split(",");
2990 }
2991
2992 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07002993 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002994 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2995 values = tcpBufferSizes.split(",");
2996 }
2997
2998 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2999
3000 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003001 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003002
Chenbo Feng15416292018-11-08 17:36:21 -08003003 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3004 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3005 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003006 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003007 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003008 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003009 }
3010 }
3011
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003012 @Override
3013 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003014 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003015 NETWORK_RESTORE_DELAY_PROP_NAME);
3016 if(restoreDefaultNetworkDelayStr != null &&
3017 restoreDefaultNetworkDelayStr.length() != 0) {
3018 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003019 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003020 } catch (NumberFormatException e) {
3021 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003022 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003023 // if the system property isn't set, use the value for the apn type
3024 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3025
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003026 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3027 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003028 }
3029 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003030 }
3031
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003032 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
3033 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
3034 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003035 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003036 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003037 // Start gathering diagnostic information.
3038 netDiags.add(new NetworkDiagnostics(
3039 nai.network,
3040 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003041 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003042 DIAG_TIME_MS));
3043 }
3044
3045 for (NetworkDiagnostics netDiag : netDiags) {
3046 pw.println();
3047 netDiag.waitForMeasurements();
3048 netDiag.dump(pw);
3049 }
3050 }
3051
The Android Open Source Project28527d22009-03-03 19:31:44 -08003052 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003053 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3054 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003055 if (!checkDumpPermission(mContext, TAG, writer)) return;
3056
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003057 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003058 }
3059
lucaslin99473f62020-12-10 15:10:54 +08003060 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3061 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3062 != PackageManager.PERMISSION_GRANTED) {
3063 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003064 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003065 + " due to missing android.permission.DUMP permission");
3066 return false;
3067 } else {
3068 return true;
3069 }
3070 }
3071
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003072 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003073 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003074
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003075 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003076 dumpNetworkDiagnostics(pw);
3077 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003078 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003079 dumpNetworks(pw);
3080 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003081 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003082 dumpNetworkRequests(pw);
3083 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003084 }
Erik Kline9647f382015-06-05 17:47:34 +09003085
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003086 pw.print("NetworkProviders for:");
3087 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
3088 pw.print(" " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003089 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09003090 pw.println();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003091 pw.println();
3092
Chalard Jean5b409c72021-02-04 13:12:59 +09003093 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003094 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003095 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003096 pw.println("none");
3097 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003098 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003099 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003100 pw.println();
3101
James Mattis8b298a02021-06-01 22:34:04 -07003102 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003103 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003104 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003105 pw.decreaseIndent();
3106 pw.println();
3107
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003108 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003109 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003110 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003111 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003112 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003113
junyulaif2c67e42018-08-07 19:50:45 +08003114 pw.println("Status for known UIDs:");
3115 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003116 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003117 for (int i = 0; i < size; i++) {
3118 // Don't crash if the array is modified while dumping in bugreports.
3119 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003120 final int uid = mUidBlockedReasons.keyAt(i);
3121 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3122 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003123 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003124 } catch (ArrayIndexOutOfBoundsException e) {
3125 pw.println(" ArrayIndexOutOfBoundsException");
3126 } catch (ConcurrentModificationException e) {
3127 pw.println(" ConcurrentModificationException");
3128 }
3129 }
3130 pw.println();
3131 pw.decreaseIndent();
3132
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003133 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003134 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003135 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003136 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003137 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003138
Robert Greenwalt94e22142014-07-30 16:31:24 -07003139 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003140
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003141 pw.println();
markchien5e866652019-09-30 14:40:57 +08003142 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003143
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003144 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003145 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003146
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003147 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003148
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003149 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003150 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003151 pw.println("mNetworkRequestInfoLogs (most recent first):");
3152 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003153 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003154 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003155
3156 pw.println();
3157 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3158 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003159 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003160 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003161
3162 pw.println();
3163 pw.println("NetTransition WakeLock activity (most recent first):");
3164 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003165 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3166 pw.println("total releases: " + mTotalWakelockReleases);
3167 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3168 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3169 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3170 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3171 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3172 }
James Mattiscb1e0362021-04-06 17:07:42 -07003173 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003174
3175 pw.println();
3176 pw.println("bandwidth update requests (by uid):");
3177 pw.increaseIndent();
3178 synchronized (mBandwidthRequests) {
3179 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3180 pw.println("[" + mBandwidthRequests.keyAt(i)
3181 + "]: " + mBandwidthRequests.valueAt(i));
3182 }
3183 }
3184 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003185 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003186
James Mattiscb1e0362021-04-06 17:07:42 -07003187 pw.println();
3188 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3189 pw.increaseIndent();
3190 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003191 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003192 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003193
3194 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003195
3196 pw.println();
3197 pw.println("Permission Monitor:");
3198 pw.increaseIndent();
3199 mPermissionMonitor.dump(pw);
3200 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003201
3202 pw.println();
3203 pw.println("Legacy network activity:");
3204 pw.increaseIndent();
3205 mNetworkActivityTracker.dump(pw);
3206 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003207 }
3208
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003209 private void dumpNetworks(IndentingPrintWriter pw) {
3210 for (NetworkAgentInfo nai : networksSortedById()) {
3211 pw.println(nai.toString());
3212 pw.increaseIndent();
3213 pw.println(String.format(
3214 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3215 nai.numForegroundNetworkRequests(),
3216 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3217 nai.numBackgroundNetworkRequests(),
3218 nai.numNetworkRequests()));
3219 pw.increaseIndent();
3220 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3221 pw.println(nai.requestAt(i).toString());
3222 }
3223 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003224 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003225 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003226 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003227 pw.decreaseIndent();
3228 pw.decreaseIndent();
3229 }
3230 }
3231
James Mattis8b298a02021-06-01 22:34:04 -07003232 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3233 if (!mProfileNetworkPreferences.isEmpty()) {
3234 pw.println("Profile preferences:");
3235 pw.increaseIndent();
3236 pw.println(mProfileNetworkPreferences.preferences);
3237 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003238 }
James Mattis8b298a02021-06-01 22:34:04 -07003239 if (!mOemNetworkPreferences.isEmpty()) {
3240 pw.println("OEM preferences:");
3241 pw.increaseIndent();
3242 pw.println(mOemNetworkPreferences);
3243 pw.decreaseIndent();
3244 }
3245 if (!mMobileDataPreferredUids.isEmpty()) {
3246 pw.println("Mobile data preferred UIDs:");
3247 pw.increaseIndent();
3248 pw.println(mMobileDataPreferredUids);
3249 pw.decreaseIndent();
3250 }
James Mattis45d81842021-01-10 14:24:24 -08003251
James Mattis8b298a02021-06-01 22:34:04 -07003252 pw.println("Default requests:");
3253 pw.increaseIndent();
3254 dumpPerAppDefaultRequests(pw);
3255 pw.decreaseIndent();
3256 }
3257
3258 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003259 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3260 if (mDefaultRequest == defaultRequest) {
3261 continue;
3262 }
3263
James Mattis8b298a02021-06-01 22:34:04 -07003264 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3265 final String networkOutput;
3266 if (null == satisfier) {
3267 networkOutput = "null";
3268 } else if (mNoServiceNetwork.equals(satisfier)) {
3269 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003270 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003271 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003272 }
James Mattis8b298a02021-06-01 22:34:04 -07003273 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3274 ? "" : " asUid: " + defaultRequest.mAsUid;
3275 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3276 + defaultRequest.mPid + asUidString + "]";
3277 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3278 + " Preference order: " + defaultRequest.mPreferenceOrder
3279 + " Tracked UIDs: " + defaultRequest.getUids();
3280 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003281 }
3282 }
3283
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003284 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003285 NetworkRequestInfo[] infos = null;
3286 while (infos == null) {
3287 try {
3288 infos = requestsSortedById();
3289 } catch (ConcurrentModificationException e) {
3290 // mNetworkRequests should only be accessed from handler thread, except dump().
3291 // As dump() is never called in normal usage, it would be needlessly expensive
3292 // to lock the collection only for its benefit. Instead, retry getting the
3293 // requests if ConcurrentModificationException is thrown during dump().
3294 }
3295 }
3296 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003297 pw.println(nri.toString());
3298 }
3299 }
3300
Chalard Jean524f0b12021-10-25 21:11:56 +09003301 private void dumpAllRequestInfoLogsToLogcat() {
3302 try (PrintWriter logPw = new PrintWriter(new Writer() {
3303 @Override
3304 public void write(final char[] cbuf, final int off, final int len) {
3305 // This method is called with 0-length and 1-length arrays for empty strings
3306 // or strings containing only the DEL character.
3307 if (len <= 1) return;
3308 Log.e(TAG, new String(cbuf, off, len));
3309 }
3310 @Override public void flush() {}
3311 @Override public void close() {}
3312 })) {
3313 mNetworkRequestInfoLogs.dump(logPw);
3314 }
3315 }
3316
Hugo Benichia480ba52018-09-03 08:19:02 +09003317 /**
3318 * Return an array of all current NetworkAgentInfos sorted by network id.
3319 */
3320 private NetworkAgentInfo[] networksSortedById() {
3321 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003322 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003323 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003324 return networks;
3325 }
3326
3327 /**
3328 * Return an array of all current NetworkRequest sorted by request id.
3329 */
James Mattis258ea3c2020-11-15 15:04:40 -08003330 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003331 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003332 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003333 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003334 // Sort the array based off the NRI containing the min requestId in its requests.
3335 Arrays.sort(requests,
3336 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3337 Comparator.comparingInt(req -> req.requestId)).requestId
3338 )
3339 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003340 return requests;
3341 }
3342
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003343 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003344 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003345 if (officialNai != null && officialNai.equals(nai)) return true;
3346 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003347 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003348 " - " + nai);
3349 }
3350 return false;
3351 }
3352
Robert Greenwalt2034b912009-08-12 16:08:25 -07003353 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003354 private class NetworkStateTrackerHandler extends Handler {
3355 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003356 super(looper);
3357 }
3358
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003359 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003360 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3361 final NetworkAgentInfo nai = arg.first;
3362 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003363 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003364 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003365 }
3366 return;
3367 }
3368
3369 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003370 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean15228572022-01-28 19:29:12 +09003371 final NetworkCapabilities networkCapabilities = new NetworkCapabilities(
3372 (NetworkCapabilities) arg.second);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003373 processCapabilitiesFromAgent(nai, networkCapabilities);
Hugo Benichibbc15192016-09-15 18:18:48 +09003374 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003375 break;
3376 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003377 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003378 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003379 processLinkPropertiesFromAgent(nai, newLp);
3380 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003381 break;
3382 }
3383 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003384 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003385 updateNetworkInfo(nai, info);
3386 break;
3387 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003388 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003389 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003390 break;
3391 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003392 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003393 if (nai.everConnected) {
3394 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003395 // Note that if the NAI had been connected, this would affect the
3396 // score, and therefore would require re-mixing the score and performing
3397 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003398 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003399 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3400 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003401 // Mark the network as temporarily accepting partial connectivity so that it
3402 // will be validated (and possibly become default) even if it only provides
3403 // partial internet access. Note that if user connects to partial connectivity
3404 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3405 // out of wifi coverage) and if the same wifi is available again, the device
3406 // will auto connect to this wifi even though the wifi has "no internet".
3407 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003408 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003409 break;
3410 }
junyulai011b1f12019-01-03 18:50:15 +08003411 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003412 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003413 break;
3414 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003415 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003416 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003417 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003418
3419 if (isLegacyLockdownNai(nai)
3420 && (underlying == null || underlying.size() != 1)) {
3421 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3422 + " must have exactly one underlying network: " + underlying);
3423 }
3424
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003425 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3426 nai.declaredUnderlyingNetworks = (underlying != null)
3427 ? underlying.toArray(new Network[0]) : null;
3428
3429 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3430 if (DBG) {
3431 log(nai.toShortString() + " changed underlying networks to "
3432 + Arrays.toString(nai.declaredUnderlyingNetworks));
3433 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003434 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003435 notifyIfacesChangedForNetworkStats();
3436 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003437 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003438 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003439 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3440 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3441 nai.teardownDelayMs = msg.arg1;
3442 } else {
3443 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3444 }
Chalard Jean550b5212021-03-05 23:07:53 +09003445 break;
3446 }
3447 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3448 nai.setLingerDuration((int) arg.second);
3449 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003450 }
Tyler Wear72388212021-09-09 14:49:02 -07003451 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3452 DscpPolicy policy = (DscpPolicy) arg.second;
3453 if (mDscpPolicyTracker != null) {
3454 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3455 }
3456 break;
3457 }
3458 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3459 if (mDscpPolicyTracker != null) {
3460 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3461 }
3462 break;
3463 }
3464 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3465 if (mDscpPolicyTracker != null) {
3466 mDscpPolicyTracker.removeAllDscpPolicies(nai);
3467 }
3468 break;
3469 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003470 }
3471 }
3472
3473 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
3474 switch (msg.what) {
3475 default:
3476 return false;
lucasline117e2e2019-10-22 18:27:33 +08003477 case EVENT_PROBE_STATUS_CHANGED: {
3478 final Integer netId = (Integer) msg.obj;
3479 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3480 if (nai == null) {
3481 break;
3482 }
3483 final boolean probePrivateDnsCompleted =
3484 ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
3485 final boolean privateDnsBroken =
3486 ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
3487 if (probePrivateDnsCompleted) {
3488 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3489 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003490 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003491 }
3492 // Only show the notification when the private DNS is broken and the
3493 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003494 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003495 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3496 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003497 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003498 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3499 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3500 // private DNS is broken, it means this network is being reevaluated.
3501 // Either probing private DNS is not necessary any more or it hasn't been
3502 // done yet. In either case, the networkCapabilities should be updated to
3503 // reflect the new status.
3504 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003505 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003506 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003507 }
3508 break;
3509 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003510 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003511 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3512
3513 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(results.mNetId);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003514 if (nai == null) break;
3515
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003516 handleNetworkTested(nai, results.mTestResult,
3517 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003518 break;
3519 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003520 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09003521 final int netId = msg.arg2;
Hugo Benichif4210292017-04-21 15:07:12 +09003522 final boolean visible = toBool(msg.arg1);
Erik Kline9a62f012018-03-21 07:18:33 -07003523 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Ondada1452016-10-11 15:10:46 -07003524 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04003525 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3526 nai.lastCaptivePortalDetected = visible;
3527 nai.everCaptivePortalDetected |= visible;
Calvin Ondada1452016-10-11 15:10:46 -07003528 if (nai.lastCaptivePortalDetected &&
paulhu56e09df2021-03-17 20:30:33 +08003529 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3530 == getCaptivePortalMode()) {
Chalard Jean49707572019-12-10 21:07:02 +09003531 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003532 nai.onPreventAutomaticReconnect();
Calvin Ondada1452016-10-11 15:10:46 -07003533 teardownUnneededNetwork(nai);
3534 break;
3535 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003536 updateCapabilitiesForNetwork(nai);
Paul Jensen53f08952015-06-16 14:27:36 -04003537 }
3538 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003539 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003540 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003541 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3542 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003543 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003544 if (nai == null) {
3545 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3546 break;
3547 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003548 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003549 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003550 (PendingIntent) msg.obj,
3551 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003552 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003553 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003554 break;
3555 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003556 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline9a62f012018-03-21 07:18:33 -07003557 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003558 if (nai == null) break;
3559
Erik Kline9a62f012018-03-21 07:18:33 -07003560 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003561 break;
3562 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003563 case EVENT_CAPPORT_DATA_CHANGED: {
3564 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3565 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003566 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003567 break;
3568 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003569 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003570 return true;
3571 }
3572
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003573 private void handleNetworkTested(
3574 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
3575 final boolean wasPartial = nai.partialConnectivity;
3576 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3577 final boolean partialConnectivityChanged =
3578 (wasPartial != nai.partialConnectivity);
3579
3580 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3581 final boolean wasValidated = nai.lastValidated;
Chalard Jean5b409c72021-02-04 13:12:59 +09003582 final boolean wasDefault = isDefaultNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003583
3584 if (DBG) {
3585 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3586 ? " with redirect to " + redirectUrl
3587 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003588 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003589 }
3590 if (valid != nai.lastValidated) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003591 final int oldScore = nai.getCurrentScore();
3592 nai.lastValidated = valid;
3593 nai.everValidated |= valid;
3594 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003595 if (valid) {
3596 handleFreshlyValidatedNetwork(nai);
3597 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3598 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003599 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003600 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003601 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003602 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003603 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003604 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003605 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003606 NotificationType.PRIVATE_DNS_BROKEN);
3607 // If network becomes valid, the hasShownBroken should be reset for
3608 // that network so that the notification will be fired when the private
3609 // DNS is broken again.
3610 nai.networkAgentConfig.hasShownBroken = false;
3611 }
3612 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003613 updateCapabilitiesForNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003614 }
3615 updateInetCondition(nai);
3616 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003617 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003618 nai.onValidationStatusChanged(
3619 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3620 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003621
3622 // If NetworkMonitor detects partial connectivity before
3623 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3624 // immediately. Re-notify partial connectivity silently if no internet
3625 // notification already there.
3626 if (!wasPartial && nai.partialConnectivity) {
3627 // Remove delayed message if there is a pending message.
3628 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3629 handlePromptUnvalidated(nai.network);
3630 }
3631
3632 if (wasValidated && !nai.lastValidated) {
3633 handleNetworkUnvalidated(nai);
3634 }
3635 }
3636
Calvin Ondada1452016-10-11 15:10:46 -07003637 private int getCaptivePortalMode() {
3638 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08003639 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3640 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07003641 }
3642
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003643 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3644 switch (msg.what) {
3645 default:
3646 return false;
3647 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3648 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3649 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3650 handleLingerComplete(nai);
3651 }
3652 break;
3653 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003654 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3655 handleNetworkAgentRegistered(msg);
3656 break;
3657 }
3658 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3659 handleNetworkAgentDisconnected(msg);
3660 break;
3661 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003662 }
3663 return true;
3664 }
3665
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003666 @Override
3667 public void handleMessage(Message msg) {
lifraf3a3492021-03-10 13:58:14 +08003668 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09003669 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003670 maybeHandleNetworkAgentMessage(msg);
3671 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003672 }
3673 }
3674
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003675 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09003676 private final int mNetId;
3677 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003678
3679 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003680 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003681 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003682 }
3683
3684 @Override
3685 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3686 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09003687 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003688 }
3689
3690 @Override
3691 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003692 // Legacy version of notifyNetworkTestedWithExtras.
3693 // Would only be called if the system has a NetworkStack module older than the
3694 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08003695 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003696 }
3697
3698 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003699 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09003700 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3701 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003702 final Message msg = mTrackerHandler.obtainMessage(
3703 EVENT_NETWORK_TESTED,
3704 new NetworkTestedResults(
3705 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003706 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003707
3708 // Invoke ConnectivityReport generation for this Network test event.
3709 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3710 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003711
Cody Kestingf1120be2020-08-03 18:01:40 -07003712 // NetworkMonitor reports the network validation result as a bitmask while
3713 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
3714 // logical value for ConnectivityDiagnostics.
3715 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
3716 p.result);
3717
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003718 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07003719 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003720 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3721 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3722
Aaron Huang959d3642021-01-21 15:47:41 +08003723 ConnectivityReportEvent reportEvent =
3724 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3725 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
3726 ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003727 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003728 }
3729
3730 @Override
3731 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3732 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3733 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09003734 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003735 }
3736
3737 @Override
lucasline117e2e2019-10-22 18:27:33 +08003738 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3739 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3740 EVENT_PROBE_STATUS_CHANGED,
3741 probesCompleted, probesSucceeded, new Integer(mNetId)));
3742 }
3743
3744 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003745 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3746 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3747 EVENT_CAPPORT_DATA_CHANGED,
3748 0, mNetId, data));
3749 }
3750
3751 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003752 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003753 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003754 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003755
3756 final PendingIntent pendingIntent;
3757 // Only the system server can register notifications with package "android"
3758 final long token = Binder.clearCallingIdentity();
3759 try {
paulhu7746e4e2020-06-09 19:07:03 +08003760 pendingIntent = PendingIntent.getBroadcast(
3761 mContext,
3762 0 /* requestCode */,
3763 intent,
3764 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003765 } finally {
3766 Binder.restoreCallingIdentity(token);
3767 }
3768 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3769 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09003770 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003771 }
3772
3773 @Override
3774 public void hideProvisioningNotification() {
3775 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09003776 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003777 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003778
3779 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003780 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003781 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08003782 }
3783
3784 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003785 public int getInterfaceVersion() {
3786 return this.VERSION;
3787 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09003788
3789 @Override
3790 public String getInterfaceHash() {
3791 return this.HASH;
3792 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003793 }
3794
Cody Kestingf1120be2020-08-03 18:01:40 -07003795 /**
3796 * Converts the given NetworkMonitor-specific validation result bitmask to a
3797 * ConnectivityDiagnostics-specific validation result int.
3798 */
3799 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
3800 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
3801 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
3802 }
3803 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
3804 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
3805 }
3806 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
3807 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
3808 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
3809 }
3810
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003811 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07003812 log("Data stall detected with methods: " + p.detectionMethod);
3813
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003814 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07003815 int detectionMethod = 0;
3816 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
3817 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
3818 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
3819 }
3820 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
3821 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
3822 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
3823 p.tcpMetricsCollectionPeriodMillis);
3824 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003825 }
3826
Cody Kestingf53a0752020-04-15 12:33:28 -07003827 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003828 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08003829 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07003830
3831 // NetworkStateTrackerHandler currently doesn't take any actions based on data
3832 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
3833 // the cost of going through two handlers.
3834 mConnectivityDiagnosticsHandler.sendMessage(msg);
3835 }
3836
Cody Kestingb37958e2020-05-15 10:36:01 -07003837 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
3838 return (p.detectionMethod & detectionMethod) != 0;
3839 }
3840
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003841 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
3842 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07003843 }
3844
Erik Klinea73af002018-06-26 18:53:43 +09003845 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
3846 if (nai == null) return;
3847 // If the Private DNS mode is opportunistic, reprogram the DNS servers
3848 // in order to restart a validation pass from within netd.
3849 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3850 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003851 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09003852 }
3853 }
3854
Erik Kline31b4a9e2018-01-11 21:07:29 +09003855 private void handlePrivateDnsSettingsChanged() {
3856 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3857
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003858 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07003859 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003860 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05003861 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3862 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09003863 }
3864 }
3865
Erik Kline9a62f012018-03-21 07:18:33 -07003866 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
3867 // Private DNS only ever applies to networks that might provide
3868 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003869 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09003870
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003871 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07003872 // schedule DNS resolutions. If a DNS resolution is required the
3873 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09003874 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07003875
3876 // With Private DNS bypass support, we can proceed to update the
3877 // Private DNS config immediately, even if we're in strict mode
3878 // and have not yet resolved the provider name into a set of IPs.
3879 updatePrivateDns(nai, cfg);
3880 }
3881
3882 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
3883 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003884 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09003885 }
3886
dalyk1720e542018-03-05 12:42:22 -05003887 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
3888 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
3889 if (nai == null) {
3890 return;
3891 }
3892 mDnsManager.updatePrivateDnsValidation(update);
3893 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3894 }
3895
paulhu7c0a2e62021-01-08 00:51:49 +08003896 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003897 int prefixLength) {
3898 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
3899 if (nai == null) return;
3900
paulhu7c0a2e62021-01-08 00:51:49 +08003901 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
3902 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003903
3904 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08003905 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003906 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003907 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003908 prefixLength);
3909 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003910 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003911 return;
3912 }
3913 }
3914
Lorenzo Colittid523d142020-04-01 20:16:30 +09003915 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003916 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3917 }
3918
Hai Shalome58bdc62021-01-11 18:45:34 -08003919 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003920 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08003921 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003922 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
3923 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3924 }
3925
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003926 /**
junyulai2b6f0c22021-02-03 20:15:30 +08003927 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003928 * @param nai the agent info to update
3929 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08003930 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003931 */
junyulai2b6f0c22021-02-03 20:15:30 +08003932 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
3933 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
3934 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003935 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08003936 // one lingered request, set inactive.
3937 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08003938 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08003939 if (DBG) log("Unsetting inactive " + nai.toShortString());
3940 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003941 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08003942 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003943 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08003944 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
3945 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003946 }
junyulai2b6f0c22021-02-03 20:15:30 +08003947 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003948 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003949 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003950 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003951 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05003952 }
3953
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003954 private void handleNetworkAgentRegistered(Message msg) {
3955 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3956 if (!mNetworkAgentInfos.contains(nai)) {
3957 return;
3958 }
3959
3960 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
3961 if (VDBG) log("NetworkAgent registered");
3962 } else {
3963 loge("Error connecting NetworkAgent");
3964 mNetworkAgentInfos.remove(nai);
3965 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09003966 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003967 synchronized (mNetworkForNetId) {
3968 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003969 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003970 mNetIdManager.releaseNetId(nai.network.getNetId());
3971 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09003972 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003973 }
3974 }
3975 }
Paul Jensend5f53392014-11-25 15:26:53 -05003976
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003977 private void handleNetworkAgentDisconnected(Message msg) {
3978 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07003979 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003980 }
3981
Chalard Jeand9fffc32018-05-11 20:19:20 +09003982 // Destroys a network, remove references to it from the internal state managed by
3983 // ConnectivityService, free its interfaces and clean up.
3984 // Must be called on the Handler thread.
3985 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09003986 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07003987
3988 if (!mNetworkAgentInfos.contains(nai)) return;
3989
Chalard Jeand9fffc32018-05-11 20:19:20 +09003990 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09003991 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003992 }
lucaslinb25c9a62019-02-12 15:30:13 +08003993 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003994 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003995 // A network agent has disconnected.
3996 // TODO - if we move the logic to the network agent (have them disconnect
3997 // because they lost all their requests or because their score isn't good)
3998 // then they would disconnect organically, report their new state and then
3999 // disconnect the channel.
4000 if (nai.networkInfo.isConnected()) {
4001 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4002 null, null);
4003 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004004 final boolean wasDefault = isDefaultNetwork(nai);
4005 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004006 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004007 }
4008 notifyIfacesChangedForNetworkStats();
4009 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4010 // by other networks that are already connected. Perhaps that can be done by
4011 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4012 // of rematchAllNetworksAndRequests
4013 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004014 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004015
4016 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004017 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4018 // Disable wakeup packet monitoring for each interface.
4019 wakeupModifyInterface(iface, nai.networkCapabilities, false);
4020 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004021 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004022 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004023 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004024 synchronized (mNetworkForNetId) {
4025 // Remove the NetworkAgent, but don't mark the netId as
4026 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004027 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004028 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004029 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004030 // Remove all previously satisfied requests.
4031 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004032 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004033 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004034 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004035 if (currentNetwork != null
4036 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004037 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004038 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4039 // rematch not to keep disconnected agents instead of setting it here ; this
4040 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004041 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004042 for (final NetworkOfferInfo noi : mNetworkOffers) {
4043 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004044 }
James Mattise3ef1912020-12-20 11:09:58 -08004045
Chalard Jean5b409c72021-02-04 13:12:59 +09004046 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004047 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004048 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004049 // network, because while incorrect this is the closest to the old (also
4050 // incorrect) behavior.
4051 mNetworkActivityTracker.updateDataActivityTracking(
4052 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004053 ensureNetworkTransitionWakelock(nai.toShortString());
4054 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004055 }
4056 }
junyulai2b6f0c22021-02-03 20:15:30 +08004057 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004058 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004059 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004060 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004061 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004062 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004063 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004064
4065 // Immediate teardown.
4066 if (nai.teardownDelayMs == 0) {
4067 destroyNetwork(nai);
4068 return;
4069 }
4070
4071 // Delayed teardown.
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304072 if (nai.created) {
4073 try {
4074 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4075 } catch (RemoteException e) {
4076 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4077 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004078 }
4079 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4080 }
4081
4082 private void destroyNetwork(NetworkAgentInfo nai) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004083 if (nai.created) {
4084 // Tell netd to clean up the configuration for this network
4085 // (routing rules, DNS, etc).
4086 // This may be slow as it requires a lot of netd shelling out to ip and
4087 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004088 // after we've rematched networks with requests (which might change the default
4089 // network or service a new request from an app), so network traffic isn't interrupted
4090 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004091 destroyNativeNetwork(nai);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004092 mDnsManager.removeNetwork(nai.network);
4093 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004094 mNetIdManager.releaseNetId(nai.network.getNetId());
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004095 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004096 }
4097
Ken Chen6df7a902021-04-09 15:08:42 +08004098 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004099 try {
4100 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004101 final NativeNetworkConfig config;
4102 if (nai.isVPN()) {
4103 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004104 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004105 return false;
4106 }
4107 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4108 INetd.PERMISSION_NONE,
4109 (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass),
Chiachang Wang9164c102022-01-13 10:54:32 +08004110 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004111 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004112 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
4113 getNetworkPermission(nai.networkCapabilities), /*secure=*/ false,
Chiachang Wangbf6b8792022-01-11 10:48:07 +08004114 VpnManager.TYPE_VPN_NONE, /*excludeLocalRoutes=*/ false);
Luke Huangfdd11f82019-04-09 18:41:49 +08004115 }
Ken Chen6df7a902021-04-09 15:08:42 +08004116 mNetd.networkCreate(config);
4117 mDnsResolver.createNetworkCache(nai.network.getNetId());
4118 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4119 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004120 return true;
4121 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004122 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004123 return false;
4124 }
4125 }
4126
Ken Chen6df7a902021-04-09 15:08:42 +08004127 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004128 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004129 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004130 } catch (RemoteException | ServiceSpecificException e) {
4131 loge("Exception destroying network(networkDestroy): " + e);
4132 }
4133 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004134 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004135 } catch (RemoteException | ServiceSpecificException e) {
4136 loge("Exception destroying network: " + e);
4137 }
4138 }
4139
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004140 // If this method proves to be too slow then we can maintain a separate
4141 // pendingIntent => NetworkRequestInfo map.
4142 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4143 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004144 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4145 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4146 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004147 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004148 return entry.getValue();
4149 }
4150 }
4151 return null;
4152 }
4153
Chalard Jean524f0b12021-10-25 21:11:56 +09004154 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4155 if (SdkLevel.isAtLeastT()) {
4156 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4157 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4158 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4159 // bug is fixed.
4160 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004161 throw new IllegalStateException("This NRI is already registered. New : " + nri
4162 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004163 }
4164 }
4165 }
4166 }
4167
Chalard Jeanac9ace02022-01-26 16:54:05 +09004168 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
4169 @NonNull final NetworkCapabilities caps) {
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004170 if (SdkLevel.isAtLeastT() && mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004171 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
4172 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004173 }
4174 return false;
4175 }
4176
James Mattisf7027322020-12-13 16:28:14 -08004177 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004178 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004179 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4180 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4181 final NetworkRequestInfo existingRequest =
4182 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004183 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004184 if (DBG) {
4185 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4186 + nri.mRequests.get(0) + " because their intents matched.");
4187 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004188 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004189 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004190 }
Erik Kline05f2b402015-04-30 12:58:40 +09004191 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004192 }
4193
James Mattisf7027322020-12-13 16:28:14 -08004194 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004195 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004196 }
4197
James Mattis3ce3d3c2021-02-09 18:18:28 -08004198 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004199 ensureRunningOnConnectivityServiceThread();
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004200 NetworkRequest requestToBeReleased = null;
James Mattis45d81842021-01-10 14:24:24 -08004201 for (final NetworkRequestInfo nri : nris) {
4202 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004203 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004204 for (final NetworkRequest req : nri.mRequests) {
4205 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004206 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004207 if (req.isListen()) {
4208 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4209 if (req.networkCapabilities.hasSignalStrength()
4210 && network.satisfiesImmutableCapabilitiesOf(req)) {
4211 updateSignalStrengthThresholds(network, "REGISTER", req);
4212 }
James Mattisf7027322020-12-13 16:28:14 -08004213 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004214 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004215 if (req.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004216 if (!hasCarrierPrivilegeForNetworkCaps(nri.mUid, req.networkCapabilities)
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004217 && !checkConnectivityRestrictedNetworksPermission(
4218 nri.mPid, nri.mUid)) {
4219 requestToBeReleased = req;
4220 }
4221 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004222 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004223
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004224 // If this NRI has a satisfier already, it is replacing an older request that
4225 // has been removed. Track it.
4226 final NetworkRequest activeRequest = nri.getActiveRequest();
4227 if (null != activeRequest) {
4228 // If there is an active request, then for sure there is a satisfier.
4229 nri.getSatisfier().addRequest(activeRequest);
4230 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004231 }
James Mattisf7027322020-12-13 16:28:14 -08004232
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004233 if (requestToBeReleased != null) {
4234 releaseNetworkRequestAndCallOnUnavailable(requestToBeReleased);
4235 return;
4236 }
4237
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004238 if (mFlags.noRematchAllRequestsOnRegister()) {
4239 rematchNetworksAndRequests(nris);
4240 } else {
4241 rematchAllNetworksAndRequests();
4242 }
James Mattis45d81842021-01-10 14:24:24 -08004243
Chalard Jean0354d8c2021-01-12 10:58:56 +09004244 // Requests that have not been matched to a network will not have been sent to the
4245 // providers, because the old satisfier and the new satisfier are the same (null in this
4246 // case). Send these requests to the providers.
4247 for (final NetworkRequestInfo nri : nris) {
4248 for (final NetworkOfferInfo noi : mNetworkOffers) {
4249 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004250 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004251 }
4252 }
4253
James Mattisf7027322020-12-13 16:28:14 -08004254 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4255 final int callingUid) {
4256 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004257 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004258 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4259 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4260 handleReleaseNetworkRequest(
4261 nri.mRequests.get(0),
4262 callingUid,
4263 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004264 }
4265 }
4266
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004267 // Determines whether the network is the best (or could become the best, if it validated), for
4268 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4269 // on the value of reason:
4270 //
4271 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4272 // then it should be torn down.
4273 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4274 // then it should be lingered.
4275 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004276 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004277
4278 if (!nai.everConnected || nai.isVPN() || nai.isInactive()
4279 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4280 return false;
4281 }
4282
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004283 final int numRequests;
4284 switch (reason) {
4285 case TEARDOWN:
4286 numRequests = nai.numRequestNetworkRequests();
4287 break;
4288 case LINGER:
4289 numRequests = nai.numForegroundNetworkRequests();
4290 break;
4291 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004292 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004293 return true;
4294 }
4295
Chalard Jean947acd42021-03-08 22:29:27 +09004296 if (numRequests > 0) return false;
4297
Paul Jensende49eb12015-06-25 15:30:08 -04004298 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004299 if (reason == UnneededFor.LINGER
4300 && !nri.isMultilayerRequest()
4301 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004302 // Background requests don't affect lingering.
4303 continue;
4304 }
4305
James Mattis3d229892020-11-16 16:46:28 -08004306 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004307 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004308 }
4309 }
Paul Jensende49eb12015-06-25 15:30:08 -04004310 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004311 }
4312
James Mattis3d229892020-11-16 16:46:28 -08004313 private boolean isNetworkPotentialSatisfier(
4314 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4315 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004316 // request, return immediately. For multilayer requests, check to see if any of the
4317 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004318 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4319 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004320 return false;
4321 }
4322 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004323 // This multilayer listen request is satisfied therefore no further requests need to be
4324 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004325 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004326 return false;
4327 }
James Mattis3d229892020-11-16 16:46:28 -08004328 // As non-multilayer listen requests have already returned, the below would only happen
4329 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004330 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004331 continue;
4332 }
4333 // If this Network is already the highest scoring Network for a request, or if
4334 // there is hope for it to become one if it validated, then it is needed.
4335 if (candidate.satisfies(req)) {
4336 // As soon as a network is found that satisfies a request, return. Specifically for
4337 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4338 // is important so as to not evaluate lower priority requests further in
4339 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004340 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4341 ? nri.getSatisfier() : null;
4342 // Note that this catches two important cases:
4343 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4344 // is currently satisfying the request. This is desirable when
4345 // cellular ends up validating but WiFi does not.
4346 // 2. Unvalidated WiFi will not be reaped when validated cellular
4347 // is currently satisfying the request. This is desirable when
4348 // WiFi ends up validating and out scoring cellular.
4349 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004350 }
4351 }
4352
4353 return false;
4354 }
4355
Erik Kline0c04b742016-07-07 16:50:58 +09004356 private NetworkRequestInfo getNriForAppRequest(
4357 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004358 // Looking up the app passed param request in mRequests isn't possible since it may return
4359 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4360 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004361 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4362 // to avoid potential race conditions when validating a package->uid mapping when sending
4363 // the callback on the very low-chance that an application shuts down prior to the callback
4364 // being sent.
4365 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4366 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004367
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004368 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004369 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004370 log(String.format("UID %d attempted to %s for unowned request %s",
4371 callingUid, requestedOperation, nri));
4372 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004373 }
Erik Kline0c04b742016-07-07 16:50:58 +09004374 }
4375
4376 return nri;
4377 }
4378
James Mattisf7027322020-12-13 16:28:14 -08004379 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4380 final String callingMethod) {
4381 if (nri.isMultilayerRequest()) {
4382 throw new IllegalStateException(
4383 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004384 }
4385 }
4386
James Mattisf7027322020-12-13 16:28:14 -08004387 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004388 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004389 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4390 // single NetworkRequest and thus does not apply to multilayer requests.
4391 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4392 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004393 return;
4394 }
James Mattis2516da32021-01-31 17:06:19 -08004395 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004396 return;
4397 }
James Mattisf7027322020-12-13 16:28:14 -08004398 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4399 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004400 }
4401 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004402 callCallbackForRequest(
4403 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004404 }
4405
James Mattisf7027322020-12-13 16:28:14 -08004406 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4407 final int callingUid,
4408 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004409 final NetworkRequestInfo nri =
4410 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4411 if (nri == null) {
4412 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004413 }
James Mattisf7027322020-12-13 16:28:14 -08004414 if (VDBG || (DBG && request.isRequest())) {
4415 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004416 }
4417 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004418 if (callOnUnavailable) {
4419 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4420 }
Erik Kline155a59a2015-11-25 12:49:38 +09004421 }
Erik Kline0c04b742016-07-07 16:50:58 +09004422
James Mattisa076c532020-12-02 14:12:41 -08004423 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004424 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004425 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004426 if (null == mNetworkRequests.remove(req)) {
4427 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4428 continue;
4429 }
James Mattisa076c532020-12-02 14:12:41 -08004430 if (req.isListen()) {
4431 removeListenRequestFromNetworks(req);
4432 }
4433 }
James Mattis8f036802021-06-20 16:26:01 -07004434 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004435 if (mDefaultNetworkRequests.remove(nri)) {
4436 // If this request was one of the defaults, then the UID rules need to be updated
4437 // WARNING : if the app(s) for which this network request is the default are doing
4438 // traffic, this will kill their connected sockets, even if an equivalent request
4439 // is going to be reinstated right away ; unconnected traffic will go on the default
4440 // until the new default is set, which will happen very soon.
4441 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4442 // remove ranges for those requests that won't have a replacement
4443 final NetworkAgentInfo satisfier = nri.getSatisfier();
4444 if (null != satisfier) {
4445 try {
paulhu0e79d952021-06-09 16:11:35 +08004446 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4447 satisfier.network.getNetId(),
4448 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004449 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004450 } catch (RemoteException e) {
4451 loge("Exception setting network preference default network", e);
4452 }
4453 }
4454 }
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09004455 nri.decrementRequestCount();
Erik Kline0c04b742016-07-07 16:50:58 +09004456 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004457 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004458
4459 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004460 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004461 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004462 }
4463 }
4464
Chalard Jean0354d8c2021-01-12 10:58:56 +09004465 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4466 // needed for this offer.
4467 for (final NetworkOfferInfo noi : mNetworkOffers) {
4468 for (final NetworkRequest req : nri.mRequests) {
4469 if (req.isRequest() && noi.offer.neededFor(req)) {
4470 noi.offer.onNetworkUnneeded(req);
4471 }
4472 }
4473 }
James Mattisa076c532020-12-02 14:12:41 -08004474 }
4475
James Mattis3ce3d3c2021-02-09 18:18:28 -08004476 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4477 for (final NetworkRequestInfo nri : nris) {
4478 if (mDefaultRequest == nri) {
4479 // Make sure we never remove the default request.
4480 continue;
4481 }
4482 handleRemoveNetworkRequest(nri);
4483 }
4484 }
4485
James Mattisa076c532020-12-02 14:12:41 -08004486 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4487 // listens don't have a singular affected Network. Check all networks to see
4488 // if this listen request applies and remove it.
4489 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4490 nai.removeRequest(req.requestId);
4491 if (req.networkCapabilities.hasSignalStrength()
4492 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4493 updateSignalStrengthThresholds(nai, "RELEASE", req);
4494 }
4495 }
4496 }
4497
4498 /**
4499 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4500 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4501 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4502 */
4503 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4504 boolean wasKept = false;
4505 final NetworkAgentInfo nai = nri.getSatisfier();
4506 if (nai != null) {
4507 final int requestLegacyType = nri.getActiveRequest().legacyType;
4508 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4509 nai.removeRequest(nri.getActiveRequest().requestId);
4510 if (VDBG || DDBG) {
4511 log(" Removing from current network " + nai.toShortString()
4512 + ", leaving " + nai.numNetworkRequests() + " requests.");
4513 }
4514 // If there are still lingered requests on this network, don't tear it down,
4515 // but resume lingering instead.
4516 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004517 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004518 notifyNetworkLosing(nai, now);
4519 }
4520 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4521 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4522 teardownUnneededNetwork(nai);
4523 } else {
4524 wasKept = true;
4525 }
James Mattisa076c532020-12-02 14:12:41 -08004526 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4527 // Went from foreground to background.
4528 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004529 }
4530
Erik Kline0c04b742016-07-07 16:50:58 +09004531 // Maintain the illusion. When this request arrived, we might have pretended
4532 // that a network connected to serve it, even though the network was already
4533 // connected. Now that this request has gone away, we might have to pretend
4534 // that the network disconnected. LegacyTypeTracker will generate that
4535 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004536 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004537 boolean doRemove = true;
4538 if (wasKept) {
4539 // check if any of the remaining requests for this network are for the
4540 // same legacy type - if so, don't remove the nai
4541 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4542 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004543 if (otherRequest.legacyType == requestLegacyType
4544 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004545 if (DBG) log(" still have other legacy request - leaving");
4546 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004547 }
4548 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004549 }
4550
Erik Kline0c04b742016-07-07 16:50:58 +09004551 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004552 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004553 }
4554 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004555 }
4556 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004557
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004558 private PerUidCounter getRequestCounter(NetworkRequestInfo nri) {
4559 return checkAnyPermissionOf(
4560 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4561 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4562 }
4563
Lorenzo Colittid6459092016-07-04 12:55:44 +09004564 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004565 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004566 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004567 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004568 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004569 }
4570
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004571 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004572 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4573 enforceNetworkStackSettingsOrSetup();
4574 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4575 encodeBool(accept), encodeBool(always), network));
4576 }
4577
4578 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004579 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004580 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004581 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4582 }
4583
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004584 @Override
4585 public void setTestAllowBadWifiUntil(long timeMs) {
4586 enforceSettingsPermission();
4587 if (!Build.isDebuggable()) {
4588 throw new IllegalStateException("Does not support in non-debuggable build");
4589 }
4590
4591 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4592 throw new IllegalArgumentException("It should not exceed "
4593 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4594 }
4595
4596 mHandler.sendMessage(
4597 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
4598 }
4599
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004600 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4601 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4602 " accept=" + accept + " always=" + always);
4603
4604 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4605 if (nai == null) {
4606 // Nothing to do.
4607 return;
4608 }
4609
4610 if (nai.everValidated) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004611 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004612 return;
4613 }
4614
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004615 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08004616 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004617 }
4618
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004619 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4620 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004621 // If network becomes partial connectivity and user already accepted to use this
4622 // network, we should respect the user's option and don't need to popup the
4623 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004624 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004625 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004626 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004627 }
4628
4629 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004630 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004631 }
4632
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004633 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04004634 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004635 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09004636 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04004637 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004638 }
4639
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004640 }
4641
lucaslin2240ef62019-03-12 13:08:03 +08004642 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4643 boolean always) {
4644 if (DBG) {
4645 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4646 + " always=" + always);
4647 }
4648
4649 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4650 if (nai == null) {
4651 // Nothing to do.
4652 return;
4653 }
4654
4655 if (nai.lastValidated) {
4656 // The network validated while the dialog box was up. Take no action.
4657 return;
4658 }
4659
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004660 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4661 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004662 }
4663
4664 // TODO: Use the current design or save the user choice into IpMemoryStore.
4665 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004666 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08004667 }
4668
4669 if (!accept) {
4670 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004671 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08004672 // Tear down the network.
4673 teardownUnneededNetwork(nai);
4674 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08004675 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4676 // result in a partial connectivity result which will be processed by
4677 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08004678 //
4679 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4680 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004681 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08004682 }
4683 }
4684
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004685 private void handleSetAvoidUnvalidated(Network network) {
4686 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4687 if (nai == null || nai.lastValidated) {
4688 // Nothing to do. The network either disconnected or revalidated.
4689 return;
4690 }
4691 if (!nai.avoidUnvalidated) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004692 nai.avoidUnvalidated = true;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004693 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004694 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004695 }
4696 }
4697
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004698 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09004699 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004700 mHandler.sendMessageDelayed(
4701 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4702 PROMPT_UNVALIDATED_DELAY_MS);
4703 }
4704
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004705 @Override
4706 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08004707 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004708 mHandler.post(() -> {
4709 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4710 if (nai == null) return;
4711 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004712 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004713 });
4714 }
4715
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004716 /**
4717 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4718 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004719 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004720 * @param appExtras Bundle to use as intent extras for the captive portal application.
4721 * Must be treated as opaque to avoid preventing the captive portal app to
4722 * update its arguments.
4723 */
4724 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004725 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08004726 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4727 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004728
4729 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4730 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004731 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4732 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004733 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4734
lucaslin75ff7022020-12-17 04:14:35 +08004735 final long token = Binder.clearCallingIdentity();
4736 try {
4737 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4738 } finally {
4739 Binder.restoreCallingIdentity(token);
4740 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004741 }
4742
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004743 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4744 private final Network mNetwork;
4745
4746 private CaptivePortalImpl(Network network) {
4747 mNetwork = network;
4748 }
4749
4750 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004751 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004752 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
4753 enforceSettingsPermission();
4754 }
4755
Chiachang Wang938bfba2020-01-09 13:50:55 +08004756 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004757 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004758 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004759 }
4760
4761 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08004762 public void appRequest(final int request) {
4763 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4764 if (nm == null) return;
4765
4766 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08004767 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09004768 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08004769 }
4770 }
4771
4772 @Nullable
4773 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
4774 // getNetworkAgentInfoForNetwork is thread-safe
4775 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4776 if (nai == null) return null;
4777
4778 // nai.networkMonitor() is thread-safe
4779 return nai.networkMonitor();
4780 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004781 }
4782
Hugo Benichic9048bc2016-09-14 23:23:08 +00004783 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004784 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09004785 }
4786
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004787 /**
4788 * Return whether the device should maintain continuous, working connectivity by switching away
4789 * from WiFi networks having no connectivity.
4790 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
4791 */
4792 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004793 if (!checkNetworkStackPermission()) {
4794 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
4795 }
4796 return avoidBadWifi();
4797 }
4798
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004799 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09004800 ensureRunningOnConnectivityServiceThread();
4801 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004802 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09004803 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004804 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09004805 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
4806 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
4807 for (final NetworkOfferInfo noi : offersToUpdate) {
4808 updateOfferScore(noi.offer);
4809 }
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004810 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004811 }
4812
Erik Kline95ecfee2016-10-02 18:02:14 +09004813 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004814 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004815 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004816 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004817 if (!configRestrict) {
4818 pw.println("Bad Wi-Fi avoidance: unrestricted");
4819 return;
4820 }
4821
4822 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
4823 pw.increaseIndent();
4824 pw.println("Config restrict: " + configRestrict);
4825
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004826 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004827 String description;
4828 // Can't use a switch statement because strings are legal case labels, but null is not.
4829 if ("0".equals(value)) {
4830 description = "get stuck";
4831 } else if (value == null) {
4832 description = "prompt";
4833 } else if ("1".equals(value)) {
4834 description = "avoid";
4835 } else {
4836 description = value + " (?)";
4837 }
4838 pw.println("User setting: " + description);
4839 pw.println("Network overrides:");
4840 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09004841 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004842 if (nai.avoidUnvalidated) {
Chalard Jean49707572019-12-10 21:07:02 +09004843 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004844 }
4845 }
4846 pw.decreaseIndent();
4847 pw.decreaseIndent();
4848 }
4849
paulhu7746e4e2020-06-09 19:07:03 +08004850 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
4851 // unify the method.
4852 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
4853 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
4854 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
4855 return settingsComponent != null
4856 ? settingsComponent.getPackageName() : "com.android.settings";
4857 }
4858
lucaslinb1e8e382019-01-24 15:55:30 +08004859 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004860 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004861 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004862 switch (type) {
4863 case NO_INTERNET:
4864 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004865 // High priority because it is only displayed for explicitly selected networks.
4866 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004867 break;
lucasline117e2e2019-10-22 18:27:33 +08004868 case PRIVATE_DNS_BROKEN:
4869 action = Settings.ACTION_WIRELESS_SETTINGS;
4870 // High priority because we should let user know why there is no internet.
4871 highPriority = true;
4872 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004873 case LOST_INTERNET:
4874 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004875 // High priority because it could help the user avoid unexpected data usage.
4876 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004877 break;
lucaslin2240ef62019-03-12 13:08:03 +08004878 case PARTIAL_CONNECTIVITY:
4879 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004880 // Don't bother the user with a high-priority notification if the network was not
4881 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004882 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08004883 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004884 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004885 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004886 return;
4887 }
4888
4889 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08004890 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08004891 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08004892 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08004893 // Some OEMs have their own Settings package. Thus, need to get the current using
4894 // Settings package name instead of just use default name "com.android.settings".
4895 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
4896 intent.setClassName(settingsPkgName,
4897 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08004898 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004899
paulhu2af50222020-10-11 22:52:27 +08004900 PendingIntent pendingIntent = PendingIntent.getActivity(
4901 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08004902 0 /* requestCode */,
4903 intent,
paulhu2af50222020-10-11 22:52:27 +08004904 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004905
Serik Beketayevec8ad212020-12-07 22:43:07 -08004906 mNotifier.showNotification(
4907 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004908 }
4909
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004910 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
4911 // Don't prompt if the network is validated, and don't prompt on captive portals
4912 // because we're already prompting the user to sign in.
4913 if (nai.everValidated || nai.everCaptivePortalDetected) {
4914 return false;
4915 }
4916
4917 // If a network has partial connectivity, always prompt unless the user has already accepted
4918 // partial connectivity and selected don't ask again. This ensures that if the device
4919 // automatically connects to a network that has partial Internet access, the user will
4920 // always be able to use it, either because they've already chosen "don't ask again" or
4921 // because we have prompt them.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004922 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004923 return true;
4924 }
4925
4926 // If a network has no Internet access, only prompt if the network was explicitly selected
4927 // and if the user has not already told us to use the network regardless of whether it
4928 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004929 if (nai.networkAgentConfig.explicitlySelected
4930 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004931 return true;
4932 }
4933
4934 return false;
4935 }
4936
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004937 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09004938 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004939 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4940
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004941 if (nai == null || !shouldPromptUnvalidated(nai)) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004942 return;
4943 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09004944
4945 // Stop automatically reconnecting to this network in the future. Automatically connecting
4946 // to a network that provides no or limited connectivity is not useful, because the user
4947 // cannot use that network except through the notification shown by this method, and the
4948 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004949 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09004950
lucaslin2240ef62019-03-12 13:08:03 +08004951 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
4952 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
4953 // popup the notification immediately when the network is partial connectivity.
4954 if (nai.partialConnectivity) {
lucasline0118ab2019-03-21 11:59:22 +08004955 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08004956 } else {
4957 showNetworkNotification(nai, NotificationType.NO_INTERNET);
4958 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004959 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004960
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004961 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
4962 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09004963 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07004964
lucaslin2240ef62019-03-12 13:08:03 +08004965 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4966 return;
4967 }
4968
4969 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08004970 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004971 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004972 }
4973
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004974 @Override
4975 public int getMultipathPreference(Network network) {
4976 enforceAccessPermission();
4977
4978 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06004979 if (nai != null && nai.networkCapabilities
4980 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004981 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
4982 }
4983
Aaron Huang9a57acf2020-12-08 10:03:29 +08004984 final NetworkPolicyManager netPolicyManager =
4985 mContext.getSystemService(NetworkPolicyManager.class);
4986
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09004987 final long token = Binder.clearCallingIdentity();
4988 final int networkPreference;
4989 try {
4990 networkPreference = netPolicyManager.getMultipathPreference(network);
4991 } finally {
4992 Binder.restoreCallingIdentity(token);
4993 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08004994 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09004995 return networkPreference;
4996 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004997 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
4998 }
4999
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005000 @Override
5001 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005002 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005003 }
5004
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005005 private class InternalHandler extends Handler {
5006 public InternalHandler(Looper looper) {
5007 super(looper);
5008 }
5009
5010 @Override
5011 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005012 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005013 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005014 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005015 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005016 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005017 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005018 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005019 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005020 break;
5021 }
Jason Monka69f1b02013-10-10 14:02:51 -04005022 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005023 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5024 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005025 break;
5026 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005027 case EVENT_REGISTER_NETWORK_PROVIDER: {
5028 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005029 break;
5030 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005031 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5032 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005033 break;
5034 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005035 case EVENT_REGISTER_NETWORK_OFFER: {
5036 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5037 break;
5038 }
5039 case EVENT_UNREGISTER_NETWORK_OFFER: {
5040 final NetworkOfferInfo offer =
5041 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5042 if (null != offer) {
5043 handleUnregisterNetworkOffer(offer);
5044 }
5045 break;
5046 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005047 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005048 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5049 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5050 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005051 break;
5052 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005053 case EVENT_REGISTER_NETWORK_REQUEST:
5054 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005055 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005056 break;
5057 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005058 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5059 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005060 handleRegisterNetworkRequestWithIntent(msg);
5061 break;
5062 }
Erik Kline155a59a2015-11-25 12:49:38 +09005063 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5064 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5065 handleTimedOutNetworkRequest(nri);
5066 break;
5067 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005068 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5069 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5070 break;
5071 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005072 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005073 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5074 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005075 break;
5076 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005077 case EVENT_RELEASE_NETWORK_REQUEST_AND_CALL_UNAVAILABLE: {
5078 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5079 /* callOnUnavailable */ true);
5080 break;
5081 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005082 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005083 Network network = (Network) msg.obj;
5084 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005085 break;
5086 }
lucaslin2240ef62019-03-12 13:08:03 +08005087 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5088 Network network = (Network) msg.obj;
5089 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5090 toBool(msg.arg2));
5091 break;
5092 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005093 case EVENT_SET_AVOID_UNVALIDATED: {
5094 handleSetAvoidUnvalidated((Network) msg.obj);
5095 break;
5096 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005097 case EVENT_PROMPT_UNVALIDATED: {
5098 handlePromptUnvalidated((Network) msg.obj);
5099 break;
5100 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005101 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5102 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005103 break;
5104 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005105 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005106 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005107 mKeepaliveTracker.handleStartKeepalive(msg);
5108 break;
5109 }
5110 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005111 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005112 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5113 int slot = msg.arg1;
5114 int reason = msg.arg2;
5115 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
5116 break;
5117 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005118 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5119 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5120 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005121 break;
5122 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005123 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5124 handlePrivateDnsSettingsChanged();
5125 break;
dalyk1720e542018-03-05 12:42:22 -05005126 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5127 handlePrivateDnsValidationUpdate(
5128 (PrivateDnsValidationUpdate) msg.obj);
5129 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005130 case EVENT_UID_BLOCKED_REASON_CHANGED:
5131 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005132 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005133 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5134 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5135 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005136 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005137 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5138 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005139 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005140 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005141 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005142 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005143 final Pair<List<ProfileNetworkPreferenceList.Preference>,
5144 IOnCompleteListener> arg =
5145 (Pair<List<ProfileNetworkPreferenceList.Preference>,
5146 IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005147 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005148 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005149 }
lucaslin1193a5d2021-01-21 02:04:15 +08005150 case EVENT_REPORT_NETWORK_ACTIVITY:
5151 mNetworkActivityTracker.handleReportNetworkActivity();
5152 break;
paulhu51f77dc2021-06-07 02:34:20 +00005153 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5154 handleMobileDataPreferredUidsChanged();
5155 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005156 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5157 final long timeMs = ((Long) msg.obj).longValue();
5158 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5159 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005160 }
5161 }
5162 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005163
Lorenzo Colittid6459092016-07-04 12:55:44 +09005164 @Override
markchien5776f962019-12-16 20:15:20 +08005165 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005166 public int getLastTetherError(String iface) {
markchien5776f962019-12-16 20:15:20 +08005167 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5168 Context.TETHERING_SERVICE);
5169 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -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[] getTetherableIfaces() {
markchien5776f962019-12-16 20:15:20 +08005175 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5176 Context.TETHERING_SERVICE);
5177 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005178 }
5179
Lorenzo Colittid6459092016-07-04 12:55:44 +09005180 @Override
markchien5776f962019-12-16 20:15:20 +08005181 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005182 public String[] getTetheredIfaces() {
markchien5776f962019-12-16 20:15:20 +08005183 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5184 Context.TETHERING_SERVICE);
5185 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005186 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005187
markchien5776f962019-12-16 20:15:20 +08005188
Lorenzo Colittid6459092016-07-04 12:55:44 +09005189 @Override
markchien5776f962019-12-16 20:15:20 +08005190 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005191 public String[] getTetheringErroredIfaces() {
markchien5776f962019-12-16 20:15:20 +08005192 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5193 Context.TETHERING_SERVICE);
5194
5195 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005196 }
5197
Lorenzo Colittid6459092016-07-04 12:55:44 +09005198 @Override
markchien5776f962019-12-16 20:15:20 +08005199 @Deprecated
5200 public String[] getTetherableUsbRegexs() {
5201 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5202 Context.TETHERING_SERVICE);
5203
5204 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005205 }
5206
Udam Saini8f7d6a72017-06-07 12:06:28 -07005207 @Override
markchien5776f962019-12-16 20:15:20 +08005208 @Deprecated
5209 public String[] getTetherableWifiRegexs() {
5210 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5211 Context.TETHERING_SERVICE);
5212 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005213 }
5214
Robert Greenwalte0b00512014-07-02 09:59:16 -07005215 // Called when we lose the default network and have no replacement yet.
5216 // This will automatically be cleared after X seconds or a new default network
5217 // becomes CONNECTED, whichever happens first. The timer is started by the
5218 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005219 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005220 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005221 if (mNetTransitionWakeLock.isHeld()) {
5222 return;
5223 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005224 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005225 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5226 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005227 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005228 mWakelockLogs.log("ACQUIRE for " + forWhom);
5229 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005230 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005231 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005232 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005233 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005234
Hugo Benichi471b62a2017-03-30 23:18:10 +09005235 // Called when we gain a new default network to release the network transition wakelock in a
5236 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5237 // message is cancelled.
5238 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005239 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005240 if (!mNetTransitionWakeLock.isHeld()) {
5241 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005242 }
5243 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005244 // Cancel self timeout on wakelock hold.
5245 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5246 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5247 mHandler.sendMessageDelayed(msg, 1000);
5248 }
5249
5250 // Called when either message of ensureNetworkTransitionWakelock or
5251 // scheduleReleaseNetworkTransitionWakelock is processed.
5252 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5253 String event = eventName(eventId);
5254 synchronized (this) {
5255 if (!mNetTransitionWakeLock.isHeld()) {
5256 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005257 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005258 return;
5259 }
5260 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005261 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5262 mTotalWakelockDurationMs += lockDuration;
5263 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5264 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005265 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005266 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005267 }
5268
Robert Greenwalt986c7412010-09-08 15:24:47 -07005269 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005270 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005271 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005272 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005273 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005274 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005275 }
5276
Lorenzo Colittid6459092016-07-04 12:55:44 +09005277 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005278 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005279 enforceAccessPermission();
5280 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005281 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005282 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005283
5284 final NetworkAgentInfo nai;
5285 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005286 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005287 } else {
5288 nai = getNetworkAgentInfoForNetwork(network);
5289 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005290
5291 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005292 mHandler.obtainMessage(
5293 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005294 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005295
Hugo Benichid6b510a2017-04-06 17:22:18 +09005296 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005297 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005298 if (nai == null
5299 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005300 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005301 return;
5302 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005303 // Revalidate if the app report does not match our current validated state.
Hugo Benichie9d321b2017-04-06 16:01:44 +09005304 if (hasConnectivity == nai.lastValidated) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005305 mConnectivityDiagnosticsHandler.sendMessage(
5306 mConnectivityDiagnosticsHandler.obtainMessage(
5307 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5308 new ReportedNetworkConnectivityInfo(
5309 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005310 return;
5311 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005312 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005313 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005314 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005315 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005316 // Validating a network that has not yet connected could result in a call to
5317 // rematchNetworkAndRequests() which is not meant to work on such networks.
5318 if (!nai.everConnected) {
5319 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005320 }
paulhu7aeba372020-12-30 00:42:19 +08005321 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5322 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005323 return;
5324 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005325
5326 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5327 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5328 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5329 // completed.
5330 mConnectivityDiagnosticsHandler.sendMessage(
5331 mConnectivityDiagnosticsHandler.obtainMessage(
5332 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5333 new ReportedNetworkConnectivityInfo(
5334 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005335 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005336 }
5337
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005338 // TODO: call into netd.
5339 private boolean queryUserAccess(int uid, Network network) {
5340 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5341 if (nai == null) return false;
5342
5343 // Any UID can use its default network.
5344 if (nai == getDefaultNetworkForUid(uid)) return true;
5345
5346 // Privileged apps can use any network.
5347 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5348 return true;
5349 }
5350
5351 // An unprivileged UID can use a VPN iff the VPN applies to it.
5352 if (nai.isVPN()) {
5353 return nai.networkCapabilities.appliesToUid(uid);
5354 }
5355
5356 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5357 // sockets, i.e., if it is the owner.
5358 final NetworkAgentInfo vpn = getVpnForUid(uid);
5359 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5360 && uid != vpn.networkCapabilities.getOwnerUid()) {
5361 return false;
5362 }
5363
5364 // The UID's permission must be at least sufficient for the network. Since the restricted
5365 // permission was already checked above, that just leaves background networks.
5366 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5367 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5368 }
5369
5370 // Unrestricted network. Anyone gets to use it.
5371 return true;
5372 }
5373
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005374 /**
5375 * Returns information about the proxy a certain network is using. If given a null network, it
5376 * it will return the proxy for the bound network for the caller app or the default proxy if
5377 * none.
5378 *
5379 * @param network the network we want to get the proxy information for.
5380 * @return Proxy information if a network has a proxy configured, or otherwise null.
5381 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005382 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005383 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005384 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005385 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005386 if (network == null) {
5387 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005388 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005389 true);
5390 if (activeNetwork == null) {
5391 return null;
5392 }
5393 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005394 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005395 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5396 // caller may not have.
5397 return getLinkPropertiesProxyInfo(network);
5398 }
5399 // No proxy info available if the calling UID does not have network access.
5400 return null;
5401 }
5402
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005403
5404 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005405 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5406 if (nai == null) return null;
5407 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005408 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5409 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005410 }
5411 }
5412
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005413 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005414 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhudf23d662021-01-25 18:53:17 +08005415 PermissionUtils.enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005416 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005417 }
5418
Chalard Jean777e2e52018-06-07 18:02:37 +09005419 @Override
5420 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005421 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005422 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005423 }
5424
Jason Monk4d5e20f2014-04-25 15:00:09 -04005425 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005426 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005427 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005428 proxy = null;
5429 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005430 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005431 }
5432
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005433 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5434 // when any network changes proxy.
5435 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5436 // multi-network world where an app might be bound to a non-default network.
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005437 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensenc0618a62014-12-10 15:12:18 -05005438 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5439 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5440
Chalard Jean7d97afc2018-06-07 17:41:29 +09005441 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005442 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005443 }
5444 }
5445
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005446 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005447 final private HashMap<Uri, Integer> mUriEventMap;
5448 final private Context mContext;
5449 final private Handler mHandler;
5450
5451 SettingsObserver(Context context, Handler handler) {
5452 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005453 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005454 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005455 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005456 }
5457
Erik Kline05f2b402015-04-30 12:58:40 +09005458 void observe(Uri uri, int what) {
5459 mUriEventMap.put(uri, what);
5460 final ContentResolver resolver = mContext.getContentResolver();
5461 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005462 }
5463
5464 @Override
5465 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005466 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005467 }
5468
5469 @Override
5470 public void onChange(boolean selfChange, Uri uri) {
5471 final Integer what = mUriEventMap.get(uri);
5472 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005473 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005474 } else {
5475 loge("No matching event to send for URI=" + uri);
5476 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005477 }
5478 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005479
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005480 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005481 Log.d(TAG, s);
5482 }
5483
5484 private static void logw(String s) {
5485 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005486 }
5487
Daniel Brightf9e945b2020-06-15 16:10:01 -07005488 private static void logwtf(String s) {
5489 Log.wtf(TAG, s);
5490 }
5491
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005492 private static void logwtf(String s, Throwable t) {
5493 Log.wtf(TAG, s, t);
5494 }
5495
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005496 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005497 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005498 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005499
Hugo Benichi39621362017-02-11 17:04:43 +09005500 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005501 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005502 }
5503
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005504 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005505 * Return the information of all ongoing VPNs.
5506 *
5507 * <p>This method is used to update NetworkStatsService.
5508 *
5509 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08005510 */
junyulai2050bed2021-01-23 09:46:34 +08005511 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005512 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09005513 if (mLockdownEnabled) {
5514 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08005515 }
junyulai2050bed2021-01-23 09:46:34 +08005516 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005517 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08005518 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005519 if (info != null) {
5520 infoList.add(info);
5521 }
5522 }
junyulai2050bed2021-01-23 09:46:34 +08005523 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08005524 }
5525
5526 /**
5527 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00005528 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08005529 */
junyulai2050bed2021-01-23 09:46:34 +08005530 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005531 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08005532 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5533 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09005534 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5535 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5536 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08005537 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5538 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00005539 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00005540 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08005541 }
5542 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005543
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005544 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005545
5546 List<String> interfaces = new ArrayList<>();
5547 for (Network network : underlyingNetworks) {
5548 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5549 if (underlyingNai == null) continue;
5550 LinkProperties lp = underlyingNai.linkProperties;
5551 for (String iface : lp.getAllInterfaceNames()) {
5552 if (!TextUtils.isEmpty(iface)) {
5553 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00005554 }
5555 }
Benedict Wong34857f82019-06-12 17:46:15 +00005556 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005557
5558 if (interfaces.isEmpty()) return null;
5559
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005560 // Must be non-null or NetworkStatsService will crash.
5561 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5562 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08005563 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08005564 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005565
junyulai2050bed2021-01-23 09:46:34 +08005566 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5567 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08005568 }
5569
James Mattisd31bdfa2020-12-23 16:37:26 -08005570 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08005571 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5572 Network[] underlyingNetworks) {
5573 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005574 if (underlyingNetworks == null && defaultNetwork != null) {
5575 // null underlying networks means to track the default.
5576 underlyingNetworks = new Network[] { defaultNetwork };
5577 }
5578 return underlyingNetworks;
5579 }
5580
5581 // Returns true iff |network| is an underlying network of |nai|.
5582 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5583 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5584 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09005585 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08005586 final Network[] underlying = underlyingNetworksOrDefault(
5587 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005588 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005589 }
5590
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005591 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005592 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005593 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005594 * When underlying networks change, such networks may have to update capabilities to reflect
5595 * things like the metered bit, their transports, and so on. The capabilities are calculated
5596 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005597 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005598 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005599 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005600 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005601 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005602 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005603 }
5604 }
5605 }
5606
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005607 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5608 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5609 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5610 // a VPN is not up.
5611 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5612 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5613 for (UidRange range : blockedUidRanges) {
5614 if (range.contains(uid)) return true;
5615 }
5616 return false;
5617 }
5618
5619 @Override
5620 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08005621 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005622 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5623 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5624 }
5625
5626 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5627 if (DBG) {
5628 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5629 + Arrays.toString(ranges));
5630 }
5631 // Cannot use a Set since the list of UID ranges might contain duplicates.
5632 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5633 for (int i = 0; i < ranges.length; i++) {
5634 if (requireVpn) {
5635 newVpnBlockedUidRanges.add(ranges[i]);
5636 } else {
5637 newVpnBlockedUidRanges.remove(ranges[i]);
5638 }
5639 }
5640
5641 try {
5642 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5643 } catch (RemoteException | ServiceSpecificException e) {
5644 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5645 + Arrays.toString(ranges) + "): netd command failed: " + e);
5646 }
5647
5648 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5649 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00005650 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5651 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005652 }
5653
5654 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5655 }
5656
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07005657 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005658 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08005659 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005660 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01005661 }
5662
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005663 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5664 return mLockdownEnabled
5665 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5666 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00005667 }
5668
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005669 private NetworkAgentInfo getLegacyLockdownNai() {
5670 if (!mLockdownEnabled) {
5671 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005672 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005673 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005674 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5675 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005676
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005677 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005678 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5679 // a local variable. There is no need to make a copy because its contents cannot change.
5680 final Network[] underlying = nai.declaredUnderlyingNetworks;
5681 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005682 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005683 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005684
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005685 // The legacy lockdown VPN always uses the default network.
5686 // If the VPN's underlying network is no longer the current default network, it means that
5687 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005688 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5689 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005690 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005691 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005692 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005693 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005694
5695 return nai;
5696 };
5697
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005698 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5699 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5700 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005701 private DetailedState getLegacyLockdownState(DetailedState origState) {
5702 if (origState != DetailedState.CONNECTED) {
5703 return origState;
5704 }
5705 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5706 ? DetailedState.CONNECTING
5707 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005708 }
5709
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005710 private void filterForLegacyLockdown(NetworkInfo ni) {
5711 if (!mLockdownEnabled || !ni.isConnected()) return;
5712 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5713 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5714 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5715 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5716 // network, this time with a state of CONNECTED.
5717 //
5718 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5719 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5720 // is not too far off the truth, since an always-on VPN, when not connected, is always
5721 // trying to reconnect.
5722 if (getLegacyLockdownNai() == null) {
5723 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5724 }
5725 }
5726
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005727 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005728 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04005729 String action) {
paulhu8e96a752019-08-12 16:25:11 +08005730 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09005731 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5732 return;
5733 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04005734 final long ident = Binder.clearCallingIdentity();
5735 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09005736 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09005737 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09005738 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04005739 } finally {
5740 Binder.restoreCallingIdentity(ident);
5741 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005742 }
Wink Savillecb117d32013-08-29 14:57:08 -07005743
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005744 @Override
5745 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01005746 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005747 final long ident = Binder.clearCallingIdentity();
5748 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005749 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09005750 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005751 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5752 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08005753 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005754 } finally {
5755 Binder.restoreCallingIdentity(ident);
5756 }
5757 }
5758
James Mattis02220e22021-03-13 19:27:21 -08005759 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005760 mPermissionMonitor.onUserAdded(user);
James Mattisae9aeb02021-03-01 17:09:11 -08005761 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5762 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5763 }
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005764 }
5765
James Mattis02220e22021-03-13 19:27:21 -08005766 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005767 mPermissionMonitor.onUserRemoved(user);
Chalard Jean0f57a492021-03-09 21:09:20 +09005768 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005769 handleSetProfileNetworkPreference(
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08005770 List.of(new ProfileNetworkPreferenceList.Preference(user, null, true)),
Chalard Jean0f57a492021-03-09 21:09:20 +09005771 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08005772 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5773 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5774 }
junyulaid91e7052020-08-28 13:44:33 +08005775 }
5776
James Mattis02220e22021-03-13 19:27:21 -08005777 private void onPackageChanged(@NonNull final String packageName) {
5778 // This is necessary in case a package is added or removed, but also when it's replaced to
5779 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5780 // as one in the preferences, then it should follow the same routing as that other package,
5781 // which means updating the rules is never to be needed in this case (whether it joins or
5782 // leaves a UID with a preference).
5783 if (isMappedInOemNetworkPreference(packageName)) {
5784 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5785 }
5786 }
5787
5788 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005789 @Override
5790 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09005791 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005792 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005793 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08005794
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005795 // User should be filled for below intents, check the existence.
5796 if (user == null) {
5797 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5798 return;
5799 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005800
Lorenzo Colitticd675292021-02-04 17:32:07 +09005801 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005802 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005803 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005804 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09005805 } else {
junyulaid91e7052020-08-28 13:44:33 +08005806 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005807 }
5808 }
5809 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07005810
James Mattis02220e22021-03-13 19:27:21 -08005811 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5812 @Override
5813 public void onReceive(Context context, Intent intent) {
5814 ensureRunningOnConnectivityServiceThread();
5815 switch (intent.getAction()) {
5816 case Intent.ACTION_PACKAGE_ADDED:
5817 case Intent.ACTION_PACKAGE_REMOVED:
5818 case Intent.ACTION_PACKAGE_REPLACED:
5819 onPackageChanged(intent.getData().getSchemeSpecificPart());
5820 break;
5821 default:
5822 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5823 }
5824 }
5825 };
5826
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005827 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005828 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005829
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005830 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005831 public final String name;
5832 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005833 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005834 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005835
lifraf3a3492021-03-10 13:58:14 +08005836 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5837 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005838 this.name = name;
5839 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005840 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005841 mDeathRecipient = deathRecipient;
5842
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005843 if (mDeathRecipient == null) {
5844 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005845 }
5846 }
5847
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005848 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005849 try {
5850 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5851 } catch (RemoteException e) {
5852 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005853 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005854 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005855 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005856
James Mattis4fce5d12020-11-12 15:53:42 -08005857 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
5858 for (int i = 0; i < requests.size(); i++) {
5859 ensureNetworkRequestHasType(requests.get(i));
5860 }
5861 }
5862
Lorenzo Colitti70964d32016-07-05 01:22:13 +09005863 private void ensureNetworkRequestHasType(NetworkRequest request) {
5864 if (request.type == NetworkRequest.Type.NONE) {
5865 throw new IllegalArgumentException(
5866 "All NetworkRequests in ConnectivityService must have a type");
5867 }
5868 }
5869
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005870 /**
5871 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08005872 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005873 */
James Mattis258ea3c2020-11-15 15:04:40 -08005874 @VisibleForTesting
5875 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08005876 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
5877 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08005878 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08005879
James Mattisa076c532020-12-02 14:12:41 -08005880 // mSatisfier and mActiveRequest rely on one another therefore set them together.
5881 void setSatisfier(
5882 @Nullable final NetworkAgentInfo satisfier,
5883 @Nullable final NetworkRequest activeRequest) {
5884 mSatisfier = satisfier;
5885 mActiveRequest = activeRequest;
5886 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005887
James Mattisd31bdfa2020-12-23 16:37:26 -08005888 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005889 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09005890 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08005891 private NetworkAgentInfo mSatisfier;
5892 NetworkAgentInfo getSatisfier() {
5893 return mSatisfier;
5894 }
5895
5896 // The request in mRequests assigned to a network agent. This is null if none of the
5897 // requests in mRequests can be satisfied. This member has the constraint of only being
5898 // accessible on the handler thread.
5899 @Nullable
5900 private NetworkRequest mActiveRequest;
5901 NetworkRequest getActiveRequest() {
5902 return mActiveRequest;
5903 }
5904
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005905 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08005906 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08005907 @Nullable
5908 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005909
5910 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08005911 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005912 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005913 final int mPid;
5914 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08005915 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005916 @Nullable
5917 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005918
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005919 // Counter keeping track of this NRI.
5920 final PerUidCounter mPerUidCounter;
5921
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005922 // Effective UID of this request. This is different from mUid when a privileged process
5923 // files a request on behalf of another UID. This UID is used to determine blocked status,
5924 // UID matching, and so on. mUid above is used for permission checks and to enforce the
5925 // maximum limit of registered callbacks per UID.
5926 final int mAsUid;
5927
paulhu48291862021-07-14 14:53:57 +08005928 // Preference order of this request.
5929 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08005930
James Mattis3ce3d3c2021-02-09 18:18:28 -08005931 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
5932 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
5933 // maintained for keying off of. This is only a concern when the original nri
5934 // mNetworkRequests changes which happens currently for apps that register callbacks to
5935 // track the default network. In those cases, the nri is updated to have mNetworkRequests
5936 // that match the per-app default nri that currently tracks the calling app's uid so that
5937 // callbacks are fired at the appropriate time. When the callbacks fire,
5938 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
5939 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
5940 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
5941 @NonNull
5942 private final NetworkRequest mNetworkRequestForCallback;
5943 NetworkRequest getNetworkRequestForCallback() {
5944 return mNetworkRequestForCallback;
5945 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005946
James Mattisd31bdfa2020-12-23 16:37:26 -08005947 /**
5948 * Get the list of UIDs this nri applies to.
5949 */
5950 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00005951 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08005952 // networkCapabilities.getUids() returns a defensive copy.
5953 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00005954 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
5955 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08005956 }
5957
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005958 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
5959 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08005960 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08005961 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08005962 }
5963
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005964 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08005965 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08005966 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005967 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08005968 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08005969 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005970 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08005971 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005972 mBinder = null;
5973 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005974 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005975 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005976 mPerUidCounter = getRequestCounter(this);
5977 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005978 /**
5979 * Location sensitive data not included in pending intent. Only included in
5980 * {@link NetworkCallback}.
5981 */
5982 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005983 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08005984 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005985 }
5986
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005987 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08005988 @Nullable final IBinder binder,
5989 @NetworkCallback.Flag int callbackFlags,
5990 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005991 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
5992 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08005993 }
5994
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005995 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08005996 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08005997 @Nullable final IBinder binder,
5998 @NetworkCallback.Flag int callbackFlags,
5999 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006000 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006001 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006002 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006003 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006004 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006005 mBinder = binder;
6006 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006007 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006008 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006009 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006010 mPerUidCounter = getRequestCounter(this);
6011 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006012 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006013 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006014 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006015 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006016 }
6017
James Mattis3ce3d3c2021-02-09 18:18:28 -08006018 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6019 @NonNull final List<NetworkRequest> r) {
6020 super();
6021 ensureAllNetworkRequestsHaveType(r);
6022 mRequests = initializeRequests(r);
6023 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006024 final NetworkAgentInfo satisfier = nri.getSatisfier();
6025 if (null != satisfier) {
6026 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6027 // The active request is necessary to figure out what callbacks to send, in
6028 // particular then a network updates its capabilities.
6029 // As this code creates a new NRI with a new set of requests, figure out which of
6030 // the list of requests should be the active request. It is always the first
6031 // request of the list that can be satisfied by the satisfier since the order of
6032 // requests is a priority order.
6033 // Note even in the presence of a satisfier there may not be an active request,
6034 // when the satisfier is the no-service network.
6035 NetworkRequest activeRequest = null;
6036 for (final NetworkRequest candidate : r) {
6037 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6038 activeRequest = candidate;
6039 break;
6040 }
6041 }
6042 setSatisfier(satisfier, activeRequest);
6043 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006044 mMessenger = nri.mMessenger;
6045 mBinder = nri.mBinder;
6046 mPid = nri.mPid;
6047 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006048 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006049 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006050 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006051 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006052 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006053 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006054 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006055 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006056 }
6057
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006058 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006059 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006060 }
6061
paulhue9913722021-05-26 15:19:20 +08006062 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006063 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006064 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006065 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006066 }
6067
James Mattis2516da32021-01-31 17:06:19 -08006068 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6069 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6070 // false.
6071 boolean isBeingSatisfied() {
6072 return (null != mSatisfier && null != mActiveRequest);
6073 }
6074
James Mattis3d229892020-11-16 16:46:28 -08006075 boolean isMultilayerRequest() {
6076 return mRequests.size() > 1;
6077 }
6078
James Mattis45d81842021-01-10 14:24:24 -08006079 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6080 // Creating a defensive copy to prevent the sender from modifying the list being
6081 // reflected in the return value of this method.
6082 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006083 return Collections.unmodifiableList(tempRequests);
6084 }
6085
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006086 void decrementRequestCount() {
6087 mPerUidCounter.decrementCount(mUid);
6088 }
6089
James Mattisb1392002021-03-31 13:57:52 -07006090 void linkDeathRecipient() {
6091 if (null != mBinder) {
6092 try {
6093 mBinder.linkToDeath(this, 0);
6094 } catch (RemoteException e) {
6095 binderDied();
6096 }
6097 }
6098 }
6099
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006100 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006101 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006102 try {
6103 mBinder.unlinkToDeath(this, 0);
6104 } catch (NoSuchElementException e) {
6105 // Temporary workaround for b/194394697 pending analysis of additional logs
6106 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6107 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006108 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006109 }
6110
paulhu48291862021-07-14 14:53:57 +08006111 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6112 // Compare two preference orders.
6113 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006114 }
6115
paulhu48291862021-07-14 14:53:57 +08006116 int getPreferenceOrderForNetd() {
6117 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6118 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6119 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006120 }
paulhu48291862021-07-14 14:53:57 +08006121 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006122 }
6123
James Mattis4fce5d12020-11-12 15:53:42 -08006124 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006125 public void binderDied() {
6126 log("ConnectivityService NetworkRequestInfo binderDied(" +
Chalard Jean524f0b12021-10-25 21:11:56 +09006127 "uid/pid:" + mUid + "/" + mPid + ", " + mRequests + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09006128 // As an immutable collection, mRequests cannot change by the time the
6129 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6130 // is acceptable. Use handleReleaseNetworkRequest and not directly
6131 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6132 // the app already unregistered the request.
6133 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6134 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006135 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006136
James Mattis4fce5d12020-11-12 15:53:42 -08006137 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006138 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006139 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6140 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006141 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006142 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006143 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006144 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006145 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006146 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006147 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006148 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006149 }
6150
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006151 // This checks that the passed capabilities either do not request a
6152 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006153 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006154 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006155 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006156 throw new SecurityException("Insufficient permissions to request a specific SSID");
6157 }
paulhu1a407652019-03-22 16:35:06 +08006158
6159 if (nc.hasSignalStrength()
6160 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6161 throw new SecurityException(
6162 "Insufficient permissions to request a specific signal strength");
6163 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006164 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006165
junyulai2217bec2021-04-14 23:33:31 +08006166 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006167 enforceNetworkFactoryPermission();
6168 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006169 }
6170
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006171 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006172 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006173 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006174 // mNetworkRequests may contain the same value multiple times in case of
6175 // multilayer requests. It won't matter in this case because the thresholds
6176 // will then be the same and be deduplicated as they enter the `thresholds` set.
6177 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006178 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6179 for (final NetworkRequest req : nri.mRequests) {
6180 if (req.networkCapabilities.hasSignalStrength()
6181 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6182 thresholds.add(req.networkCapabilities.getSignalStrength());
6183 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006184 }
6185 }
6186 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006187 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006188 }
6189
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006190 private void updateSignalStrengthThresholds(
6191 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006192 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006193
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006194 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006195 String detail;
6196 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6197 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6198 } else {
6199 detail = reason;
6200 }
6201 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006202 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006203 }
6204
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006205 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006206 }
6207
Chalard Jeandd421992021-12-16 23:16:02 +09006208 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07006209 if (nc == null) {
6210 return;
6211 }
6212 NetworkSpecifier ns = nc.getNetworkSpecifier();
6213 if (ns == null) {
6214 return;
6215 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006216 if (ns instanceof MatchAllNetworkSpecifier) {
6217 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6218 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006219 }
6220
Chalard Jeandd421992021-12-16 23:16:02 +09006221 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08006222 ensureValidNetworkSpecifier(nc);
6223 if (nc.isPrivateDnsBroken()) {
6224 throw new IllegalArgumentException("Can't request broken private DNS");
6225 }
Chalard Jean9a30acf2021-12-13 22:53:51 +09006226 if (nc.hasAccessUids()) {
6227 throw new IllegalArgumentException("Can't request access UIDs");
6228 }
lucasline117e2e2019-10-22 18:27:33 +08006229 }
6230
Chalard Jeandd421992021-12-16 23:16:02 +09006231 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
6232 ensureListenableCapabilities(nc);
6233 final String badCapability = nc.describeFirstNonRequestableCapability();
6234 if (badCapability != null) {
6235 throw new IllegalArgumentException("Cannot request network with " + badCapability);
6236 }
6237 }
6238
Chiachang Wang3bc52762021-11-25 14:17:57 +08006239 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6240 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006241 private boolean isTargetSdkAtleast(int version, int callingUid,
6242 @NonNull String callingPackageName) {
6243 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006244 final PackageManager pm =
6245 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006246 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006247 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006248 if (callingVersion < version) return false;
6249 } catch (PackageManager.NameNotFoundException e) { }
6250 return true;
6251 }
6252
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006253 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006254 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006255 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006256 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006257 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006258 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006259 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6260 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006261 throw new SecurityException("Insufficient permissions to specify legacy type");
6262 }
markchienfac84a22020-03-18 21:16:15 +08006263 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006264 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006265 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006266 // Privileged callers can track the default network of another UID by passing in a UID.
6267 if (asUid != Process.INVALID_UID) {
6268 enforceSettingsPermission();
6269 } else {
6270 asUid = callingUid;
6271 }
junyulaiad010792021-01-11 16:53:38 +08006272 final NetworkRequest.Type reqType;
6273 try {
6274 reqType = NetworkRequest.Type.values()[reqTypeInt];
6275 } catch (ArrayIndexOutOfBoundsException e) {
6276 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6277 }
6278 switch (reqType) {
6279 case TRACK_DEFAULT:
6280 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006281 // is unused and will be replaced by ones appropriate for the UID (usually, the
6282 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006283 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006284 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006285 enforceAccessPermission();
6286 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006287 case TRACK_SYSTEM_DEFAULT:
6288 enforceSettingsPermission();
6289 networkCapabilities = new NetworkCapabilities(defaultNc);
6290 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006291 case BACKGROUND_REQUEST:
6292 enforceNetworkStackOrSettingsPermission();
6293 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006294 case REQUEST:
6295 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6296 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6297 callingAttributionTag);
6298 // TODO: this is incorrect. We mark the request as metered or not depending on
6299 // the state of the app when the request is filed, but we never change the
6300 // request if the app changes network state. http://b/29964605
6301 enforceMeteredApnPolicy(networkCapabilities);
6302 break;
junyulai1b1c8742021-03-12 20:05:08 +08006303 case LISTEN_FOR_BEST:
6304 enforceAccessPermission();
6305 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6306 break;
junyulaiad010792021-01-11 16:53:38 +08006307 default:
6308 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006309 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006310 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006311 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006312 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006313
junyulai1b1c8742021-03-12 20:05:08 +08006314 // Enforce FOREGROUND if the caller does not have permission to use background network.
6315 if (reqType == LISTEN_FOR_BEST) {
6316 restrictBackgroundRequestForCaller(networkCapabilities);
6317 }
6318
6319 // Set the UID range for this request to the single UID of the requester, unless the
6320 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006321 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6322 // are no visible methods to set the UIDs, an app could use reflection to try and get
6323 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006324 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006325 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6326 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006327
Etan Cohen85000162017-02-05 10:42:27 -08006328 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006329 throw new IllegalArgumentException("Bad timeout specified");
6330 }
Etan Cohen9786d922015-11-18 10:56:15 -08006331
James Mattis3ce3d3c2021-02-09 18:18:28 -08006332 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006333 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006334 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006335 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006336 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006337 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006338
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006339 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6340 // copied from the default request above. (This is necessary to ensure, for example, that
6341 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6342 // changes don't alter request matching.
6343 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6344 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006345 throw new IllegalStateException(
6346 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006347 + networkCapabilities + " vs. " + defaultNc);
6348 }
6349
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006350 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006351 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006352 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006353 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006354 }
6355 return networkRequest;
6356 }
6357
James Mattis3ce3d3c2021-02-09 18:18:28 -08006358 /**
6359 * Return the nri to be used when registering a network request. Specifically, this is used with
6360 * requests registered to track the default request. If there is currently a per-app default
6361 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6362 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006363 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6364 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006365 * @param nr the network request for the nri.
6366 * @param msgr the messenger for the nri.
6367 * @param binder the binder for the nri.
6368 * @param callingAttributionTag the calling attribution tag for the nri.
6369 * @return the nri to register.
6370 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006371 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006372 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006373 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006374 @Nullable String callingAttributionTag) {
6375 final List<NetworkRequest> requests;
6376 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6377 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006378 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006379 } else {
6380 requests = Collections.singletonList(nr);
6381 }
Roshan Pius951c0032020-12-22 15:10:42 -08006382 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006383 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006384 }
6385
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006386 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
6387 String callingPackageName, String callingAttributionTag) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006388 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006389 if (!networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)) {
6390 enforceConnectivityRestrictedNetworksPermission();
6391 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006392 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006393 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006394 }
6395 }
6396
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006397 private boolean checkConnectivityRestrictedNetworksPermission(int callerPid, int callerUid) {
6398 if (checkAnyPermissionOf(callerPid, callerUid,
6399 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)
6400 || checkAnyPermissionOf(callerPid, callerUid,
6401 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
6402 return true;
6403 }
6404 return false;
6405 }
6406
fenglu3f357402015-03-20 11:29:56 -07006407 @Override
fenglub00f4882015-04-21 17:12:05 -07006408 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006409 enforceAccessPermission();
6410 NetworkAgentInfo nai = null;
6411 if (network == null) {
6412 return false;
6413 }
6414 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006415 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006416 }
6417 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006418 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006419 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006420 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006421 Integer uidReqs = mBandwidthRequests.get(uid);
6422 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006423 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006424 }
6425 mBandwidthRequests.put(uid, ++uidReqs);
6426 }
fenglu3f357402015-03-20 11:29:56 -07006427 return true;
6428 }
6429 return false;
6430 }
6431
Felipe Leme0a5ae422016-06-20 16:36:29 -07006432 private boolean isSystem(int uid) {
6433 return uid < Process.FIRST_APPLICATION_UID;
6434 }
fenglu3f357402015-03-20 11:29:56 -07006435
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006436 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006437 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006438 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006439 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006440 return;
6441 }
Hugo Benichi39621362017-02-11 17:04:43 +09006442 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6443 // Policy already enforced.
6444 return;
6445 }
paulhuaf50d7d2020-12-24 19:47:34 +08006446 final long ident = Binder.clearCallingIdentity();
6447 try {
6448 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6449 // If UID is restricted, don't allow them to bring up metered APNs.
6450 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6451 }
6452 } finally {
6453 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006454 }
6455 }
6456
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006457 @Override
6458 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006459 PendingIntent operation, @NonNull String callingPackageName,
6460 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006461 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006462 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006463 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006464 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6465 callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006466 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006467 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006468 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006469 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006470 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6471 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09006472
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006473 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006474 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006475 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6476 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006477 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006478 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6479 nri));
6480 return networkRequest;
6481 }
6482
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006483 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6484 mHandler.sendMessageDelayed(
6485 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006486 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006487 }
6488
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006489 @Override
6490 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006491 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006492 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006493 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006494 }
6495
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006496 // In order to implement the compatibility measure for pre-M apps that call
6497 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6498 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6499 // This ensures it has permission to do so.
6500 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6501 if (nc == null) {
6502 return false;
6503 }
6504 int[] transportTypes = nc.getTransportTypes();
6505 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6506 return false;
6507 }
6508 try {
6509 mContext.enforceCallingOrSelfPermission(
6510 android.Manifest.permission.ACCESS_WIFI_STATE,
6511 "ConnectivityService");
6512 } catch (SecurityException e) {
6513 return false;
6514 }
6515 return true;
6516 }
6517
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006518 @Override
6519 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08006520 Messenger messenger, IBinder binder,
6521 @NetworkCallback.Flag int callbackFlags,
6522 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006523 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006524 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6525 enforceAccessPermission();
6526 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006527
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006528 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006529 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006530 Binder.getCallingPid(), callingUid, callingPackageName);
6531 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09006532 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6533 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6534 // onLost and onAvailable callbacks when networks move in and out of the background.
6535 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6536 // can't request networks.
6537 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09006538 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07006539
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006540 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006541 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08006542 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006543 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08006544 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006545 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006546
6547 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6548 return networkRequest;
6549 }
6550
6551 @Override
6552 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08006553 PendingIntent operation, @NonNull String callingPackageName,
6554 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006555 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006556 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04006557 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6558 enforceAccessPermission();
6559 }
Chalard Jeandd421992021-12-16 23:16:02 +09006560 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006561 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006562 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006563 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006564 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006565
6566 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006567 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006568 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6569 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006570 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04006571
WeiZhang1cc3f172021-06-03 19:02:04 -05006572 mHandler.sendMessage(mHandler.obtainMessage(
6573 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006574 }
6575
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006576 /** Returns the next Network provider ID. */
6577 public final int nextNetworkProviderId() {
6578 return mNextNetworkProviderId.getAndIncrement();
6579 }
6580
Erik Kline0c04b742016-07-07 16:50:58 +09006581 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006582 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006583 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09006584 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006585 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006586 }
6587
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006588 private void releaseNetworkRequestAndCallOnUnavailable(NetworkRequest networkRequest) {
6589 ensureNetworkRequestHasType(networkRequest);
6590 mHandler.sendMessage(mHandler.obtainMessage(
6591 EVENT_RELEASE_NETWORK_REQUEST_AND_CALL_UNAVAILABLE, mDeps.getCallingUid(), 0,
6592 networkRequest));
6593 }
6594
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006595 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6596 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006597 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6598 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6599 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08006600 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006601 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006602 return;
6603 }
6604
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006605 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6606 mNetworkProviderInfos.put(npi.messenger, npi);
6607 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006608 }
6609
6610 @Override
6611 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006612 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08006613 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006614 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08006615 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006616 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6617 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006618 }
6619
6620 @Override
6621 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006622 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006623 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006624 }
6625
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006626 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09006627 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006628 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6629 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09006630 Objects.requireNonNull(score);
6631 Objects.requireNonNull(caps);
6632 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09006633 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006634 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09006635 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
6636 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006637 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6638 }
6639
Chalard Jeanbb902a52021-08-18 01:35:19 +09006640 private void updateOfferScore(final NetworkOffer offer) {
6641 final boolean yieldToBadWiFi =
6642 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
6643 final NetworkOffer newOffer = new NetworkOffer(
6644 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
6645 offer.caps, offer.callback, offer.providerId);
6646 if (offer.equals(newOffer)) return;
6647 handleRegisterNetworkOffer(newOffer);
6648 }
6649
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006650 @Override
6651 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6652 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6653 }
6654
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006655 private void handleUnregisterNetworkProvider(Messenger messenger) {
6656 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6657 if (npi == null) {
6658 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006659 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006660 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006661 // Unregister all the offers from this provider
6662 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6663 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09006664 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006665 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6666 toRemove.add(noi);
6667 }
6668 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09006669 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006670 handleUnregisterNetworkOffer(noi);
6671 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006672 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006673 }
6674
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006675 @Override
James Mattisf7027322020-12-13 16:28:14 -08006676 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006677 if (request.hasTransport(TRANSPORT_TEST)) {
6678 enforceNetworkFactoryOrTestNetworksPermission();
6679 } else {
6680 enforceNetworkFactoryPermission();
6681 }
James Mattisf7027322020-12-13 16:28:14 -08006682 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6683 if (nri != null) {
6684 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6685 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6686 mHandler.post(() -> handleReleaseNetworkRequest(
6687 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6688 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006689 }
6690
Paul Jensen1f567382015-02-13 14:18:39 -05006691 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6692 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006693 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05006694 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006695 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05006696 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006697 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006698
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09006699 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05006700 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006701 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006702
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006703 // UID ranges for users that are currently blocked by VPNs.
6704 // This array is accessed and iterated on multiple threads without holding locks, so its
6705 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6706 // (on the handler thread).
6707 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6708
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006709 // Must only be accessed on the handler thread
6710 @NonNull
6711 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6712
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006713 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006714 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006715
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006716 // Current OEM network preferences. This object must only be written to on the handler thread.
6717 // Since it is immutable and always non-null, other threads may read it if they only care
6718 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08006719 @NonNull
6720 private OemNetworkPreferences mOemNetworkPreferences =
6721 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006722 // Current per-profile network preferences. This object follows the same threading rules as
6723 // the OEM network preferences above.
6724 @NonNull
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006725 private ProfileNetworkPreferenceList mProfileNetworkPreferences =
6726 new ProfileNetworkPreferenceList();
James Mattis45d81842021-01-10 14:24:24 -08006727
paulhu51f77dc2021-06-07 02:34:20 +00006728 // A set of UIDs that should use mobile data preferentially if available. This object follows
6729 // the same threading rules as the OEM network preferences above.
6730 @NonNull
6731 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
6732
James Mattiscb1e0362021-04-06 17:07:42 -07006733 // OemNetworkPreferences activity String log entries.
6734 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6735 @NonNull
6736 private final LocalLog mOemNetworkPreferencesLogs =
6737 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6738
James Mattis02220e22021-03-13 19:27:21 -08006739 /**
6740 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6741 * @param packageName the package name to check existence of a mapping for.
6742 * @return true if a mapping exists, false otherwise
6743 */
6744 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6745 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6746 }
6747
James Mattise3ef1912020-12-20 11:09:58 -08006748 // The always-on request for an Internet-capable network that apps without a specific default
6749 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08006750 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09006751 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006752 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08006753 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08006754 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08006755 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006756 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006757
James Mattisd31bdfa2020-12-23 16:37:26 -08006758 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6759 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6760 }
6761
6762 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08006763 * Return the default network request currently tracking the given uid.
6764 * @param uid the uid to check.
6765 * @return the NetworkRequestInfo tracking the given uid.
6766 */
6767 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08006768 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08006769 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006770 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006771 // Checking the first request is sufficient as only multilayer requests will have more
6772 // than one request and for multilayer, all requests will track the same uids.
6773 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08006774 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08006775 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08006776 highestPriorityNri = nri;
6777 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006778 }
6779 }
paulhuaa0743d2021-05-26 21:56:03 +08006780 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006781 }
6782
6783 /**
6784 * Get a copy of the network requests of the default request that is currently tracking the
6785 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006786 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6787 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006788 * @param requestorUid the uid to check the default for.
6789 * @param requestorPackageName the requestor's package name.
6790 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6791 */
6792 @NonNull
6793 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006794 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006795 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006796 getDefaultRequestTrackingUid(asUid).mRequests,
6797 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006798 }
6799
6800 /**
6801 * Copy the given nri's NetworkRequest collection.
6802 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006803 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6804 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006805 * @param requestorUid the uid to set on the copied collection.
6806 * @param requestorPackageName the package name to set on the copied collection.
6807 * @return the copied NetworkRequest collection.
6808 */
6809 @NonNull
6810 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006811 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6812 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006813 final List<NetworkRequest> requests = new ArrayList<>();
6814 for (final NetworkRequest nr : requestsToCopy) {
6815 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006816 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08006817 nr.legacyType, nextNetworkRequestId(), nr.type));
6818 }
6819 return requests;
6820 }
6821
6822 @NonNull
6823 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006824 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6825 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09006826 // These capabilities are for a TRACK_DEFAULT callback, so:
6827 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6828 // mDefaultRequest and a per-UID default request.
6829 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006830 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09006831 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006832 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6833 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006834 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006835 restrictRequestUidsForCallerAndSetRequestorInfo(
6836 netCap, requestorUid, requestorPackageName);
6837 return netCap;
6838 }
6839
6840 /**
6841 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6842 * @param nr the network request to check for equality against.
6843 * @return the nri if one exists, null otherwise.
6844 */
6845 @Nullable
6846 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6847 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6848 if (nri.getNetworkRequestForCallback().equals(nr)) {
6849 return nri;
6850 }
6851 }
6852 return null;
6853 }
6854
6855 /**
6856 * Check if an nri is currently being managed by per-app default networking.
6857 * @param nri the nri to check.
6858 * @return true if this nri is currently being managed by per-app default networking.
6859 */
6860 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
6861 // nri.mRequests.get(0) is only different from the original request filed in
6862 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
6863 // functionality therefore if these two don't match, it means this particular nri is
6864 // currently being managed by a per-app default.
6865 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
6866 }
6867
6868 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08006869 * Determine if an nri is a managed default request that disallows default networking.
6870 * @param nri the request to evaluate
6871 * @return true if device-default networking is disallowed
6872 */
6873 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
6874 // Check if this nri is a managed default that supports the default network at its
6875 // lowest priority request.
6876 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
6877 final NetworkCapabilities lowestPriorityNetCap =
6878 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
6879 return isPerAppDefaultRequest(nri)
6880 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
6881 lowestPriorityNetCap));
6882 }
6883
Erik Kline05f2b402015-04-30 12:58:40 +09006884 // Request used to optionally keep mobile data active even when higher
6885 // priority networks like Wi-Fi are active.
6886 private final NetworkRequest mDefaultMobileDataRequest;
6887
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006888 // Request used to optionally keep wifi data active even when higher
6889 // priority networks like ethernet are active.
6890 private final NetworkRequest mDefaultWifiRequest;
6891
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08006892 // Request used to optionally keep vehicle internal network always active
6893 private final NetworkRequest mDefaultVehicleRequest;
6894
James Mattisd31bdfa2020-12-23 16:37:26 -08006895 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
6896 // network with no service. This NAI should never be matched against, nor should any public API
6897 // ever return the associated network. For this reason, this NAI is not in the list of available
6898 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
6899 // default requests that don't support using the device default network which will ultimately
6900 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
6901 @VisibleForTesting
6902 final NetworkAgentInfo mNoServiceNetwork;
6903
Chalard Jean5b409c72021-02-04 13:12:59 +09006904 // The NetworkAgentInfo currently satisfying the default request, if any.
6905 private NetworkAgentInfo getDefaultNetwork() {
6906 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09006907 }
6908
James Mattis2516da32021-01-31 17:06:19 -08006909 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08006910 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08006911 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6912 // Currently, all network requests will have the same uids therefore checking the first
6913 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006914 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08006915 if (null == uids) {
6916 continue;
6917 }
6918 for (final UidRange range : uids) {
6919 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08006920 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08006921 highestPriorityNri = nri;
6922 }
James Mattis2516da32021-01-31 17:06:19 -08006923 }
6924 }
6925 }
paulhuaa0743d2021-05-26 21:56:03 +08006926 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08006927 }
6928
Varun Ananddf569952019-02-06 10:13:38 -08006929 @Nullable
6930 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
6931 return nai != null ? nai.network : null;
6932 }
6933
6934 private void ensureRunningOnConnectivityServiceThread() {
6935 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
6936 throw new IllegalStateException(
6937 "Not running on ConnectivityService thread: "
6938 + Thread.currentThread().getName());
6939 }
6940 }
6941
Chalard Jean3a3f5f22019-04-10 23:07:55 +09006942 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09006943 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
6944 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006945 }
6946
Chalard Jean29d06db2018-05-02 21:14:54 +09006947 /**
6948 * Register a new agent with ConnectivityService to handle a network.
6949 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006950 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09006951 * @param networkInfo the initial info associated with this network. It can be updated later :
6952 * see {@link #updateNetworkInfo}.
6953 * @param linkProperties the initial link properties of this network. They can be updated
6954 * later : see {@link #updateLinkProperties}.
6955 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09006956 * later : see {@link #updateCapabilities}.
Chalard Jean28018572020-12-21 18:36:52 +09006957 * @param initialScore the initial score of the network. See
Chalard Jean29d06db2018-05-02 21:14:54 +09006958 * {@link NetworkAgentInfo#getCurrentScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006959 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006960 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09006961 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09006962 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006963 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09006964 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09006965 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
6966 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09006967 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
6968 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
6969 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09006970 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09006971 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09006972 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6973 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006974 } else {
6975 enforceNetworkFactoryPermission();
6976 }
6977
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006978 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006979 final long token = Binder.clearCallingIdentity();
6980 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006981 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09006982 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006983 } finally {
6984 Binder.restoreCallingIdentity(token);
6985 }
6986 }
6987
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006988 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006989 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09006990 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
6991 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006992
Chalard Jean366c5252022-01-25 18:27:53 +09006993 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
6994 // the capabilities' access UID comply with security limitations. They will be sanitized
6995 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
6996 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006997 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jean366c5252022-01-25 18:27:53 +09006998 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo),
6999 linkProperties, networkCapabilities,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007000 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007001 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7002 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007003
Chalard Jeanf2da1772018-04-26 16:16:10 +09007004 final String extraInfo = networkInfo.getExtraInfo();
7005 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007006 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007007 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007008 mDeps.getNetworkStack().makeNetworkMonitor(
7009 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007010 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7011 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007012 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007013 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007014 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007015 }
7016
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007017 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007018 if (VDBG) log("Network Monitor created for " + nai);
7019 // nai.nc and nai.lp are the same object that was passed by the network agent if the agent
7020 // lives in the same process as this code (e.g. wifi), so make sure this code doesn't
7021 // mutate their object
7022 final NetworkCapabilities nc = new NetworkCapabilities(nai.networkCapabilities);
7023 final LinkProperties lp = new LinkProperties(nai.linkProperties);
7024 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
7025 processCapabilitiesFromAgent(nai, nc);
7026 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
7027 processLinkPropertiesFromAgent(nai, lp);
7028 nai.linkProperties = lp;
7029
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007030 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007031
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007032 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007033 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007034 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007035 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007036
7037 try {
7038 networkMonitor.start();
7039 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007040 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007041 }
Chalard Jean366c5252022-01-25 18:27:53 +09007042
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007043 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007044 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007045 updateNetworkInfo(nai, networkInfo);
7046 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007047 }
7048
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007049 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7050 @NonNull public final NetworkOffer offer;
7051
7052 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7053 this.offer = offer;
7054 }
7055
7056 @Override
7057 public void binderDied() {
7058 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7059 }
7060 }
7061
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007062 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7063 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7064 if (npi.providerId == providerId) return true;
7065 }
7066 return false;
7067 }
7068
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007069 /**
7070 * Register or update a network offer.
7071 * @param newOffer The new offer. If the callback member is the same as an existing
7072 * offer, it is an update of that offer.
7073 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007074 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007075 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7076 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007077 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007078 // This may actually happen if a provider updates its score or registers and then
7079 // immediately unregisters. The offer would still be in the handler queue, but the
7080 // provider would have been removed.
7081 if (DBG) log("Received offer from an unregistered provider");
7082 return;
7083 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007084 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7085 if (null != existingOffer) {
7086 handleUnregisterNetworkOffer(existingOffer);
7087 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007088 if (DBG) {
7089 // handleUnregisterNetworkOffer has already logged the old offer
7090 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7091 }
7092 } else {
7093 if (DBG) {
7094 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7095 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007096 }
7097 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7098 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007099 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007100 } catch (RemoteException e) {
7101 noi.binderDied();
7102 return;
7103 }
7104 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007105 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007106 }
7107
7108 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7109 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007110 if (DBG) {
7111 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7112 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007113
7114 // If the provider removes the offer and dies immediately afterwards this
7115 // function may be called twice in a row, but the array will no longer contain
7116 // the offer.
7117 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007118 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007119 }
7120
7121 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7122 @NonNull final INetworkOfferCallback callback) {
7123 ensureRunningOnConnectivityServiceThread();
7124 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007125 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007126 }
7127 return null;
7128 }
7129
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007130 /**
7131 * Called when receiving LinkProperties directly from a NetworkAgent.
7132 * Stores into |nai| any data coming from the agent that might also be written to the network's
7133 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7134 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007135 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007136 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007137 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7138 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007139 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007140 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007141 }
7142
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007143 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007144 @NonNull LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007145 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007146
Lorenzo Colittid523d142020-04-01 20:16:30 +09007147 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7148 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7149 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007150 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007151
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007152 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007153
7154 // update filtering rules, need to happen after the interface update so netd knows about the
7155 // new interface (the interface name -> index map becomes initialized)
7156 updateVpnFiltering(newLp, oldLp, networkAgent);
7157
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007158 updateMtu(newLp, oldLp);
7159 // TODO - figure out what to do for clat
7160// for (LinkProperties lp : newLp.getStackedLinks()) {
7161// updateMtu(lp, null);
7162// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007163 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007164 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7165 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007166
Erik Klineb9888902016-04-05 13:30:49 +09007167 updateRoutes(newLp, oldLp, netId);
7168 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007169 // Make sure LinkProperties represents the latest private DNS status.
7170 // This does not need to be done before updateDnses because the
7171 // LinkProperties are not the source of the private DNS configuration.
7172 // updateDnses will fetch the private DNS configuration from DnsManager.
7173 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007174
Chalard Jean5b409c72021-02-04 13:12:59 +09007175 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007176 handleApplyDefaultProxy(newLp.getHttpProxy());
7177 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007178 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007179 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007180
7181 updateWakeOnLan(newLp);
7182
Hai Shalome58bdc62021-01-11 18:45:34 -08007183 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7184 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7185 // does, it needs to be merged here.
7186 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7187 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007188
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007189 // TODO - move this check to cover the whole function
7190 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007191 synchronized (networkAgent) {
7192 networkAgent.linkProperties = newLp;
7193 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007194 // Start or stop DNS64 detection and 464xlat according to network state.
7195 networkAgent.clatd.update();
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08007196 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007197 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7198 new LinkProperties(newLp, true /* parcelSensitiveFields */));
lucaslin74fa3972018-11-28 12:51:55 +08007199 if (networkAgent.everConnected) {
7200 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
7201 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007202 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007203
7204 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007205 }
7206
Hai Shalome58bdc62021-01-11 18:45:34 -08007207 /**
7208 * @param naData captive portal data from NetworkAgent
7209 * @param apiData captive portal data from capport API
7210 */
7211 @Nullable
7212 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7213 CaptivePortalData apiData) {
7214 if (naData == null || apiData == null) {
7215 return naData == null ? apiData : naData;
7216 }
7217 final CaptivePortalData.Builder captivePortalBuilder =
7218 new CaptivePortalData.Builder(naData);
7219
7220 if (apiData.isCaptive()) {
7221 captivePortalBuilder.setCaptive(true);
7222 }
7223 if (apiData.isSessionExtendable()) {
7224 captivePortalBuilder.setSessionExtendable(true);
7225 }
7226 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7227 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7228 // otherwise data would be inconsistent. Prefer the capport API info if present,
7229 // as it can generally be refreshed more often.
7230 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7231 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7232 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7233 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7234 // No source has time / bytes remaining information: surface the newest refresh time
7235 // for other fields
7236 captivePortalBuilder.setRefreshTime(
7237 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7238 }
7239
Hai Shalom7c6ab402021-02-04 19:34:06 -08007240 // Prioritize the user portal URL from the network agent if the source is authenticated.
7241 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7242 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7243 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7244 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007245 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007246 // Prioritize the venue information URL from the network agent if the source is
7247 // authenticated.
7248 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7249 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7250 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7251 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007252 }
7253 return captivePortalBuilder.build();
7254 }
7255
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007256 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007257 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007258 // marks on unsupported interfaces is harmless.
7259 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7260 return;
7261 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007262
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007263 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7264 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7265
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007266 // Mask/mark of zero will not detect anything interesting.
7267 // Don't install rules unless both values are nonzero.
7268 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007269 return;
7270 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007271
7272 final String prefix = "iface:" + iface;
7273 try {
7274 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007275 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007276 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007277 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007278 }
7279 } catch (Exception e) {
7280 loge("Exception modifying wakeup packet monitoring: " + e);
7281 }
7282
Joel Scherpelza235a812017-05-22 13:47:41 +09007283 }
7284
Chalard Jean9589e722019-11-19 19:03:53 +09007285 private void updateInterfaces(final @Nullable LinkProperties newLp,
7286 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007287 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09007288 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fa7d9e2017-08-22 16:35:52 +01007289 oldLp != null ? oldLp.getAllInterfaceNames() : null,
7290 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jean9589e722019-11-19 19:03:53 +09007291 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007292 for (final String iface : interfaceDiff.added) {
7293 try {
7294 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007295 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09007296 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007297 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7298 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007299 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007300 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007301 }
Paul Jensenbff73492014-04-28 10:33:11 -04007302 }
7303 }
Chalard Jean9589e722019-11-19 19:03:53 +09007304 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007305 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007306 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007307 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007308 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007309 } catch (Exception e) {
7310 loge("Exception removing interface: " + e);
7311 }
7312 }
7313 }
7314
Tyler Weare4314862019-12-05 14:55:30 -08007315 // TODO: move to frameworks/libs/net.
7316 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7317 final String nextHop;
7318
7319 switch (route.getType()) {
7320 case RouteInfo.RTN_UNICAST:
7321 if (route.hasGateway()) {
7322 nextHop = route.getGateway().getHostAddress();
7323 } else {
7324 nextHop = INetd.NEXTHOP_NONE;
7325 }
7326 break;
7327 case RouteInfo.RTN_UNREACHABLE:
7328 nextHop = INetd.NEXTHOP_UNREACHABLE;
7329 break;
7330 case RouteInfo.RTN_THROW:
7331 nextHop = INetd.NEXTHOP_THROW;
7332 break;
7333 default:
7334 nextHop = INetd.NEXTHOP_NONE;
7335 break;
7336 }
7337
7338 final RouteInfoParcel rip = new RouteInfoParcel();
7339 rip.ifName = route.getInterface();
7340 rip.destination = route.getDestination().toString();
7341 rip.nextHop = nextHop;
7342 rip.mtu = route.getMtu();
7343
7344 return rip;
7345 }
7346
Paul Jensene0fd4a82014-08-06 15:51:33 -04007347 /**
7348 * Have netd update routes from oldLp to newLp.
7349 * @return true if routes changed between oldLp and newLp
7350 */
7351 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007352 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007353 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7354 new CompareOrUpdateResult<>(
7355 oldLp != null ? oldLp.getAllRoutes() : null,
7356 newLp != null ? newLp.getAllRoutes() : null,
7357 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007358
7359 // add routes before removing old in case it helps with continuous connectivity
7360
Chalard Jean9dd11612018-06-04 16:52:49 +09007361 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007362 for (RouteInfo route : routeDiff.added) {
7363 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007364 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007365 try {
Tyler Weare4314862019-12-05 14:55:30 -08007366 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007367 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007368 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007369 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007370 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007371 }
7372 }
7373 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007374 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007375 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007376 try {
Tyler Weare4314862019-12-05 14:55:30 -08007377 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007378 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007379 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007380 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007381 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007382 }
7383 }
7384
7385 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007386 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007387 try {
Tyler Weare4314862019-12-05 14:55:30 -08007388 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007389 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007390 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007391 }
7392 }
Tyler Weare4314862019-12-05 14:55:30 -08007393
7394 for (RouteInfo route : routeDiff.updated) {
7395 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7396 try {
7397 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7398 } catch (Exception e) {
7399 loge("Exception in networkUpdateRouteParcel: " + e);
7400 }
7401 }
7402 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7403 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007404 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007405
Erik Klineb9888902016-04-05 13:30:49 +09007406 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7407 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7408 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007409 }
Erik Klineb9888902016-04-05 13:30:49 +09007410
Erik Kline31b4a9e2018-01-11 21:07:29 +09007411 if (DBG) {
7412 final Collection<InetAddress> dnses = newLp.getDnsServers();
7413 log("Setting DNS servers for network " + netId + " to " + dnses);
7414 }
Erik Klineb9888902016-04-05 13:30:49 +09007415 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007416 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007417 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007418 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007419 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007420 }
Erik Kline54e35c02017-04-07 15:29:29 +09007421 }
7422
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007423 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7424 NetworkAgentInfo nai) {
7425 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
7426 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
7427 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
7428 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
7429
7430 if (!wasFiltering && !needsFiltering) {
7431 // Nothing to do.
7432 return;
7433 }
7434
7435 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7436 // Nothing changed.
7437 return;
7438 }
7439
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007440 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Qingxi Libb8da982020-01-17 17:54:27 -08007441 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007442 // TODO: this create a window of opportunity for apps to receive traffic between the time
7443 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007444 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007445 // old rules are being removed.
7446 if (wasFiltering) {
7447 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7448 }
7449 if (needsFiltering) {
7450 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7451 }
7452 }
7453
Valentin Iftime9fa35092019-09-24 13:32:13 +02007454 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007455 if (mWolSupportedInterfaces == null) {
7456 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007457 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007458 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007459 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7460 }
7461
Luke Huangb913c812018-08-24 20:33:16 +08007462 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007463 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007464 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007465 }
7466 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007467 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007468 }
Luke Huangb913c812018-08-24 20:33:16 +08007469 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007470 }
7471
Chalard Jean62edfd82019-12-02 18:39:29 +09007472 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7473 @NonNull final NetworkCapabilities newNc) {
7474 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7475 final int newPermission = getNetworkPermission(newNc);
7476 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7477 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007478 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08007479 } catch (RemoteException | ServiceSpecificException e) {
7480 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09007481 }
7482 }
7483 }
7484
Paul Jensen53f08952015-06-16 14:27:36 -04007485 /**
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007486 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7487 * Stores into |nai| any data coming from the agent that might also be written to the network's
7488 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7489 * agent is not lost when updateCapabilities is called.
7490 */
7491 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
Chalard Jean15228572022-01-28 19:29:12 +09007492 if (nc.hasConnectivityManagedCapability()) {
7493 Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
7494 }
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007495 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7496 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7497 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7498 // the owner UID here and behave as if the agent had never tried to change it.
Lorenzo Colitti93401342020-12-09 18:30:52 +09007499 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7500 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7501 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7502 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7503 }
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007504 nai.declaredCapabilities = new NetworkCapabilities(nc);
Chalard Jeanac9ace02022-01-26 16:54:05 +09007505 NetworkAgentInfo.restrictCapabilitiesFromNetworkAgent(nc, nai.creatorUid,
7506 mCarrierPrivilegeAuthenticator);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007507 }
7508
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007509 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007510 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09007511 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007512 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08007513 underlyingNetworks = underlyingNetworksOrDefault(
7514 agentCaps.getOwnerUid(), underlyingNetworks);
lifrade6c2a2021-03-04 14:08:08 +08007515 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007516 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7517 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007518 // metered if any underlying is metered, or originally declared metered by the agent.
7519 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007520 boolean roaming = false; // roaming if any underlying is roaming
7521 boolean congested = false; // congested if any underlying is congested
7522 boolean suspended = true; // suspended if all underlying are suspended
7523
7524 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08007525 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007526 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08007527 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007528 for (Network underlyingNetwork : underlyingNetworks) {
7529 final NetworkAgentInfo underlying =
7530 getNetworkAgentInfoForNetwork(underlyingNetwork);
7531 if (underlying == null) continue;
7532
7533 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7534 hadUnderlyingNetworks = true;
7535 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007536 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007537 }
7538
7539 // Merge capabilities of this underlying network. For bandwidth, assume the
7540 // worst case.
7541 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7542 underlyingCaps.getLinkDownstreamBandwidthKbps());
7543 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7544 underlyingCaps.getLinkUpstreamBandwidthKbps());
7545 // If this underlying network is metered, the VPN is metered (it may cost money
7546 // to send packets on this network).
7547 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7548 // If this underlying network is roaming, the VPN is roaming (the billing structure
7549 // is different than the usual, local one).
7550 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7551 // If this underlying network is congested, the VPN is congested (the current
7552 // condition of the network affects the performance of this network).
7553 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7554 // If this network is not suspended, the VPN is not suspended (the VPN
7555 // is able to transfer some data).
7556 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08007557 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007558 }
7559 }
7560 if (!hadUnderlyingNetworks) {
7561 // No idea what the underlying networks are; assume reasonable defaults
7562 metered = true;
7563 roaming = false;
7564 congested = false;
7565 suspended = false;
7566 }
7567
lifrade6c2a2021-03-04 14:08:08 +08007568 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007569 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7570 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7571 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7572 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7573 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7574 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08007575 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007576 }
7577
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007578 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007579 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7580 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7581 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04007582 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007583 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007584 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09007585 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007586 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7587 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007588 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007589 // avoid connect/teardown loops.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007590 if (nai.everConnected &&
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007591 !nai.isVPN() &&
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007592 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7593 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09007594 // does not cause any request (that is not a listen) currently matching that agent to
7595 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007596 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09007597 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007598 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09007599 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007600 }
7601
Paul Jensen53f08952015-06-16 14:27:36 -04007602 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007603 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensende49eb12015-06-25 15:30:08 -04007604 if (nai.lastValidated) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007605 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007606 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007607 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007608 }
Paul Jensende49eb12015-06-25 15:30:08 -04007609 if (nai.lastCaptivePortalDetected) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007610 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007611 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007612 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007613 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007614 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007615 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007616 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007617 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007618 }
lucaslin2240ef62019-03-12 13:08:03 +08007619 if (nai.partialConnectivity) {
7620 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7621 } else {
7622 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7623 }
lucasline117e2e2019-10-22 18:27:33 +08007624 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007625
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007626 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09007627 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7628 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007629 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09007630 }
7631
Lorenzo Colittibd079452021-07-02 11:47:57 +09007632 if (nai.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007633 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7634 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007635 }
7636
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007637 return newNc;
7638 }
7639
Lorenzo Colitti44840702021-01-11 22:27:57 +09007640 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7641 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7642 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7643 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7644 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7645 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7646 if (prevSuspended != suspended) {
7647 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7648 // onResumed have been removed.
7649 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7650 : ConnectivityManager.CALLBACK_RESUMED);
7651 }
7652 if (prevSuspended != suspended || prevRoaming != roaming) {
7653 // updateNetworkInfo will mix in the suspended info from the capabilities and
7654 // take appropriate action for the network having possibly changed state.
7655 updateNetworkInfo(nai, nai.networkInfo);
7656 }
7657 }
7658
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007659 /**
7660 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7661 *
7662 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7663 * capabilities we manage and store in {@code nai}, such as validated status and captive
7664 * portal status)
7665 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7666 * potentially triggers rematches.
7667 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7668 * change.)
7669 *
7670 * @param oldScore score of the network before any of the changes that prompted us
7671 * to call this function.
7672 * @param nai the network having its capabilities updated.
7673 * @param nc the new network capabilities.
7674 */
Chalard Jean62edfd82019-12-02 18:39:29 +09007675 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7676 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007677 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007678 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean62edfd82019-12-02 18:39:29 +09007679 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09007680 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007681
Chalard Jeanb2a49912018-01-16 18:43:05 +09007682 updateUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09007683 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007684
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007685 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007686 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7687 // the change we're processing can't affect any requests, it can only affect the listens
7688 // on this network. We might have been called by rematchNetworkAndRequests when a
7689 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09007690 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007691 } else {
7692 // If the requestable capabilities have changed or the score changed, we can't have been
7693 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09007694 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04007695 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07007696 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09007697 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007698
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007699 final boolean oldMetered = prevNc.isMetered();
7700 final boolean newMetered = newNc.isMetered();
7701 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08007702
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007703 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00007704 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7705 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007706 }
junyulaif2c67e42018-08-07 19:50:45 +08007707
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007708 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7709 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08007710
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007711 // Report changes that are interesting for network statistics tracking.
7712 if (meteredChanged || roamingChanged) {
7713 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06007714 }
7715
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007716 // This network might have been underlying another network. Propagate its capabilities.
7717 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08007718
7719 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007720 mDnsManager.updateTransportsForNetwork(
7721 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08007722 }
lucaslin53e8a262021-06-08 01:43:59 +08007723
7724 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007725 }
7726
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007727 /** Convenience method to update the capabilities for a given network. */
7728 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7729 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7730 }
7731
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007732 /**
7733 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7734 * network.
7735 *
7736 * Ingress interface filtering enforces that all apps under the given network can only receive
7737 * packets from the network's interface (and loopback). This is important for VPNs because
7738 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7739 * non-VPN interfaces.
7740 *
7741 * As a result, this method should return true iff
7742 * 1. the network is an app VPN (not legacy VPN)
7743 * 2. the VPN does not allow bypass
7744 * 3. the VPN is fully-routed
7745 * 4. the VPN interface is non-null
7746 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007747 * @see INetd#firewallAddUidInterfaceRules
7748 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007749 */
7750 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7751 LinkProperties lp) {
7752 if (nc == null || lp == null) return false;
7753 return nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007754 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08007755 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007756 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08007757 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7758 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007759 }
7760
Chiachang Wang28afaff2020-12-10 22:24:47 +08007761 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7762 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7763 int index = 0;
7764 for (UidRange range : ranges) {
7765 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7766 index++;
7767 }
7768 return stableRanges;
7769 }
7770
Chalard Jeane6c95272022-01-25 21:04:21 +09007771 private static UidRangeParcel[] intsToUidRangeStableParcels(
7772 final @NonNull ArraySet<Integer> uids) {
7773 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
7774 int index = 0;
7775 for (int uid : uids) {
7776 stableRanges[index] = new UidRangeParcel(uid, uid);
7777 index++;
7778 }
7779 return stableRanges;
7780 }
7781
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007782 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7783 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7784 for (int i = 0; i < ranges.length; i++) {
7785 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7786 }
7787 return stableRanges;
7788 }
7789
Ken Chen5e65a852020-12-24 12:59:10 +08007790 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7791 int[] exemptUids) {
7792 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7793 try {
7794 mNetd.socketDestroy(ranges, exemptUids);
7795 } catch (Exception e) {
7796 loge("Exception in socket destroy: ", e);
7797 }
7798 }
7799 }
7800
paulhuaa0743d2021-05-26 21:56:03 +08007801 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08007802 int[] exemptUids = new int[2];
7803 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7804 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7805 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7806 exemptUids[0] = VPN_UID;
7807 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7808 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7809
7810 maybeCloseSockets(nai, ranges, exemptUids);
7811 try {
7812 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08007813 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007814 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08007815 } else {
paulhu0e79d952021-06-09 16:11:35 +08007816 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007817 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08007818 }
7819 } catch (Exception e) {
7820 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7821 " on netId " + nai.network.netId + ". " + e);
7822 }
7823 maybeCloseSockets(nai, ranges, exemptUids);
7824 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007825
lucaslin53e8a262021-06-08 01:43:59 +08007826 private boolean isProxySetOnAnyDefaultNetwork() {
7827 ensureRunningOnConnectivityServiceThread();
7828 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7829 final NetworkAgentInfo nai = nri.getSatisfier();
7830 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
7831 return true;
7832 }
7833 }
7834 return false;
7835 }
7836
7837 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7838 NetworkCapabilities newNc) {
7839 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
7840 // the proxy might be changed since the default network satisfied by the apps might also
7841 // changed.
7842 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
7843 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09007844 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
7845 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
7846 if (nai.isVPN() && nai.everConnected && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08007847 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
7848 mProxyTracker.sendProxyBroadcast();
7849 }
7850 }
7851
Chalard Jeane6c95272022-01-25 21:04:21 +09007852 private void updateUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
7853 @Nullable NetworkCapabilities newNc) {
7854 updateVpnUids(nai, prevNc, newNc);
7855 updateAccessUids(nai, prevNc, newNc);
7856 }
7857
7858 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
7859 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007860 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7861 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007862 if (null == prevRanges) prevRanges = new ArraySet<>();
7863 if (null == newRanges) newRanges = new ArraySet<>();
7864 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
7865
7866 prevRanges.removeAll(newRanges);
7867 newRanges.removeAll(prevRangesCopy);
7868
7869 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007870 // When updating the VPN uid routing rules, add the new range first then remove the old
7871 // range. If old range were removed first, there would be a window between the old
7872 // range being removed and the new range being added, during which UIDs contained
7873 // in both ranges are not subject to any VPN routing rules. Adding new range before
7874 // removing old range works because, unlike the filtering rules below, it's possible to
7875 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08007876 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
7877 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
7878 // [1-5] & [1-2],[4-5] == [3]
7879 // Then we can do:
7880 // maybeCloseSockets([3])
7881 // mNetd.networkAddUidRanges([1-2],[4-5])
7882 // mNetd.networkRemoveUidRanges([1-5])
7883 // maybeCloseSockets([3])
7884 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
7885 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09007886 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08007887 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007888 }
7889 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08007890 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007891 }
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007892 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
7893 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
7894 final String iface = nai.linkProperties.getInterfaceName();
7895 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09007896 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007897 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
7898 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
7899 // were added first and then newRanges got removed later, there would be only one uid
7900 // 10013 left. A consequence of removing old ranges before adding new ranges is that
7901 // there is now a window of opportunity when the UIDs are not subject to any filtering.
7902 // Note that this is in contrast with the (more robust) update of VPN routing rules
7903 // above, where the addition of new ranges happens before the removal of old ranges.
7904 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
7905 // to be removed will never overlap with the new range to be added.
7906 if (wasFiltering && !prevRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08007907 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007908 }
7909 if (shouldFilter && !newRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08007910 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007911 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09007912 } catch (Exception e) {
7913 // Never crash!
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007914 loge("Exception in updateUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007915 }
7916 }
7917
Chalard Jeane6c95272022-01-25 21:04:21 +09007918 private void updateAccessUids(@NonNull NetworkAgentInfo nai,
7919 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
7920 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
7921 final boolean prevEmpty = null == prevNc || prevNc.getAccessUidsNoCopy().isEmpty();
7922 final boolean newEmpty = null == newNc || newNc.getAccessUidsNoCopy().isEmpty();
7923 if (prevEmpty && newEmpty) return;
7924
7925 final ArraySet<Integer> prevUids =
7926 null == prevNc ? new ArraySet<>() : prevNc.getAccessUidsNoCopy();
7927 final ArraySet<Integer> newUids =
7928 null == newNc ? new ArraySet<>() : newNc.getAccessUidsNoCopy();
7929
7930 if (prevUids.equals(newUids)) return;
7931
7932 // This implementation is very simple and vastly faster for sets of Integers than
7933 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
7934 // a key computed from the value and has storage for that.
7935 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
7936 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
7937 toRemove.removeAll(newUids);
7938 toAdd.removeAll(prevUids);
7939
7940 try {
7941 if (!toAdd.isEmpty()) {
7942 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
7943 nai.network.netId,
7944 intsToUidRangeStableParcels(toAdd),
7945 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
7946 }
7947 if (!toRemove.isEmpty()) {
7948 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
7949 nai.network.netId,
7950 intsToUidRangeStableParcels(toRemove),
7951 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
7952 }
7953 } catch (RemoteException e) {
7954 // Netd died. This usually causes a runtime restart anyway.
7955 }
7956 }
7957
Hugo Benichi9d35b752017-09-01 01:23:32 +00007958 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09007959 ensureRunningOnConnectivityServiceThread();
7960
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007961 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00007962 // Ignore updates for disconnected networks
7963 return;
7964 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007965 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09007966 log("Update of LinkProperties for " + nai.toShortString()
7967 + "; created=" + nai.created
7968 + "; everConnected=" + nai.everConnected);
Hugo Benichi9d35b752017-09-01 01:23:32 +00007969 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007970 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
7971 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08007972 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00007973 }
7974
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007975 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
7976 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007977 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007978 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08007979 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08007980 // If apps could file multi-layer requests with PendingIntents, they'd need to know
7981 // which of the layer is satisfied alongside with some ID for the request. Hence, if
7982 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09007983 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
7984 // need to be sent as a separate extra.
7985 final NetworkRequest req = nri.isMultilayerRequest()
7986 ? nri.getActiveRequest()
7987 // Non-multilayer listen requests do not have an active request
7988 : nri.mRequests.get(0);
7989 if (req == null) {
7990 Log.wtf(TAG, "No request in NRI " + nri);
7991 }
7992 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007993 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007994 sendIntent(nri.mPendingIntent, intent);
7995 }
7996 // else not handled
7997 }
7998
7999 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8000 mPendingIntentWakeLock.acquire();
8001 try {
8002 if (DBG) log("Sending " + pendingIntent);
8003 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
8004 } catch (PendingIntent.CanceledException e) {
8005 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8006 mPendingIntentWakeLock.release();
8007 releasePendingNetworkRequest(pendingIntent);
8008 }
8009 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8010 }
8011
8012 @Override
8013 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8014 String resultData, Bundle resultExtras) {
8015 if (DBG) log("Finished sending " + pendingIntent);
8016 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008017 // Release with a delay so the receiving client has an opportunity to put in its
8018 // own request.
8019 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008020 }
8021
James Mattis212df9e2020-12-03 19:57:41 -08008022 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
8023 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
8024 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008025 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008026 // Default request has no msgr. Also prevents callbacks from being invoked for
8027 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8028 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8029 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008030 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008031 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008032 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008033 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008034 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008035 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008036 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008037 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8038 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008039 }
Roshan Pius951c0032020-12-22 15:10:42 -08008040 final boolean includeLocationSensitiveInfo =
8041 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008042 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008043 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008044 final NetworkCapabilities nc =
8045 networkCapabilitiesRestrictedForCallerPermissions(
8046 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8047 putParcelable(
8048 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008049 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008050 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008051 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008052 nri.mCallingAttributionTag));
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008053 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8054 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008055 // For this notification, arg1 contains the blocked status.
8056 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008057 break;
8058 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008059 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008060 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008061 break;
8062 }
8063 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008064 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008065 final NetworkCapabilities netCap =
8066 networkCapabilitiesRestrictedForCallerPermissions(
8067 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8068 putParcelable(
8069 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008070 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008071 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008072 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008073 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008074 break;
8075 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008076 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008077 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8078 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008079 break;
8080 }
junyulaif2c67e42018-08-07 19:50:45 +08008081 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008082 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008083 msg.arg1 = arg1;
8084 break;
8085 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008086 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008087 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008088 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008089 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008090 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008091 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008092 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008093 }
James Mattis45d81842021-01-10 14:24:24 -08008094 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008095 } catch (RemoteException e) {
8096 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008097 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008098 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008099 }
8100
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008101 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8102 bundle.putParcelable(t.getClass().getSimpleName(), t);
8103 }
8104
Chalard Jean0702f982021-09-16 21:50:07 +09008105 /**
8106 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8107 *
8108 * When a request should be assigned to a new network, it is normally lingered to give
8109 * time for apps to gracefully migrate their connections. When both networks are on the same
8110 * radio, but that radio can't do time-sharing efficiently, this may end up being
8111 * counter-productive because any traffic on the old network may drastically reduce the
8112 * performance of the new network.
8113 * The stack supports a configuration to let modem vendors state that their radio can't
8114 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8115 * from one cell network to another can't be done gracefully.
8116 *
8117 * @param oldNai the old network serving the request
8118 * @param newNai the new network serving the request
8119 * @return whether the switch can be graceful
8120 */
8121 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8122 @NonNull final NetworkAgentInfo newSatisfier) {
8123 if (mCellularRadioTimesharingCapable) return true;
8124 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8125 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8126 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8127 }
8128
Paul Jensenaf94b982014-09-30 15:37:41 -04008129 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008130 if (nai.numRequestNetworkRequests() != 0) {
8131 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8132 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008133 // Ignore listening and track default requests.
8134 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008135 loge("Dead network still had at least " + nr);
8136 break;
8137 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008138 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008139 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008140 }
8141
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008142 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8143 if (oldNetwork == null) {
8144 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8145 return;
8146 }
Chalard Jean49707572019-12-10 21:07:02 +09008147 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008148
8149 // If we get here it means that the last linger timeout for this network expired. So there
8150 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008151 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008152
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008153 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008154 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008155 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008156 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008157 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008158 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008159 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008160 }
8161
James Mattise3ef1912020-12-20 11:09:58 -08008162 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8163 boolean isDefaultChanged = false;
8164 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8165 final NetworkReassignment.RequestReassignment reassignment =
8166 changes.getReassignment(defaultRequestInfo);
8167 if (null == reassignment) {
8168 continue;
8169 }
8170 // reassignment only contains those instances where the satisfying network changed.
8171 isDefaultChanged = true;
8172 // Notify system services of the new default.
8173 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8174 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008175
James Mattise3ef1912020-12-20 11:09:58 -08008176 if (isDefaultChanged) {
8177 // Hold a wakelock for a short time to help apps in migrating to a new default.
8178 scheduleReleaseNetworkTransitionWakelock();
8179 }
8180 }
8181
8182 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8183 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8184 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8185 if (DBG) {
8186 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8187 }
Chalard Jean8e382112019-12-03 20:45:30 +09008188
James Mattisd31bdfa2020-12-23 16:37:26 -08008189 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8190 if (newDefaultNetwork != null) {
8191 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008192 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008193
James Mattisd31bdfa2020-12-23 16:37:26 -08008194 // Set an app level managed default and return since further processing only applies to the
8195 // default network.
8196 if (mDefaultRequest != nri) {
8197 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8198 return;
8199 }
8200
8201 makeDefaultNetwork(newDefaultNetwork);
8202
James Mattise3ef1912020-12-20 11:09:58 -08008203 if (oldDefaultNetwork != null) {
8204 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8205 }
8206 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008207 handleApplyDefaultProxy(null != newDefaultNetwork
8208 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8209 updateTcpBufferSizes(null != newDefaultNetwork
8210 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008211 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008212 }
8213
James Mattisd31bdfa2020-12-23 16:37:26 -08008214 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8215 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8216 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8217 try {
8218 if (VDBG) {
8219 log("Setting default network for " + nri
8220 + " using UIDs " + nri.getUids()
8221 + " with old network " + (oldDefaultNetwork != null
8222 ? oldDefaultNetwork.network().getNetId() : "null")
8223 + " and new network " + (newDefaultNetwork != null
8224 ? newDefaultNetwork.network().getNetId() : "null"));
8225 }
8226 if (nri.getUids().isEmpty()) {
8227 throw new IllegalStateException("makeDefaultForApps called without specifying"
8228 + " any applications to set as the default." + nri);
8229 }
8230 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008231 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008232 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008233 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008234 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008235 }
8236 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008237 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008238 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008239 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008240 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008241 }
8242 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008243 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008244 }
8245 }
8246
8247 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8248 try {
8249 if (null != newDefaultNetwork) {
8250 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8251 } else {
8252 mNetd.networkClearDefault();
8253 }
8254 } catch (RemoteException | ServiceSpecificException e) {
8255 loge("Exception setting default network :" + e);
8256 }
8257 }
8258
Chalard Jean05cbe972019-12-09 11:50:38 +09008259 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008260 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09008261 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09008262 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09008263 processNewlySatisfiedListenRequests(nai);
8264 }
8265
8266 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008267 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8268 if (nri.isMultilayerRequest()) {
8269 continue;
8270 }
8271 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008272 if (!nr.isListen()) continue;
8273 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08008274 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008275 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
8276 }
8277 }
Chalard Jeancd397a22019-11-22 22:33:33 +09008278 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008279
Chalard Jeancd397a22019-11-22 22:33:33 +09008280 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008281 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8282 if (nri.isMultilayerRequest()) {
8283 continue;
8284 }
8285 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008286 if (!nr.isListen()) continue;
8287 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
8288 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09008289 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008290 }
8291 }
8292 }
8293
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008294 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008295 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008296 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08008297 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09008298 @Nullable public final NetworkRequest mOldNetworkRequest;
8299 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008300 @Nullable public final NetworkAgentInfo mOldNetwork;
8301 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08008302 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008303 @Nullable final NetworkRequest oldNetworkRequest,
8304 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008305 @Nullable final NetworkAgentInfo oldNetwork,
8306 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008307 mNetworkRequestInfo = networkRequestInfo;
8308 mOldNetworkRequest = oldNetworkRequest;
8309 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008310 mOldNetwork = oldNetwork;
8311 mNewNetwork = newNetwork;
8312 }
Chalard Jean49707572019-12-10 21:07:02 +09008313
8314 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09008315 final NetworkRequest requestToShow = null != mNewNetworkRequest
8316 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
8317 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08008318 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
8319 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09008320 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008321 }
8322
Chalard Jean46a62372019-12-10 21:25:24 +09008323 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008324
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008325 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09008326 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008327 }
8328
8329 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09008330 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09008331 // The code is never supposed to add two reassignments of the same request. Make
8332 // sure this stays true, but without imposing this expensive check on all
8333 // reassignments on all user devices.
8334 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08008335 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09008336 throw new IllegalStateException("Trying to reassign ["
8337 + reassignment + "] but already have ["
8338 + existing + "]");
8339 }
8340 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09008341 }
Chalard Jean46a62372019-12-10 21:25:24 +09008342 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008343 }
8344
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008345 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09008346 // the passed request.
8347 @Nullable
8348 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008349 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008350 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008351 }
8352 return null;
8353 }
Chalard Jean49707572019-12-10 21:07:02 +09008354
8355 public String toString() {
8356 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8357 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09008358 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008359 for (final RequestReassignment rr : getRequestReassignments()) {
8360 sj.add(rr.toString());
8361 }
8362 return sj.toString();
8363 }
8364
8365 public String debugString() {
8366 final StringBuilder sb = new StringBuilder();
8367 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09008368 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008369 for (final RequestReassignment rr : getRequestReassignments()) {
8370 sb.append("\n ").append(rr);
8371 }
8372 return sb.append("\n").toString();
8373 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008374 }
8375
Chalard Jean24344d72019-12-04 13:32:31 +09008376 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008377 @Nullable final NetworkRequest previousRequest,
8378 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09008379 @Nullable final NetworkAgentInfo previousSatisfier,
8380 @Nullable final NetworkAgentInfo newSatisfier,
8381 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08008382 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09008383 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09008384 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008385 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008386 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09008387 }
James Mattisa076c532020-12-02 14:12:41 -08008388 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean0702f982021-09-16 21:50:07 +09008389 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)) {
8390 // If this network switch can't be supported gracefully, the request is not
8391 // lingered. This allows letting go of the network sooner to reclaim some
8392 // performance on the new network, since the radio can't do both at the same
8393 // time while preserving good performance.
8394 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8395 }
Chalard Jean24344d72019-12-04 13:32:31 +09008396 } else {
8397 if (VDBG || DDBG) log(" accepting network in place of null");
8398 }
junyulai0ac374f2020-12-14 18:41:52 +08008399
8400 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8401 // and immediately satisfies a request then remove the timer. This will happen for
8402 // all networks except in the case of an underlying network for a VCN.
8403 if (newSatisfier.isNascent()) {
8404 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08008405 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008406 }
8407
Chalard Jean5d6e23b2021-03-01 22:00:20 +09008408 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08008409 newSatisfier.unlingerRequest(newRequest.requestId);
8410 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008411 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08008412 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008413 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09008414 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008415 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008416 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08008417 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008418 }
James Mattisa076c532020-12-02 14:12:41 -08008419 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008420 }
James Mattisa076c532020-12-02 14:12:41 -08008421 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008422 }
8423
James Mattisa076c532020-12-02 14:12:41 -08008424 /**
8425 * This function is triggered when something can affect what network should satisfy what
8426 * request, and it computes the network reassignment from the passed collection of requests to
8427 * network match to the one that the system should now have. That data is encoded in an
8428 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8429 * satisfier.
8430 *
8431 * After the reassignment is computed, it is applied to the state objects.
8432 *
8433 * @param networkRequests the nri objects to evaluate for possible network reassignment
8434 * @return NetworkReassignment listing of proposed network assignment changes
8435 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008436 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08008437 private NetworkReassignment computeNetworkReassignment(
8438 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09008439 final NetworkReassignment changes = new NetworkReassignment();
8440
Chalard Jeanc81d4c32021-04-07 17:06:19 +09008441 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09008442 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008443 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattisa076c532020-12-02 14:12:41 -08008444 if (!nai.everConnected) {
8445 continue;
8446 }
Chalard Jean857a1712019-12-10 21:08:07 +09008447 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09008448 }
Chalard Jean857a1712019-12-10 21:08:07 +09008449
James Mattisa076c532020-12-02 14:12:41 -08008450 for (final NetworkRequestInfo nri : networkRequests) {
8451 // Non-multilayer listen requests can be ignored.
8452 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8453 continue;
8454 }
8455 NetworkAgentInfo bestNetwork = null;
8456 NetworkRequest bestRequest = null;
8457 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09008458 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08008459 // Stop evaluating as the highest possible priority request is satisfied.
8460 if (null != bestNetwork) {
8461 bestRequest = req;
8462 break;
8463 }
8464 }
James Mattisd31bdfa2020-12-23 16:37:26 -08008465 if (null == bestNetwork && isDefaultBlocked(nri)) {
8466 // Remove default networking if disallowed for managed default requests.
8467 bestNetwork = mNoServiceNetwork;
8468 }
8469 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09008470 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09008471 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08008472 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09008473 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008474 }
8475 return changes;
8476 }
8477
James Mattisa076c532020-12-02 14:12:41 -08008478 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8479 return new HashSet<>(mNetworkRequests.values());
8480 }
8481
Paul Jensenc88b39b2015-06-16 14:27:36 -04008482 /**
James Mattisa076c532020-12-02 14:12:41 -08008483 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04008484 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04008485 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008486 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08008487 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8488 }
8489
8490 /**
8491 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8492 * being disconnected.
8493 */
8494 private void rematchNetworksAndRequests(
8495 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8496 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09008497 // TODO: This may be slow, and should be optimized.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008498 final long now = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08008499 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jean49707572019-12-10 21:07:02 +09008500 if (VDBG || DDBG) {
8501 log(changes.debugString());
8502 } else if (DBG) {
8503 log(changes.toString()); // Shorter form, only one line of log
8504 }
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008505 applyNetworkReassignment(changes, now);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008506 issueNetworkNeeds();
Chalard Jeand7f762d2019-12-10 19:01:29 +09008507 }
Chalard Jean64520dc2019-12-04 19:55:32 +09008508
Chalard Jeand7f762d2019-12-10 19:01:29 +09008509 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008510 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008511 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09008512
8513 // Since most of the time there are only 0 or 1 background networks, it would probably
8514 // be more efficient to just use an ArrayList here. TODO : measure performance
8515 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8516 for (final NetworkAgentInfo nai : nais) {
8517 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8518 }
8519
Chalard Jeand7f762d2019-12-10 19:01:29 +09008520 // First, update the lists of satisfied requests in the network agents. This is necessary
8521 // because some code later depends on this state to be correct, most prominently computing
8522 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09008523 for (final NetworkReassignment.RequestReassignment event :
8524 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008525 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8526 event.mOldNetworkRequest, event.mNewNetworkRequest,
8527 event.mOldNetwork, event.mNewNetwork,
8528 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09008529 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008530
James Mattise3ef1912020-12-20 11:09:58 -08008531 // Process default network changes if applicable.
8532 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008533
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008534 // Notify requested networks are available after the default net is switched, but
8535 // before LegacyTypeTracker sends legacy broadcasts
8536 for (final NetworkReassignment.RequestReassignment event :
8537 changes.getRequestReassignments()) {
8538 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008539 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008540 } else {
James Mattisa076c532020-12-02 14:12:41 -08008541 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008542 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008543 }
8544 }
8545
junyulai0ac374f2020-12-14 18:41:52 +08008546 // Update the inactivity state before processing listen callbacks, because the background
8547 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008548 // just yet though, because they have to be sent after the listens are processed to keep
8549 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08008550 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09008551 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08008552 // Rematching may have altered the inactivity state of some networks, so update all
8553 // inactivity timers. updateInactivityState reads the state from the network agent
8554 // and does nothing if the state has not changed : the source of truth is controlled
8555 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8556 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08008557 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08008558 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008559 }
8560 }
8561
Chalard Jeanb10ab412019-12-11 14:12:30 +09008562 for (final NetworkAgentInfo nai : nais) {
8563 if (!nai.everConnected) continue;
8564 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008565 // Process listen requests and update capabilities if the background state has
8566 // changed for this network. For consistency with previous behavior, send onLost
8567 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09008568 processNewlyLostListenRequests(nai);
8569 if (oldBackground != nai.isBackgroundNetwork()) {
8570 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008571 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09008572 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008573 }
8574
junyulai0ac374f2020-12-14 18:41:52 +08008575 for (final NetworkAgentInfo nai : inactiveNetworks) {
8576 // For nascent networks, if connecting with no foreground request, skip broadcasting
8577 // LOSING for backward compatibility. This is typical when mobile data connected while
8578 // wifi connected with mobile data always-on enabled.
8579 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008580 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008581 }
8582
James Mattise3ef1912020-12-20 11:09:58 -08008583 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09008584
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008585 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008586 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008587 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08008588 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008589 // This network has active linger timers and no requests, but is not
8590 // lingering. Linger it.
8591 //
8592 // One way (the only way?) this can happen if this network is unvalidated
8593 // and became unneeded due to another network improving its score to the
8594 // point where this network will no longer be able to satisfy any requests
8595 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08008596 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008597 notifyNetworkLosing(nai, now);
8598 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09008599 } else {
Chalard Jean49707572019-12-10 21:07:02 +09008600 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09008601 teardownUnneededNetwork(nai);
8602 }
8603 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04008604 }
8605 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008606
Chalard Jean62edfd82019-12-02 18:39:29 +09008607 /**
8608 * Apply a change in background state resulting from rematching networks with requests.
8609 *
8610 * During rematch, a network may change background states by starting to satisfy or stopping
8611 * to satisfy a foreground request. Listens don't count for this. When a network changes
8612 * background states, its capabilities need to be updated and callbacks fired for the
8613 * capability change.
8614 *
8615 * @param nai The network that changed background states
8616 */
8617 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8618 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8619 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8620 updateNetworkPermissions(nai, newNc);
8621 nai.getAndSetNetworkCapabilities(newNc);
8622 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8623 }
8624
Chalard Jeanf0344532019-11-19 19:23:38 +09008625 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08008626 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008627 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09008628 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8629 changes.getReassignment(mDefaultRequest);
8630 final NetworkAgentInfo oldDefaultNetwork =
8631 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8632 final NetworkAgentInfo newDefaultNetwork =
8633 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08008634
Chalard Jean5b409c72021-02-04 13:12:59 +09008635 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008636 // Maintain the illusion : since the legacy API only understands one network at a time,
8637 // if the default network changed, apps should see a disconnected broadcast for the
8638 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09008639 if (oldDefaultNetwork != null) {
8640 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8641 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008642 }
Chalard Jean5b409c72021-02-04 13:12:59 +09008643 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008644 // The new default network can be newly null if and only if the old default
8645 // network doesn't satisfy the default request any more because it lost a
8646 // capability.
Chalard Jean5b409c72021-02-04 13:12:59 +09008647 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08008648 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09008649 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008650 }
8651 }
8652
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008653 // Now that all the callbacks have been sent, send the legacy network broadcasts
8654 // as needed. This is necessary so that legacy requests correctly bind dns
8655 // requests to this network. The legacy users are listening for this broadcast
8656 // and will generally do a dns request so they can ensureRouteToHost and if
8657 // they do that before the callbacks happen they'll use the default network.
8658 //
8659 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8660 // callbacks, but if apps can receive the broadcast before the callback, they still might
8661 // have an inconsistent view of networking.
8662 //
8663 // This *does* introduce a race where if the user uses the new api
8664 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8665 // they may get old info. Reverse this after the old startUsing api is removed.
8666 // This is on top of the multiple intent sequencing referenced in the todo above.
8667 for (NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008668 if (nai.everConnected) {
8669 addNetworkToLegacyTypeTracker(nai);
8670 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08008671 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008672 }
8673
Chalard Jean0354d8c2021-01-12 10:58:56 +09008674 private void issueNetworkNeeds() {
8675 ensureRunningOnConnectivityServiceThread();
8676 for (final NetworkOfferInfo noi : mNetworkOffers) {
8677 issueNetworkNeeds(noi);
8678 }
8679 }
8680
8681 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8682 ensureRunningOnConnectivityServiceThread();
8683 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8684 informOffer(nri, noi.offer, mNetworkRanker);
8685 }
8686 }
8687
8688 /**
8689 * Inform a NetworkOffer about any new situation of a request.
8690 *
8691 * This function handles updates to offers. A number of events may happen that require
8692 * updating the registrant for this offer about the situation :
8693 * • The offer itself was updated. This may lead the offer to no longer being able
8694 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8695 * or conversely being strengthened enough to beat the satisfier (and therefore
8696 * start being needed)
8697 * • The network satisfying a request changed (including cases where the request
8698 * starts or stops being satisfied). The new network may be a stronger or weaker
8699 * match than the old one, possibly affecting whether the offer is needed.
8700 * • The network satisfying a request updated their score. This may lead the offer
8701 * to no longer be able to beat it if the current satisfier got better, or
8702 * conversely start being a good choice if the current satisfier got weaker.
8703 *
8704 * @param nri The request
8705 * @param offer The offer. This may be an updated offer.
8706 */
8707 private static void informOffer(@NonNull NetworkRequestInfo nri,
8708 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
8709 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
8710 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09008711
8712 // Multi-layer requests have a currently active request, the one being satisfied.
8713 // Since the system will try to bring up a better network than is currently satisfying
8714 // the request, NetworkProviders need to be told the offers matching the requests *above*
8715 // the currently satisfied one are needed, that the ones *below* the satisfied one are
8716 // not needed, and the offer is needed for the active request iff the offer can beat
8717 // the satisfier.
8718 // For non-multilayer requests, the logic above gracefully degenerates to only the
8719 // last case.
8720 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
8721 // providers that the offer is needed for this request, until the active request is found.
8722 // In a second phase, deal with the currently active request. In a third phase, inform
8723 // the providers that offer is unneeded for the remaining requests.
8724
8725 // First phase : inform providers of all requests above the active request.
8726 int i;
8727 for (i = 0; nri.mRequests.size() > i; ++i) {
8728 final NetworkRequest request = nri.mRequests.get(i);
8729 if (activeRequest == request) break; // Found the active request : go to phase 2
8730 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8731 // Since this request is higher-priority than the one currently satisfied, if the
8732 // offer can satisfy it, the provider should try and bring up the network for sure ;
8733 // no need to even ask the ranker – an offer that can satisfy is always better than
8734 // no network. Hence tell the provider so unless it already knew.
8735 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
8736 offer.onNetworkNeeded(request);
8737 }
8738 }
8739
8740 // Second phase : deal with the active request (if any)
8741 if (null != activeRequest && activeRequest.isRequest()) {
8742 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00008743 // If an offer can satisfy the request, it is considered needed if it is currently
8744 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09008745 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00008746 && satisfier.factorySerialNumber == offer.providerId
8747 && activeRequest.canBeSatisfiedBy(offer.caps);
8748 final boolean newNeeded = currentlyServing
8749 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008750 if (newNeeded != oldNeeded) {
8751 if (newNeeded) {
8752 offer.onNetworkNeeded(activeRequest);
8753 } else {
8754 // The offer used to be able to beat the satisfier. Now it can't.
8755 offer.onNetworkUnneeded(activeRequest);
8756 }
8757 }
8758 }
8759
8760 // Third phase : inform the providers that the offer isn't needed for any request
8761 // below the active one.
8762 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
8763 final NetworkRequest request = nri.mRequests.get(i);
8764 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8765 // Since this request is lower-priority than the one currently satisfied, if the
8766 // offer can satisfy it, the provider should not try and bring up the network.
8767 // Hence tell the provider so unless it already knew.
8768 if (offer.neededFor(request)) {
8769 offer.onNetworkUnneeded(request);
8770 }
8771 }
8772 }
8773
Chalard Jean61c79252019-11-07 23:07:32 +09008774 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8775 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8776 NetworkRequest nr = nai.requestAt(i);
8777 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8778 // legacy type tracker filters out repeat adds
8779 mLegacyTypeTracker.add(nr.legacyType, nai);
8780 }
8781 }
8782
8783 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09008784 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09008785 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8786 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8787 if (nai.isVPN()) {
8788 mLegacyTypeTracker.add(TYPE_VPN, nai);
8789 }
8790 }
8791
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008792 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04008793 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittia8de5ca2014-12-17 11:14:42 +09008794 if (!nai.everValidated) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09008795 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04008796 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09008797 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008798
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008799 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008800 // Don't repeat publish.
8801 if (newInetCondition == mDefaultInetConditionPublished) return;
8802
8803 mDefaultInetConditionPublished = newInetCondition;
8804 sendInetConditionBroadcast(nai.networkInfo);
8805 }
8806
Chalard Jeand61375d2020-01-14 22:46:36 +09008807 @NonNull
8808 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8809 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008810 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09008811 final boolean suspended =
8812 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8813 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8814 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8815 // state. This is because the network could have been suspended before connecting,
8816 // or it could be disconnecting while being suspended, and in both these cases
8817 // the state should not be overridden. Note that the only detailed state that
8818 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8819 // worry about multiple different substates of CONNECTED.
8820 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8821 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08008822 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8823 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8824 // network agent is created, then goes to suspended, then goes out of suspended without
8825 // ever setting connected. Check if network agent is ever connected to update the state.
8826 newInfo.setDetailedState(nai.everConnected
8827 ? NetworkInfo.DetailedState.CONNECTED
8828 : NetworkInfo.DetailedState.CONNECTING,
8829 info.getReason(),
8830 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09008831 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008832 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09008833 return newInfo;
8834 }
8835
8836 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8837 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8838
Erik Kline99f301b2017-02-15 19:59:17 +09008839 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008840 NetworkInfo oldInfo = null;
8841 synchronized (networkAgent) {
8842 oldInfo = networkAgent.networkInfo;
8843 networkAgent.networkInfo = newInfo;
8844 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008845
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008846 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008847 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8848 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008849 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07008850
Robin Leea8c0b6e2016-05-01 23:00:00 +01008851 if (!networkAgent.created
8852 && (state == NetworkInfo.State.CONNECTED
8853 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008854
8855 // A network that has just connected has zero requests and is thus a foreground network.
8856 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8857
Luke Huangfdd11f82019-04-09 18:41:49 +08008858 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09008859 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008860 // Initialize the network's capabilities to their starting values according to the
8861 // underlying networks. This ensures that the capabilities are correct before
8862 // anything happens to the network.
8863 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09008864 }
Paul Jensen74940202014-08-04 12:21:19 -04008865 networkAgent.created = true;
Chiachang Wang3f6cc072021-03-24 18:39:17 +08008866 networkAgent.onNetworkCreated();
Robin Leea8c0b6e2016-05-01 23:00:00 +01008867 }
8868
8869 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
8870 networkAgent.everConnected = true;
8871
lucaslin45e639b2019-04-03 17:09:28 +08008872 // NetworkCapabilities need to be set before sending the private DNS config to
8873 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09008874 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
8875
Erik Kline9a62f012018-03-21 07:18:33 -07008876 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08008877 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
8878 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008879
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008880 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
8881 // command must be sent after updating LinkProperties to maximize chances of
8882 // NetworkMonitor seeing the correct LinkProperties when starting.
8883 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008884 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09008885 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008886 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09008887 networkAgent.networkMonitor().notifyNetworkConnected(
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008888 new LinkProperties(networkAgent.linkProperties,
8889 true /* parcelSensitiveFields */),
8890 networkAgent.networkCapabilities);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09008891 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008892
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008893 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
8894 // be communicated to a particular NetworkAgent depends only on the network's immutable,
8895 // capabilities, so it only needs to be done once on initial connect, not every time the
8896 // network's capabilities change. Note that we do this before rematching the network,
8897 // so we could decide to tear it down immediately afterwards. That's fine though - on
8898 // disconnection NetworkAgents should stop any signal strength monitoring they have been
8899 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09008900 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008901
junyulai0ac374f2020-12-14 18:41:52 +08008902 // Before first rematching networks, put an inactivity timer without any request, this
8903 // allows {@code updateInactivityState} to update the state accordingly and prevent
8904 // tearing down for any {@code unneeded} evaluation in this period.
8905 // Note that the timer will not be rescheduled since the expiry time is
8906 // fixed after connection regardless of the network satisfying other requests or not.
8907 // But it will be removed as soon as the network satisfies a request for the first time.
8908 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
8909 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08008910 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008911
Paul Jensen05e85ee2014-09-11 11:00:39 -04008912 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008913 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008914
8915 // This has to happen after matching the requests, because callbacks are just requests.
8916 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008917 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008918 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04008919 if (networkAgent.isVPN()) {
Chalard Jeanb2a49912018-01-16 18:43:05 +09008920 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04008921 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09008922 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00008923 if (networkAgent.isVPN()) {
8924 // As the active or bound network changes for apps, broadcast the default proxy, as
8925 // apps may need to update their proxy data. This is called after disconnecting from
8926 // VPN to make sure we do not broadcast the old proxy data.
8927 // TODO(b/122649188): send the broadcast only to VPN users.
8928 mProxyTracker.sendProxyBroadcast();
8929 }
Yintang Gu5014b522019-06-18 14:24:32 +08008930 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
8931 state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008932 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008933 }
8934 }
8935
Chalard Jean28018572020-12-21 18:36:52 +09008936 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09008937 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
8938 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008939 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07008940 }
8941
Erik Kline99f301b2017-02-15 19:59:17 +09008942 // Notify only this one new request of the current state. Transfer all the
8943 // current state by calling NetworkCapabilities and LinkProperties callbacks
8944 // so that callers can be guaranteed to have as close to atomicity in state
8945 // transfer as can be supported by this current API.
8946 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07008947 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09008948 if (nri.mPendingIntent != null) {
8949 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
8950 // Attempt no subsequent state pushes where intents are involved.
8951 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008952 }
Erik Kline99f301b2017-02-15 19:59:17 +09008953
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008954 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08008955 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008956 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
8957 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
8958 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08008959 }
8960
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008961 // Notify the requests on this NAI that the network is now lingered.
8962 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08008963 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008964 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
8965 }
8966
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008967 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
8968 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
8969 return vpnBlocked
8970 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
8971 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
8972 }
8973
8974 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
8975 if (blockedReasons == BLOCKED_REASON_NONE) {
8976 mUidBlockedReasons.delete(uid);
8977 } else {
8978 mUidBlockedReasons.put(uid, blockedReasons);
8979 }
8980 }
8981
junyulaif2c67e42018-08-07 19:50:45 +08008982 /**
8983 * Notify of the blocked state apps with a registered callback matching a given NAI.
8984 *
8985 * Unlike other callbacks, blocked status is different between each individual uid. So for
8986 * any given nai, all requests need to be considered according to the uid who filed it.
8987 *
8988 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008989 * @param oldMetered True if the previous network capabilities were metered.
8990 * @param newMetered True if the current network capabilities are metered.
8991 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
8992 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08008993 */
8994 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00008995 boolean newMetered, List<UidRange> oldBlockedUidRanges,
8996 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08008997
8998 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8999 NetworkRequest nr = nai.requestAt(i);
9000 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009001
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009002 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9003 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9004 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009005 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009006 : oldVpnBlocked;
9007
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009008 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9009 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9010 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009011 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009012 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009013 }
9014 }
9015 }
9016
9017 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009018 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009019 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009020 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009021 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009022 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009023 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009024 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009025 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009026
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009027 final int oldBlockedState = getBlockedState(
9028 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9029 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9030 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009031 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009032 }
junyulaif2c67e42018-08-07 19:50:45 +08009033 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9034 NetworkRequest nr = nai.requestAt(i);
9035 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009036 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009037 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
9038 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009039 }
9040 }
9041 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009042 }
9043
Chalard Jean3a3f5f22019-04-10 23:07:55 +09009044 @VisibleForTesting
9045 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09009046 // The NetworkInfo we actually send out has no bearing on the real
9047 // state of affairs. For example, if the default connection is mobile,
9048 // and a request for HIPRI has just gone away, we need to pretend that
9049 // HIPRI has just disconnected. So we need to set the type to HIPRI and
9050 // the state to DISCONNECTED, even though the network is of type MOBILE
9051 // and is still connected.
9052 NetworkInfo info = new NetworkInfo(nai.networkInfo);
9053 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09009054 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009055 if (state != DetailedState.DISCONNECTED) {
9056 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09009057 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009058 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009059 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07009060 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
9061 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
9062 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
9063 if (info.isFailover()) {
9064 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
9065 nai.networkInfo.setFailover(false);
9066 }
9067 if (info.getReason() != null) {
9068 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
9069 }
9070 if (info.getExtraInfo() != null) {
9071 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
9072 }
9073 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09009074 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08009075 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07009076 if (newDefaultAgent != null) {
9077 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
9078 newDefaultAgent.networkInfo);
9079 } else {
9080 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
9081 }
9082 }
9083 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
9084 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09009085 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009086 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09009087 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009088 }
9089 }
9090 }
9091
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009092 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009093 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009094 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09009095 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09009096 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009097 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
9098 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009099 NetworkRequestInfo nri = mNetworkRequests.get(nr);
9100 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009101 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009102 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009103 } else {
9104 sendPendingIntentForRequest(nri, networkAgent, notifyType);
9105 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009106 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009107 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009108
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009109 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
9110 notifyNetworkCallbacks(networkAgent, notifyType, 0);
9111 }
9112
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009113 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09009114 * Returns the list of all interfaces that could be used by network traffic that does not
9115 * explicitly specify a network. This includes the default network, but also all VPNs that are
9116 * currently connected.
9117 *
9118 * Must be called on the handler thread.
9119 */
junyulaie7c7d2a2021-01-26 15:29:15 +08009120 @NonNull
9121 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009122 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08009123 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08009124 final Set<Integer> activeNetIds = new ArraySet<>();
9125 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9126 if (nri.isBeingSatisfied()) {
9127 activeNetIds.add(nri.getSatisfier().network().netId);
9128 }
9129 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009130 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattis2516da32021-01-31 17:06:19 -08009131 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09009132 defaultNetworks.add(nai.network);
9133 }
9134 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009135 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09009136 }
9137
9138 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09009139 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
9140 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009141 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08009142 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009143 ensureRunningOnConnectivityServiceThread();
9144 String activeIface = null;
9145 LinkProperties activeLinkProperties = getActiveLinkProperties();
9146 if (activeLinkProperties != null) {
9147 activeIface = activeLinkProperties.getInterfaceName();
9148 }
Benedict Wong9308cd32019-06-12 17:46:31 +00009149
junyulai2050bed2021-01-23 09:46:34 +08009150 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009151 try {
junyulaide41fc22021-01-22 22:46:01 +08009152 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
junyulai69114da2021-03-05 14:46:25 +08009153 for (final NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaide41fc22021-01-22 22:46:01 +08009154 snapshots.add(snapshot);
9155 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009156 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
9157 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009158 } catch (Exception ignored) {
9159 }
9160 }
9161
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07009162 @Override
Udam Sainicd645462016-01-04 12:16:14 -08009163 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08009164 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009165 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009166 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009167
9168 if (!TextUtils.isEmpty(settingUrl)) {
9169 return settingUrl;
9170 }
9171
9172 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009173 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009174 if (!TextUtils.isEmpty(settingUrl)) {
9175 return settingUrl;
9176 }
9177
9178 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009179 }
9180
9181 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009182 public void startNattKeepalive(Network network, int intervalSeconds,
9183 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009184 enforceKeepalivePermission();
9185 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009186 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai070f9ff2019-01-16 20:23:34 +08009187 intervalSeconds, cb,
junyulai011b1f12019-01-03 18:50:15 +08009188 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009189 }
9190
9191 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009192 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009193 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulaid05a1922019-01-15 11:32:44 +08009194 String dstAddr) {
Josh Gao461a1222020-06-16 15:58:11 -07009195 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009196 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009197 mKeepaliveTracker.startNattKeepalive(
9198 getNetworkAgentInfoForNetwork(network), fd, resourceId,
9199 intervalSeconds, cb,
9200 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
9201 } finally {
9202 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9203 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009204 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9205 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009206 }
9207 }
junyulaid05a1922019-01-15 11:32:44 +08009208 }
9209
9210 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009211 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009212 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009213 try {
9214 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08009215 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009216 mKeepaliveTracker.startTcpKeepalive(
9217 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
9218 } finally {
9219 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9220 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009221 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9222 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009223 }
9224 }
junyulai0835a1e2019-01-08 20:04:33 +08009225 }
9226
9227 @Override
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009228 public void stopKeepalive(Network network, int slot) {
9229 mHandler.sendMessage(mHandler.obtainMessage(
junyulai011b1f12019-01-03 18:50:15 +08009230 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009231 }
9232
9233 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07009234 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08009235 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07009236
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009237 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08009238 final long token = Binder.clearCallingIdentity();
9239 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009240 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
9241 UserHandle.getUserHandleForUid(uid))) {
9242 return;
9243 }
9244
Heemin Seogdb8489d2019-06-12 09:21:44 -07009245 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
9246 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009247
9248 // Turn airplane mode off
9249 setAirplaneMode(false);
9250
9251 // restore private DNS settings to default mode (opportunistic)
9252 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
9253 UserHandle.getUserHandleForUid(uid))) {
9254 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
9255 PRIVATE_DNS_MODE_OPPORTUNISTIC);
9256 }
9257
9258 Settings.Global.putString(mContext.getContentResolver(),
9259 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08009260 } finally {
9261 Binder.restoreCallingIdentity(token);
9262 }
Stuart Scottd5463642015-04-02 18:00:02 -07009263 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04009264
Ricky Wai7097cc92018-01-23 04:09:45 +00009265 @Override
9266 public byte[] getNetworkWatchlistConfigHash() {
9267 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
9268 if (nwm == null) {
9269 loge("Unable to get NetworkWatchlistManager");
9270 return null;
9271 }
9272 // Redirect it to network watchlist service to access watchlist file and calculate hash.
9273 return nwm.getWatchlistConfigHash();
9274 }
9275
Hugo Benichibe0c7652016-05-31 16:28:06 +09009276 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09009277 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08009278 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09009279 }
Hugo Benichif4210292017-04-21 15:07:12 +09009280
9281 private static boolean toBool(int encodedBoolean) {
9282 return encodedBoolean != 0; // Only 0 means false.
9283 }
9284
9285 private static int encodeBool(boolean b) {
9286 return b ? 1 : 0;
9287 }
mswest4632928412018-03-12 10:34:34 -07009288
9289 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009290 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
9291 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
9292 @NonNull String[] args) {
9293 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
9294 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07009295 }
9296
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009297 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07009298 @Override
9299 public int onCommand(String cmd) {
9300 if (cmd == null) {
9301 return handleDefaultCommands(cmd);
9302 }
9303 final PrintWriter pw = getOutPrintWriter();
9304 try {
9305 switch (cmd) {
9306 case "airplane-mode":
9307 final String action = getNextArg();
9308 if ("enable".equals(action)) {
9309 setAirplaneMode(true);
9310 return 0;
9311 } else if ("disable".equals(action)) {
9312 setAirplaneMode(false);
9313 return 0;
9314 } else if (action == null) {
9315 final ContentResolver cr = mContext.getContentResolver();
9316 final int enabled = Settings.Global.getInt(cr,
9317 Settings.Global.AIRPLANE_MODE_ON);
9318 pw.println(enabled == 0 ? "disabled" : "enabled");
9319 return 0;
9320 } else {
9321 onHelp();
9322 return -1;
9323 }
9324 default:
9325 return handleDefaultCommands(cmd);
9326 }
9327 } catch (Exception e) {
9328 pw.println(e);
9329 }
9330 return -1;
9331 }
9332
9333 @Override
9334 public void onHelp() {
9335 PrintWriter pw = getOutPrintWriter();
9336 pw.println("Connectivity service commands:");
9337 pw.println(" help");
9338 pw.println(" Print this help text.");
9339 pw.println(" airplane-mode [enable|disable]");
9340 pw.println(" Turn airplane mode on or off.");
9341 pw.println(" airplane-mode");
9342 pw.println(" Get airplane mode.");
9343 }
9344 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009345
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09009346 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009347 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
9348 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
9349 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +08009350 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009351 }
9352
9353 /**
9354 * @param connectionInfo the connection to resolve.
9355 * @return {@code uid} if the connection is found and the app has permission to observe it
9356 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
9357 * connection is not found.
9358 */
9359 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009360 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
9361 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
9362 }
9363
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09009364 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009365 connectionInfo.local, connectionInfo.remote);
9366
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009367 if (uid == INVALID_UID) return uid; // Not found.
9368
9369 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
9370 // VPN, if any, that applies to the UID that owns the connection.
9371 if (checkNetworkStackPermission()) return uid;
9372
9373 final NetworkAgentInfo vpn = getVpnForUid(uid);
9374 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09009375 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009376 return INVALID_UID;
9377 }
9378
9379 return uid;
9380 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +00009381
Benedict Wong493e04b2018-11-09 14:45:34 -08009382 /**
9383 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
9384 *
9385 * <p>The TestNetworkService must be run in the system server due to TUN creation.
9386 */
9387 @Override
9388 public IBinder startOrGetTestNetworkService() {
9389 synchronized (mTNSLock) {
9390 TestNetworkService.enforceTestNetworkPermissions(mContext);
9391
9392 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +08009393 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -08009394 }
9395
9396 return mTNS;
9397 }
9398 }
Cody Kestingd199a9d2019-12-17 12:55:28 -08009399
Cody Kesting73708bf2019-12-18 10:57:50 -08009400 /**
9401 * Handler used for managing all Connectivity Diagnostics related functions.
9402 *
9403 * @see android.net.ConnectivityDiagnosticsManager
9404 *
9405 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9406 */
9407 @VisibleForTesting
9408 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009409 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9410
Cody Kesting73708bf2019-12-18 10:57:50 -08009411 /**
9412 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9413 * android.net.ConnectivityDiagnosticsManager}.
9414 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9415 * NetworkRequestInfo to be registered
9416 */
9417 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9418
9419 /**
9420 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9421 * android.net.ConnectivityDiagnosticsManager}.
9422 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9423 * arg1 = the uid of the caller
9424 */
9425 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9426
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009427 /**
9428 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
9429 * after processing {@link #EVENT_NETWORK_TESTED} events.
9430 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9431 * NetworkMonitor.
9432 * data = PersistableBundle of extras passed from NetworkMonitor.
9433 *
9434 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
9435 */
9436 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
9437
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009438 /**
9439 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9440 * been detected on the network.
9441 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9442 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9443 * arg2 = NetID.
9444 * data = PersistableBundle of extras passed from NetworkMonitor.
9445 */
9446 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9447
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009448 /**
9449 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9450 * the platform. This event will invoke {@link
9451 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9452 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -07009453 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009454 */
9455 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9456
Cody Kesting73708bf2019-12-18 10:57:50 -08009457 private ConnectivityDiagnosticsHandler(Looper looper) {
9458 super(looper);
9459 }
9460
9461 @Override
9462 public void handleMessage(Message msg) {
9463 switch (msg.what) {
9464 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9465 handleRegisterConnectivityDiagnosticsCallback(
9466 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9467 break;
9468 }
9469 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9470 handleUnregisterConnectivityDiagnosticsCallback(
9471 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9472 break;
9473 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009474 case EVENT_NETWORK_TESTED: {
9475 final ConnectivityReportEvent reportEvent =
9476 (ConnectivityReportEvent) msg.obj;
9477
Aaron Huang959d3642021-01-21 15:47:41 +08009478 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009479 break;
9480 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009481 case EVENT_DATA_STALL_SUSPECTED: {
9482 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +08009483 final Pair<Long, PersistableBundle> arg =
9484 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009485 if (nai == null) break;
9486
Aaron Huang959d3642021-01-21 15:47:41 +08009487 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009488 break;
9489 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009490 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -07009491 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009492 break;
9493 }
9494 default: {
9495 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9496 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009497 }
9498 }
9499 }
9500
9501 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9502 @VisibleForTesting
9503 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9504 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9505 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009506 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009507
9508 @VisibleForTesting
9509 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009510 @NonNull IConnectivityDiagnosticsCallback cb,
9511 @NonNull NetworkRequestInfo nri,
9512 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009513 mCb = cb;
9514 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009515 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009516 }
9517
9518 @Override
9519 public void binderDied() {
9520 log("ConnectivityDiagnosticsCallback IBinder died.");
9521 unregisterConnectivityDiagnosticsCallback(mCb);
9522 }
9523 }
9524
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009525 /**
9526 * Class used for sending information from {@link
9527 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9528 */
9529 private static class NetworkTestedResults {
9530 private final int mNetId;
9531 private final int mTestResult;
9532 private final long mTimestampMillis;
9533 @Nullable private final String mRedirectUrl;
9534
9535 private NetworkTestedResults(
9536 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9537 mNetId = netId;
9538 mTestResult = testResult;
9539 mTimestampMillis = timestampMillis;
9540 mRedirectUrl = redirectUrl;
9541 }
9542 }
9543
9544 /**
9545 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9546 * ConnectivityDiagnosticsHandler}.
9547 */
9548 private static class ConnectivityReportEvent {
9549 private final long mTimestampMillis;
9550 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +08009551 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009552
Aaron Huang959d3642021-01-21 15:47:41 +08009553 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9554 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009555 mTimestampMillis = timestampMillis;
9556 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +08009557 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009558 }
9559 }
9560
Cody Kestingf1120be2020-08-03 18:01:40 -07009561 /**
9562 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
9563 * ConnectivityDiagnosticsHandler}.
9564 */
9565 private static class ReportedNetworkConnectivityInfo {
9566 public final boolean hasConnectivity;
9567 public final boolean isNetworkRevalidating;
9568 public final int reporterUid;
9569 @NonNull public final NetworkAgentInfo nai;
9570
9571 private ReportedNetworkConnectivityInfo(
9572 boolean hasConnectivity,
9573 boolean isNetworkRevalidating,
9574 int reporterUid,
9575 @NonNull NetworkAgentInfo nai) {
9576 this.hasConnectivity = hasConnectivity;
9577 this.isNetworkRevalidating = isNetworkRevalidating;
9578 this.reporterUid = reporterUid;
9579 this.nai = nai;
9580 }
9581 }
9582
Cody Kesting73708bf2019-12-18 10:57:50 -08009583 private void handleRegisterConnectivityDiagnosticsCallback(
9584 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9585 ensureRunningOnConnectivityServiceThread();
9586
9587 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -08009588 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009589 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9590
James Mattis64b8b0f2020-11-24 17:40:49 -08009591 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9592 // confusing for these networks to change when an NRI is satisfied in another layer.
9593 if (nri.isMultilayerRequest()) {
9594 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9595 + "network requests.");
9596 }
9597
Cody Kesting73708bf2019-12-18 10:57:50 -08009598 // This means that the client registered the same callback multiple times. Do
9599 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -08009600 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009601 if (VDBG) log("Diagnostics callback is already registered");
9602
9603 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9604 // incremented when the NetworkRequestInfo is created as part of
9605 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009606 nri.decrementRequestCount();
Cody Kesting73708bf2019-12-18 10:57:50 -08009607 return;
9608 }
9609
Cody Kesting31f1ff62020-03-05 10:46:02 -08009610 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -08009611
9612 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -08009613 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009614 } catch (RemoteException e) {
9615 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -08009616 return;
9617 }
9618
9619 // Once registered, provide ConnectivityReports for matching Networks
9620 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9621 synchronized (mNetworkForNetId) {
9622 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9623 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -08009624 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9625 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -08009626 matchingNetworks.add(nai);
9627 }
9628 }
9629 }
9630 for (final NetworkAgentInfo nai : matchingNetworks) {
9631 final ConnectivityReport report = nai.getConnectivityReport();
9632 if (report == null) {
9633 continue;
9634 }
9635 if (!checkConnectivityDiagnosticsPermissions(
9636 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9637 continue;
9638 }
9639
9640 try {
9641 cb.onConnectivityReportAvailable(report);
9642 } catch (RemoteException e) {
9643 // Exception while sending the ConnectivityReport. Move on to the next network.
9644 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009645 }
9646 }
9647
9648 private void handleUnregisterConnectivityDiagnosticsCallback(
9649 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9650 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009651 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009652
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009653 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9654 mConnectivityDiagnosticsCallbacks.remove(iCb);
9655 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009656 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9657 return;
9658 }
9659
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009660 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -08009661
Cody Kesting70fa2b22020-12-02 12:16:56 -08009662 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9663 // (if the Binder died)
9664 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9665 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -08009666 return;
9667 }
9668
Cody Kesting46cb1672020-03-04 13:35:20 -08009669 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9670 // incremented when the NetworkRequestInfo is created as part of
9671 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009672 nri.decrementRequestCount();
Cody Kesting46cb1672020-03-04 13:35:20 -08009673
Cody Kesting31f1ff62020-03-05 10:46:02 -08009674 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009675 }
9676
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009677 private void handleNetworkTestedWithExtras(
9678 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9679 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -08009680 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009681 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009682 final ConnectivityReport report =
9683 new ConnectivityReport(
9684 reportEvent.mNai.network,
9685 reportEvent.mTimestampMillis,
9686 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009687 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009688 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -08009689 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -07009690
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009691 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009692 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009693 for (final IConnectivityDiagnosticsCallback cb : results) {
9694 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -08009695 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009696 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -07009697 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009698 }
9699 }
9700 }
9701
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009702 private void handleDataStallSuspected(
9703 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9704 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -08009705 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009706 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009707 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -08009708 new DataStallReport(
9709 nai.network,
9710 timestampMillis,
9711 detectionMethod,
9712 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009713 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -08009714 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009715 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009716 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009717 for (final IConnectivityDiagnosticsCallback cb : results) {
9718 try {
9719 cb.onDataStallSuspected(report);
9720 } catch (RemoteException ex) {
9721 loge("Error invoking onDataStallSuspected", ex);
9722 }
9723 }
9724 }
9725
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009726 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -07009727 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
9728 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
9729 final ConnectivityReport cachedReport = nai.getConnectivityReport();
9730
9731 // If the Network is being re-validated as a result of this call to
9732 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
9733 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009734 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009735 getMatchingPermissionedCallbacks(
9736 nai,
9737 reportedNetworkConnectivityInfo.isNetworkRevalidating
9738 ? Process.INVALID_UID
9739 : reportedNetworkConnectivityInfo.reporterUid);
9740
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009741 for (final IConnectivityDiagnosticsCallback cb : results) {
9742 try {
Cody Kestingf1120be2020-08-03 18:01:40 -07009743 cb.onNetworkConnectivityReported(
9744 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009745 } catch (RemoteException ex) {
9746 loge("Error invoking onNetworkConnectivityReported", ex);
9747 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009748
9749 // If the Network isn't re-validating, also provide the cached report. If there is no
9750 // cached report, the Network is still being validated and a report will be sent once
9751 // validation is complete. Note that networks which never undergo validation will still
9752 // have a cached ConnectivityReport with RESULT_SKIPPED.
9753 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
9754 try {
9755 cb.onConnectivityReportAvailable(cachedReport);
9756 } catch (RemoteException ex) {
9757 loge("Error invoking onConnectivityReportAvailable", ex);
9758 }
9759 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009760 }
9761 }
9762
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009763 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +09009764 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9765 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009766 sanitized.setUids(null);
9767 sanitized.setAdministratorUids(new int[0]);
9768 sanitized.setOwnerUid(Process.INVALID_UID);
9769 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -08009770 }
9771
Cody Kestingf1120be2020-08-03 18:01:40 -07009772 /**
9773 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
9774 *
9775 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
9776 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009777 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -07009778 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009779 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009780 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009781 mConnectivityDiagnosticsCallbacks.entrySet()) {
9782 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9783 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -07009784
James Mattis64b8b0f2020-11-24 17:40:49 -08009785 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -07009786 if (!nai.satisfies(nri.mRequests.get(0))) {
9787 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009788 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009789
9790 // UID for this callback must either be:
9791 // - INVALID_UID (which sends callbacks to all UIDs), or
9792 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
9793 // notified as a result)
9794 if (uid != Process.INVALID_UID && uid != nri.mUid) {
9795 continue;
9796 }
9797
9798 if (!checkConnectivityDiagnosticsPermissions(
9799 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9800 continue;
9801 }
9802
9803 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009804 }
9805 return results;
9806 }
9807
Cody Kesting7474f672021-05-11 14:22:40 -07009808 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
9809 @NonNull NetworkAgentInfo nai) {
9810 // TODO(b/188483916): replace with a transport-agnostic location-aware check
9811 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
9812 }
9813
Cody Kesting160ef392021-05-05 13:17:22 -07009814 private boolean hasLocationPermission(String packageName, int uid) {
9815 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9816 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9817 // call in a try-catch.
9818 try {
9819 if (!mLocationPermissionChecker.checkLocationPermission(
9820 packageName, null /* featureId */, uid, null /* message */)) {
9821 return false;
9822 }
9823 } catch (SecurityException e) {
9824 return false;
9825 }
9826
9827 return true;
9828 }
9829
9830 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
9831 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +09009832 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -07009833 && virtual.networkCapabilities.getOwnerUid() == uid
9834 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
9835 return true;
9836 }
9837 }
9838
9839 return false;
9840 }
9841
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009842 @VisibleForTesting
9843 boolean checkConnectivityDiagnosticsPermissions(
9844 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9845 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9846 return true;
9847 }
9848
Cody Kesting160ef392021-05-05 13:17:22 -07009849 // Administrator UIDs also contains the Owner UID
9850 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
9851 if (!CollectionUtils.contains(administratorUids, callbackUid)
9852 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009853 return false;
9854 }
9855
Cody Kesting7474f672021-05-11 14:22:40 -07009856 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
9857 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009858 }
9859
Cody Kestingd199a9d2019-12-17 12:55:28 -08009860 @Override
9861 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009862 @NonNull IConnectivityDiagnosticsCallback callback,
9863 @NonNull NetworkRequest request,
9864 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -07009865 Objects.requireNonNull(callback, "callback must not be null");
9866 Objects.requireNonNull(request, "request must not be null");
9867 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
9868
Cody Kesting73708bf2019-12-18 10:57:50 -08009869 if (request.legacyType != TYPE_NONE) {
9870 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
9871 + " Please use NetworkCapabilities instead.");
9872 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009873 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -08009874 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009875
9876 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
9877 // and administrator uids to be safe.
9878 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08009879 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009880
9881 final NetworkRequest requestWithId =
9882 new NetworkRequest(
9883 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
9884
9885 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
9886 //
9887 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
9888 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
9889 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009890 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -08009891 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009892 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009893
9894 mConnectivityDiagnosticsHandler.sendMessage(
9895 mConnectivityDiagnosticsHandler.obtainMessage(
9896 ConnectivityDiagnosticsHandler
9897 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9898 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -08009899 }
9900
9901 @Override
9902 public void unregisterConnectivityDiagnosticsCallback(
9903 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +08009904 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -08009905 mConnectivityDiagnosticsHandler.sendMessage(
9906 mConnectivityDiagnosticsHandler.obtainMessage(
9907 ConnectivityDiagnosticsHandler
9908 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009909 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -08009910 0,
9911 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -08009912 }
Cody Kestingf53a0752020-04-15 12:33:28 -07009913
9914 @Override
9915 public void simulateDataStall(int detectionMethod, long timestampMillis,
9916 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -07009917 Objects.requireNonNull(network, "network must not be null");
9918 Objects.requireNonNull(extras, "extras must not be null");
9919
Cody Kestingf53a0752020-04-15 12:33:28 -07009920 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
9921 android.Manifest.permission.NETWORK_STACK);
9922 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
9923 if (!nc.hasTransport(TRANSPORT_TEST)) {
Chalard Jean15228572022-01-28 19:29:12 +09009924 throw new SecurityException("Data Stall simulation is only possible for test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -07009925 }
9926
9927 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009928 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -07009929 throw new SecurityException("Data Stall simulation is only possible for network "
9930 + "creators");
9931 }
9932
Cody Kesting652e3ec2020-05-21 12:08:21 -07009933 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
9934 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
9935 // Data Stall information as a DataStallReportParcelable and passing to
9936 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
9937 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -07009938 final DataStallReportParcelable p = new DataStallReportParcelable();
9939 p.timestampMillis = timestampMillis;
9940 p.detectionMethod = detectionMethod;
9941
9942 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
9943 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
9944 }
9945 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
9946 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
9947 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
9948 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
9949 }
9950
Serik Beketayevec8ad212020-12-07 22:43:07 -08009951 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -07009952 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009953
lucaslin66f44212021-02-23 01:12:55 +08009954 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
9955 @Override
lucaslin87b58aa2021-02-25 15:10:29 +08009956 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +08009957 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +08009958 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +08009959 }
lucaslin37a16d92021-01-21 19:48:09 +08009960
9961 @Override
9962 public void onInterfaceLinkStateChanged(String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +08009963 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +08009964 nai.clatd.interfaceLinkStateChanged(iface, up);
9965 }
9966 }
9967
9968 @Override
9969 public void onInterfaceRemoved(String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +08009970 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +08009971 nai.clatd.interfaceRemoved(iface);
9972 }
lucaslin66f44212021-02-23 01:12:55 +08009973 }
9974 }
9975
lucaslin1a8b4c62021-01-21 02:02:55 +08009976 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
9977
9978 /**
9979 * Class used for updating network activity tracking with netd and notify network activity
9980 * changes.
9981 */
9982 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +08009983 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +08009984 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +08009985 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +08009986 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
9987 new RemoteCallbackList<>();
9988 // Indicate the current system default network activity is active or not.
9989 @GuardedBy("mActiveIdleTimers")
9990 private boolean mNetworkActive;
9991 @GuardedBy("mActiveIdleTimers")
9992 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
9993 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +08009994
lucaslin1193a5d2021-01-21 02:04:15 +08009995 private class IdleTimerParams {
9996 public final int timeout;
9997 public final int transportType;
9998
9999 IdleTimerParams(int timeout, int transport) {
10000 this.timeout = timeout;
10001 this.transportType = transport;
10002 }
10003 }
10004
10005 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080010006 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080010007 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080010008 mNetd = netd;
10009 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010010 }
10011
lucaslin66f44212021-02-23 01:12:55 +080010012 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
10013 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
10014 synchronized (mActiveIdleTimers) {
10015 mNetworkActive = active;
10016 // If there are no idle timers, it means that system is not monitoring
10017 // activity, so the system default network for those default network
10018 // unspecified apps is always considered active.
10019 //
10020 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
10021 // any network activity change event. Whenever this event is received,
10022 // the mActiveIdleTimers should be always not empty. The legacy behavior
10023 // is no-op. Remove to refer to mNetworkActive only.
10024 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
10025 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
10026 }
10027 }
10028 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010029
lucaslin1193a5d2021-01-21 02:04:15 +080010030 // The network activity should only be updated from ConnectivityService handler thread
10031 // when mActiveIdleTimers lock is held.
10032 @GuardedBy("mActiveIdleTimers")
10033 private void reportNetworkActive() {
10034 final int length = mNetworkActivityListeners.beginBroadcast();
10035 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
10036 try {
10037 for (int i = 0; i < length; i++) {
10038 try {
10039 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
10040 } catch (RemoteException | RuntimeException e) {
10041 loge("Fail to send network activie to listener " + e);
10042 }
10043 }
10044 } finally {
10045 mNetworkActivityListeners.finishBroadcast();
10046 }
10047 }
10048
10049 @GuardedBy("mActiveIdleTimers")
10050 public void handleReportNetworkActivity() {
10051 synchronized (mActiveIdleTimers) {
10052 reportNetworkActive();
10053 }
10054 }
10055
lucaslin1a8b4c62021-01-21 02:02:55 +080010056 // This is deprecated and only to support legacy use cases.
10057 private int transportTypeToLegacyType(int type) {
10058 switch (type) {
10059 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010060 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080010061 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010062 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080010063 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010064 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080010065 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010066 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080010067 default:
10068 loge("Unexpected transport in transportTypeToLegacyType: " + type);
10069 }
10070 return ConnectivityManager.TYPE_NONE;
10071 }
10072
10073 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
10074 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
10075 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
10076 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
10077 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
10078 final long ident = Binder.clearCallingIdentity();
10079 try {
10080 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
10081 RECEIVE_DATA_ACTIVITY_CHANGE,
10082 null /* resultReceiver */,
10083 null /* scheduler */,
10084 0 /* initialCode */,
10085 null /* initialData */,
10086 null /* initialExtra */);
10087 } finally {
10088 Binder.restoreCallingIdentity(ident);
10089 }
10090 }
10091
10092 /**
10093 * Setup data activity tracking for the given network.
10094 *
10095 * Every {@code setupDataActivityTracking} should be paired with a
10096 * {@link #removeDataActivityTracking} for cleanup.
10097 */
10098 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
10099 final String iface = networkAgent.linkProperties.getInterfaceName();
10100
10101 final int timeout;
10102 final int type;
10103
10104 if (networkAgent.networkCapabilities.hasTransport(
10105 NetworkCapabilities.TRANSPORT_CELLULAR)) {
10106 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010107 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080010108 10);
10109 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10110 } else if (networkAgent.networkCapabilities.hasTransport(
10111 NetworkCapabilities.TRANSPORT_WIFI)) {
10112 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010113 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080010114 15);
10115 type = NetworkCapabilities.TRANSPORT_WIFI;
10116 } else {
10117 return; // do not track any other networks
10118 }
10119
lucaslinb961efc2021-01-21 02:03:17 +080010120 updateRadioPowerState(true /* isActive */, type);
10121
lucaslin1a8b4c62021-01-21 02:02:55 +080010122 if (timeout > 0 && iface != null) {
10123 try {
lucaslin1193a5d2021-01-21 02:04:15 +080010124 synchronized (mActiveIdleTimers) {
10125 // Networks start up.
10126 mNetworkActive = true;
10127 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
10128 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
10129 reportNetworkActive();
10130 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010131 } catch (Exception e) {
10132 // You shall not crash!
10133 loge("Exception in setupDataActivityTracking " + e);
10134 }
10135 }
10136 }
10137
10138 /**
10139 * Remove data activity tracking when network disconnects.
10140 */
10141 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
10142 final String iface = networkAgent.linkProperties.getInterfaceName();
10143 final NetworkCapabilities caps = networkAgent.networkCapabilities;
10144
lucaslinb961efc2021-01-21 02:03:17 +080010145 if (iface == null) return;
10146
10147 final int type;
10148 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
10149 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10150 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
10151 type = NetworkCapabilities.TRANSPORT_WIFI;
10152 } else {
10153 return; // do not track any other networks
10154 }
10155
10156 try {
10157 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080010158 synchronized (mActiveIdleTimers) {
10159 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
10160 // The call fails silently if no idle timer setup for this interface
10161 mNetd.idletimerRemoveInterface(iface, params.timeout,
10162 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080010163 }
lucaslinb961efc2021-01-21 02:03:17 +080010164 } catch (Exception e) {
10165 // You shall not crash!
10166 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080010167 }
10168 }
10169
10170 /**
10171 * Update data activity tracking when network state is updated.
10172 */
10173 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
10174 NetworkAgentInfo oldNetwork) {
10175 if (newNetwork != null) {
10176 setupDataActivityTracking(newNetwork);
10177 }
10178 if (oldNetwork != null) {
10179 removeDataActivityTracking(oldNetwork);
10180 }
10181 }
lucaslinb961efc2021-01-21 02:03:17 +080010182
10183 private void updateRadioPowerState(boolean isActive, int transportType) {
10184 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
10185 switch (transportType) {
10186 case NetworkCapabilities.TRANSPORT_CELLULAR:
10187 bs.reportMobileRadioPowerState(isActive, NO_UID);
10188 break;
10189 case NetworkCapabilities.TRANSPORT_WIFI:
10190 bs.reportWifiRadioPowerState(isActive, NO_UID);
10191 break;
10192 default:
10193 logw("Untracked transport type:" + transportType);
10194 }
10195 }
lucaslin1193a5d2021-01-21 02:04:15 +080010196
10197 public boolean isDefaultNetworkActive() {
10198 synchronized (mActiveIdleTimers) {
10199 // If there are no idle timers, it means that system is not monitoring activity,
10200 // so the default network is always considered active.
10201 //
10202 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
10203 // tracking is disabled (negative idle timer value configured), or no active default
10204 // network. In the latter case, this reports active but it should report inactive.
10205 return mNetworkActive || mActiveIdleTimers.isEmpty();
10206 }
10207 }
10208
10209 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
10210 mNetworkActivityListeners.register(l);
10211 }
10212
10213 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
10214 mNetworkActivityListeners.unregister(l);
10215 }
lucaslin012f7a12021-01-21 02:04:35 +080010216
10217 public void dump(IndentingPrintWriter pw) {
10218 synchronized (mActiveIdleTimers) {
10219 pw.print("mNetworkActive="); pw.println(mNetworkActive);
10220 pw.println("Idle timers:");
10221 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
10222 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
10223 final IdleTimerParams params = ent.getValue();
10224 pw.print(" timeout="); pw.print(params.timeout);
10225 pw.print(" type="); pw.println(params.transportType);
10226 }
10227 }
10228 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010229 }
James Mattis47db0582021-01-01 14:13:35 -080010230
Daniel Brightf9e945b2020-06-15 16:10:01 -070010231 /**
10232 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
10233 *
10234 * @param socketInfo the socket information
10235 * @param callback the callback to register
10236 */
10237 @Override
10238 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
10239 @NonNull final IQosCallback callback) {
10240 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
10241 if (nai == null || nai.networkCapabilities == null) {
10242 try {
10243 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
10244 } catch (final RemoteException ex) {
10245 loge("registerQosCallbackInternal: RemoteException", ex);
10246 }
10247 return;
10248 }
10249 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
10250 }
10251
10252 /**
10253 * Register a {@link IQosCallback} with base {@link QosFilter}.
10254 *
10255 * @param filter the filter to register
10256 * @param callback the callback to register
10257 * @param nai the agent information related to the filter's network
10258 */
10259 @VisibleForTesting
10260 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
10261 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
10262 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
10263 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
10264
10265 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
10266 enforceConnectivityRestrictedNetworksPermission();
10267 }
10268 mQosCallbackTracker.registerCallback(callback, filter, nai);
10269 }
10270
10271 /**
10272 * Unregisters the given callback.
10273 *
10274 * @param callback the callback to unregister
10275 */
10276 @Override
10277 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010278 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010279 mQosCallbackTracker.unregisterCallback(callback);
10280 }
James Mattis47db0582021-01-01 14:13:35 -080010281
James Mattis45d81842021-01-10 14:24:24 -080010282 /**
Chalard Jeanfa45a682021-02-25 17:23:40 +090010283 * Request that a user profile is put by default on a network matching a given preference.
10284 *
10285 * See the documentation for the individual preferences for a description of the supported
10286 * behaviors.
10287 *
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010288 * @param profile the user profile for whih the preference is being set.
10289 * @param preferences the list of profile network preferences for the
10290 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010291 * @param listener an optional listener to listen for completion of the operation.
10292 */
10293 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010294 public void setProfileNetworkPreferences(
10295 @NonNull final UserHandle profile,
10296 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090010297 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010298 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010299 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010300
10301 if (preferences.size() == 0) {
10302 preferences.add((new ProfileNetworkPreference.Builder()).build());
10303 }
10304
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010305 PermissionUtils.enforceNetworkStackPermission(mContext);
10306 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010307 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010308 }
10309 if (profile.getIdentifier() < 0) {
10310 throw new IllegalArgumentException("Must explicitly specify a user handle ("
10311 + "UserHandle.CURRENT not supported)");
10312 }
Chalard Jeana21ef9b2021-04-02 19:24:44 +090010313 final UserManager um = mContext.getSystemService(UserManager.class);
10314 if (!um.isManagedProfile(profile.getIdentifier())) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010315 throw new IllegalArgumentException("Profile must be a managed profile");
10316 }
paulhuaa0743d2021-05-26 21:56:03 +080010317
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010318 final List<ProfileNetworkPreferenceList.Preference> preferenceList =
10319 new ArrayList<ProfileNetworkPreferenceList.Preference>();
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010320 boolean allowFallback = true;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010321 for (final ProfileNetworkPreference preference : preferences) {
10322 final NetworkCapabilities nc;
10323 switch (preference.getPreference()) {
10324 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
10325 nc = null;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010326 if (preference.getPreferenceEnterpriseId() != 0) {
10327 throw new IllegalArgumentException(
10328 "Invalid enterprise identifier in setProfileNetworkPreferences");
10329 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010330 break;
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010331 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
10332 allowFallback = false;
10333 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010334 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010335 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
10336 throw new IllegalArgumentException(
10337 "Invalid enterprise identifier in setProfileNetworkPreferences");
10338 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010339 final Set<UidRange> uidRangeSet =
10340 getUidListToBeAppliedForNetworkPreference(profile, preference);
10341 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
10342 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
10343 } else {
10344 throw new IllegalArgumentException(
10345 "Overlapping uid range in setProfileNetworkPreferences");
10346 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010347 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010348 nc.addEnterpriseId(
10349 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010350 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10351 break;
10352 default:
10353 throw new IllegalArgumentException(
10354 "Invalid preference in setProfileNetworkPreferences");
10355 }
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010356 preferenceList.add(new ProfileNetworkPreferenceList.Preference(
10357 profile, nc, allowFallback));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010358 }
10359 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010360 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010361 }
10362
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010363 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
10364 @NonNull final UserHandle profile,
10365 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
10366 final UidRange profileUids = UidRange.createForUser(profile);
10367 Set<UidRange> uidRangeSet = UidRangeUtils.convertListToUidRange(
10368 profileNetworkPreference.getIncludedUids());
10369 if (uidRangeSet.size() > 0) {
10370 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
10371 throw new IllegalArgumentException(
10372 "Allow uid range is outside the uid range of profile.");
10373 }
10374 } else {
10375 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertListToUidRange(
10376 profileNetworkPreference.getExcludedUids());
10377 if (disallowUidRangeSet.size() > 0) {
10378 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
10379 throw new IllegalArgumentException(
10380 "disallow uid range is outside the uid range of profile.");
10381 }
10382 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
10383 disallowUidRangeSet);
10384 } else {
10385 uidRangeSet = new ArraySet<UidRange>();
10386 uidRangeSet.add(profileUids);
10387 }
10388 }
10389 return uidRangeSet;
10390 }
10391
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010392 private boolean isEnterpriseIdentifierValid(
10393 @NetworkCapabilities.EnterpriseId int identifier) {
10394 if ((identifier >= NET_ENTERPRISE_ID_1)
10395 && (identifier <= NET_ENTERPRISE_ID_5)) {
10396 return true;
10397 }
10398 return false;
10399 }
10400
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010401 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
10402 @Nullable final NetworkCapabilities nc) {
10403 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
10404 ensureRequestableCapabilities(nc);
10405 }
10406
10407 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010408 @NonNull final ProfileNetworkPreferenceList prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010409 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010410 for (final ProfileNetworkPreferenceList.Preference pref : prefs.preferences) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010411 // The NRI for a user should contain the request for capabilities.
10412 // If fallback to default network is needed then NRI should include
10413 // the request for the default network. Create an image of it to
10414 // have the correct UIDs in it (also a request can only be part of one NRI, because
10415 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010416 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
10417 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010418 if (pref.allowFallback) {
10419 nrs.add(createDefaultInternetRequestForTransport(
10420 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10421 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010422 if (VDBG) {
10423 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
10424 pref.capabilities.getUids()));
10425 }
10426
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010427 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080010428 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080010429 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010430 result.add(nri);
10431 }
10432 return result;
10433 }
10434
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010435 /**
10436 * Compare if the given UID range sets have the same UIDs.
10437 *
10438 */
10439 private boolean isRangeAlreadyInPreferenceList(
10440 @NonNull List<ProfileNetworkPreferenceList.Preference> preferenceList,
10441 @NonNull Set<UidRange> uidRangeSet) {
10442 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
10443 return false;
10444 }
10445 for (ProfileNetworkPreferenceList.Preference pref : preferenceList) {
10446 if (UidRangeUtils.doesRangeSetOverlap(
10447 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
10448 return true;
10449 }
10450 }
10451 return false;
10452 }
10453
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010454 private void handleSetProfileNetworkPreference(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010455 @NonNull final List<ProfileNetworkPreferenceList.Preference> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010456 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010457 for (final ProfileNetworkPreferenceList.Preference preference : preferenceList) {
10458 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
10459 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
10460 }
paulhu74128522021-09-28 02:29:03 +000010461 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
10462 addPerAppDefaultNetworkRequests(
10463 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010464 // Finally, rematch.
10465 rematchAllNetworksAndRequests();
10466
10467 if (null != listener) {
10468 try {
10469 listener.onComplete();
10470 } catch (RemoteException e) {
10471 loge("Listener for setProfileNetworkPreference has died");
10472 }
10473 }
10474 }
10475
paulhu51f77dc2021-06-07 02:34:20 +000010476 @VisibleForTesting
10477 @NonNull
10478 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
10479 @NonNull final Set<Integer> uids) {
10480 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10481 if (uids.size() == 0) {
10482 // Should not create NetworkRequestInfo if no preferences. Without uid range in
10483 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
10484 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
10485 return nris;
10486 }
10487
10488 final List<NetworkRequest> requests = new ArrayList<>();
10489 // The NRI should be comprised of two layers:
10490 // - The request for the mobile network preferred.
10491 // - The request for the default network, for fallback.
10492 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090010493 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000010494 requests.add(createDefaultInternetRequestForTransport(
10495 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10496 final Set<UidRange> ranges = new ArraySet<>();
10497 for (final int uid : uids) {
10498 ranges.add(new UidRange(uid, uid));
10499 }
10500 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080010501 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080010502 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000010503 return nris;
10504 }
10505
10506 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000010507 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000010508 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
10509 addPerAppDefaultNetworkRequests(
10510 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000010511 // Finally, rematch.
10512 rematchAllNetworksAndRequests();
10513 }
10514
James Mattis45d81842021-01-10 14:24:24 -080010515 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080010516 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
10517 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080010518 }
10519
10520 /**
10521 * Used by automotive devices to set the network preferences used to direct traffic at an
10522 * application level as per the given OemNetworkPreferences. An example use-case would be an
10523 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
10524 * vehicle via a particular network.
10525 *
10526 * Calling this will overwrite the existing preference.
10527 *
James Mattisda32cfe2021-01-26 16:23:52 -080010528 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090010529 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080010530 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080010531 */
James Mattis47db0582021-01-01 14:13:35 -080010532 @Override
James Mattis45d81842021-01-10 14:24:24 -080010533 public void setOemNetworkPreference(
10534 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010535 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080010536
James Mattisfa270db2021-05-31 17:11:10 -070010537 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10538 // Only bypass the permission/device checks if this is a valid test request.
10539 if (isValidTestOemNetworkPreference(preference)) {
10540 enforceManageTestNetworksPermission();
10541 } else {
10542 enforceAutomotiveDevice();
10543 enforceOemNetworkPreferencesPermission();
10544 validateOemNetworkPreferences(preference);
10545 }
James Mattis45d81842021-01-10 14:24:24 -080010546
James Mattis45d81842021-01-10 14:24:24 -080010547 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
10548 new Pair<>(preference, listener)));
10549 }
10550
James Mattisfa270db2021-05-31 17:11:10 -070010551 /**
10552 * Check the validity of an OEM network preference to be used for testing purposes.
10553 * @param preference the preference to validate
10554 * @return true if this is a valid OEM network preference test request.
10555 */
10556 private boolean isValidTestOemNetworkPreference(
10557 @NonNull final OemNetworkPreferences preference) {
10558 // Allow for clearing of an existing OemNetworkPreference used for testing.
10559 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
10560 // changes after this check is complete. This is an unlikely scenario as calling of this API
10561 // is controlled by the OEM therefore the added complexity is not worth adding given those
10562 // circumstances. That said, it is an edge case to be aware of hence this comment.
10563 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
10564 && isTestOemNetworkPreference(mOemNetworkPreferences);
10565 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
10566 }
10567
10568 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
10569 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
10570 return prefMap.size() == 1
10571 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
10572 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
10573 }
10574
James Mattis45d81842021-01-10 14:24:24 -080010575 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
10576 for (@OemNetworkPreferences.OemNetworkPreference final int pref
10577 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070010578 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
10579 throw new IllegalArgumentException(
10580 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
10581 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080010582 }
10583 }
10584 }
10585
10586 private void handleSetOemNetworkPreference(
10587 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010588 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080010589 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10590 if (DBG) {
10591 log("set OEM network preferences :" + preference.toString());
10592 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010593
James Mattiscb1e0362021-04-06 17:07:42 -070010594 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000010595 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
10596 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
10597 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080010598 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080010599
10600 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010601 try {
10602 listener.onComplete();
10603 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080010604 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010605 }
James Mattis45d81842021-01-10 14:24:24 -080010606 }
10607 }
10608
paulhu74128522021-09-28 02:29:03 +000010609 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080010610 // Skip the requests which are set by other network preference. Because the uid range rules
10611 // should stay in netd.
10612 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080010613 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080010614 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080010615 }
10616
James Mattis3ce3d3c2021-02-09 18:18:28 -080010617 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
10618 ensureRunningOnConnectivityServiceThread();
10619 mDefaultNetworkRequests.addAll(nris);
10620 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
10621 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080010622 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000010623 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
10624 nrisToRegister.addAll(
10625 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
10626 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010627 }
10628
10629 /**
10630 * All current requests that are tracking the default network need to be assessed as to whether
10631 * or not the current set of per-application default requests will be changing their default
10632 * network. If so, those requests will need to be updated so that they will send callbacks for
10633 * default network changes at the appropriate time. Additionally, those requests tracking the
10634 * default that were previously updated by this flow will need to be reassessed.
10635 * @return the nris which will need to be updated.
10636 */
10637 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
10638 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
10639 // Get the distinct nris to check since for multilayer requests, it is possible to have the
10640 // same nri in the map's values for each of its NetworkRequest objects.
10641 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080010642 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010643 // Include this nri if it is currently being tracked.
10644 if (isPerAppTrackedNri(nri)) {
10645 defaultCallbackRequests.add(nri);
10646 continue;
10647 }
10648 // We only track callbacks for requests tracking the default.
10649 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
10650 continue;
10651 }
10652 // Include this nri if it will be tracked by the new per-app default requests.
10653 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010654 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080010655 if (isNriGoingToBeTracked) {
10656 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080010657 }
10658 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080010659 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080010660 }
10661
James Mattis3ce3d3c2021-02-09 18:18:28 -080010662 /**
10663 * Create nris for those network requests that are currently tracking the default network that
10664 * are being controlled by a per-application default.
10665 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
10666 * foundation when creating the nri. Important items include the calling uid's original
10667 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
10668 * requests are assumed to have already been validated as needing to be updated.
10669 * @return the Set of nris to use when registering network requests.
10670 */
10671 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
10672 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
10673 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
10674 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
10675 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010676 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010677
Chalard Jean9473c982021-07-29 20:03:04 +090010678 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080010679 if (trackingNri == mDefaultRequest) {
10680 callbackRequestsToRegister.add(new NetworkRequestInfo(
10681 callbackRequest,
10682 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
10683 continue;
10684 }
10685
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010686 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010687 callbackRequestsToRegister.add(new NetworkRequestInfo(
10688 callbackRequest,
10689 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010690 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090010691 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080010692 }
10693 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080010694 }
10695
Chalard Jean17215832021-03-01 14:06:28 +090010696 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
10697 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090010698 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010699 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090010700 }
10701 }
10702
James Mattis45d81842021-01-10 14:24:24 -080010703 /**
10704 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
10705 */
10706 @VisibleForTesting
10707 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010708 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080010709 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010710 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080010711 final SparseArray<Set<Integer>> uids =
10712 createUidsFromOemNetworkPreferences(preference);
10713 for (int i = 0; i < uids.size(); i++) {
10714 final int key = uids.keyAt(i);
10715 final Set<Integer> value = uids.valueAt(i);
10716 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
10717 // No need to add an nri without any requests.
10718 if (0 == nri.mRequests.size()) {
10719 continue;
10720 }
10721 nris.add(nri);
10722 }
10723
10724 return nris;
10725 }
10726
10727 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
10728 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070010729 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080010730 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080010731 final List<UserHandle> users =
10732 mContext.getSystemService(UserManager.class).getUserHandles(true);
10733 if (null == users || users.size() == 0) {
10734 if (VDBG || DDBG) {
10735 log("No users currently available for setting the OEM network preference.");
10736 }
James Mattisb6b6a432021-06-01 22:30:36 -070010737 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080010738 }
James Mattis45d81842021-01-10 14:24:24 -080010739 for (final Map.Entry<String, Integer> entry :
10740 preference.getNetworkPreferences().entrySet()) {
10741 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070010742 // Add the rules for all users as this policy is device wide.
10743 for (final UserHandle user : users) {
10744 try {
10745 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
10746 if (!prefToUids.contains(pref)) {
10747 prefToUids.put(pref, new ArraySet<>());
10748 }
10749 prefToUids.get(pref).add(uid);
10750 } catch (PackageManager.NameNotFoundException e) {
10751 // Although this may seem like an error scenario, it is ok that uninstalled
10752 // packages are sent on a network preference as the system will watch for
10753 // package installations associated with this network preference and update
10754 // accordingly. This is done to minimize race conditions on app install.
10755 continue;
James Mattis45d81842021-01-10 14:24:24 -080010756 }
James Mattis45d81842021-01-10 14:24:24 -080010757 }
10758 }
James Mattisb6b6a432021-06-01 22:30:36 -070010759 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080010760 }
10761
10762 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10763 @OemNetworkPreferences.OemNetworkPreference final int preference,
10764 @NonNull final Set<Integer> uids) {
10765 final List<NetworkRequest> requests = new ArrayList<>();
10766 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10767 switch (preference) {
10768 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10769 requests.add(createUnmeteredNetworkRequest());
10770 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070010771 requests.add(createDefaultInternetRequestForTransport(
10772 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080010773 break;
10774 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10775 requests.add(createUnmeteredNetworkRequest());
10776 requests.add(createOemPaidNetworkRequest());
10777 break;
10778 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10779 requests.add(createOemPaidNetworkRequest());
10780 break;
10781 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10782 requests.add(createOemPrivateNetworkRequest());
10783 break;
James Mattisfa270db2021-05-31 17:11:10 -070010784 case OEM_NETWORK_PREFERENCE_TEST:
10785 requests.add(createUnmeteredNetworkRequest());
10786 requests.add(createTestNetworkRequest());
10787 requests.add(createDefaultRequest());
10788 break;
10789 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
10790 requests.add(createTestNetworkRequest());
10791 break;
James Mattis45d81842021-01-10 14:24:24 -080010792 default:
10793 // This should never happen.
10794 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10795 + " called with invalid preference of " + preference);
10796 }
10797
James Mattisfa270db2021-05-31 17:11:10 -070010798 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090010799 for (final int uid : uids) {
10800 ranges.add(new UidRange(uid, uid));
10801 }
10802 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080010803 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080010804 }
10805
10806 private NetworkRequest createUnmeteredNetworkRequest() {
10807 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10808 .addCapability(NET_CAPABILITY_NOT_METERED)
10809 .addCapability(NET_CAPABILITY_VALIDATED);
10810 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10811 }
10812
10813 private NetworkRequest createOemPaidNetworkRequest() {
10814 // NET_CAPABILITY_OEM_PAID is a restricted capability.
10815 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10816 .addCapability(NET_CAPABILITY_OEM_PAID)
10817 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10818 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10819 }
10820
10821 private NetworkRequest createOemPrivateNetworkRequest() {
10822 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
10823 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10824 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
10825 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10826 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10827 }
10828
10829 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070010830 final NetworkCapabilities netcap = new NetworkCapabilities();
10831 netcap.addCapability(NET_CAPABILITY_INTERNET);
10832 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
10833 return netcap;
10834 }
10835
10836 private NetworkRequest createTestNetworkRequest() {
10837 final NetworkCapabilities netcap = new NetworkCapabilities();
10838 netcap.clearAll();
10839 netcap.addTransportType(TRANSPORT_TEST);
10840 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080010841 }
James Mattis47db0582021-01-01 14:13:35 -080010842 }
markchien738ad912021-12-09 18:15:45 +080010843
10844 @Override
10845 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
10846 enforceNetworkStackOrSettingsPermission();
10847
10848 try {
10849 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080010850 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080010851 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080010852 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080010853 }
Ken Chenf5f51332022-01-28 10:08:16 +080010854 } catch (RemoteException | ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080010855 throw new IllegalStateException(e);
10856 }
10857 }
10858
10859 @Override
10860 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
10861 enforceNetworkStackOrSettingsPermission();
10862
10863 try {
10864 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080010865 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080010866 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080010867 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080010868 }
Ken Chenf5f51332022-01-28 10:08:16 +080010869 } catch (RemoteException | ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080010870 throw new IllegalStateException(e);
10871 }
10872 }
markchiene1561fa2021-12-09 22:00:56 +080010873
10874 @Override
10875 public void updateFirewallRule(final int chain, final int uid, final boolean allow) {
10876 enforceNetworkStackOrSettingsPermission();
10877
10878 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080010879 mBpfNetMaps.setUidRule(chain, uid,
markchiene1561fa2021-12-09 22:00:56 +080010880 allow ? INetd.FIREWALL_RULE_ALLOW : INetd.FIREWALL_RULE_DENY);
Ken Chenf5f51332022-01-28 10:08:16 +080010881 } catch (RemoteException | ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080010882 throw new IllegalStateException(e);
10883 }
10884 }
markchien98a6f952022-01-13 23:43:53 +080010885
10886 @Override
10887 public void setFirewallChainEnabled(final int chain, final boolean enable) {
10888 enforceNetworkStackOrSettingsPermission();
10889
10890 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080010891 mBpfNetMaps.setChildChain(chain, enable);
Ken Chenf5f51332022-01-28 10:08:16 +080010892 } catch (RemoteException | ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080010893 throw new IllegalStateException(e);
10894 }
10895 }
10896
markchien00a0bed2022-01-13 23:46:13 +080010897 @Override
10898 public void replaceFirewallChain(final int chain, final int[] uids) {
10899 enforceNetworkStackOrSettingsPermission();
10900
10901 try {
10902 switch (chain) {
10903 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
Wayne Ma2fde98c2022-01-17 18:04:05 +080010904 mBpfNetMaps.replaceUidChain("fw_dozable", true /* isAllowList */, uids);
markchien00a0bed2022-01-13 23:46:13 +080010905 break;
10906 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Wayne Ma2fde98c2022-01-17 18:04:05 +080010907 mBpfNetMaps.replaceUidChain("fw_standby", false /* isAllowList */, uids);
markchien00a0bed2022-01-13 23:46:13 +080010908 break;
10909 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
Wayne Ma2fde98c2022-01-17 18:04:05 +080010910 mBpfNetMaps.replaceUidChain("fw_powersave", true /* isAllowList */, uids);
markchien00a0bed2022-01-13 23:46:13 +080010911 break;
10912 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
Wayne Ma2fde98c2022-01-17 18:04:05 +080010913 mBpfNetMaps.replaceUidChain("fw_restricted", true /* isAllowList */, uids);
markchien00a0bed2022-01-13 23:46:13 +080010914 break;
Robert Horvath1db49e12022-01-27 19:54:29 +010010915 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
10916 mBpfNetMaps.replaceUidChain("fw_low_power_standby", true /* isAllowList */,
10917 uids);
10918 break;
markchien00a0bed2022-01-13 23:46:13 +080010919 default:
10920 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
10921 + chain);
10922 }
Ken Chenf5f51332022-01-28 10:08:16 +080010923 } catch (RemoteException | ServiceSpecificException e) {
markchien00a0bed2022-01-13 23:46:13 +080010924 throw new IllegalStateException(e);
10925 }
10926 }
markchien9c806112022-01-11 23:28:23 +080010927
10928 @Override
10929 public void swapActiveStatsMap() {
10930 enforceNetworkStackOrSettingsPermission();
10931 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080010932 mBpfNetMaps.swapActiveStatsMap();
Ken Chenf5f51332022-01-28 10:08:16 +080010933 } catch (RemoteException | ServiceSpecificException e) {
markchien9c806112022-01-11 23:28:23 +080010934 throw new IllegalStateException(e);
10935 }
10936 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070010937}