blob: fa7dfa9846d73a9720b3602409e2e6dc6d696851 [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000018
Haoyu Baib5da5752012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090020import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
21import static android.content.pm.PackageManager.FEATURE_WATCH;
22import static android.content.pm.PackageManager.FEATURE_WIFI;
23import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
Chalard Jean9a396cc2018-02-21 18:43:54 +090024import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +090025import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
26import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
27import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
28import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
29import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090033import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
34import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka98215562021-03-23 08:12:28 +000035import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
Jeff Sharkey971cd162011-08-29 16:02:57 -070036import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090037import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090038import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090039import static android.net.ConnectivityManager.TYPE_MOBILE;
40import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
41import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
42import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
43import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
44import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
45import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
46import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
47import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
48import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070049import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090050import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070051import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090052import static android.net.ConnectivityManager.TYPE_WIFI;
53import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070054import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070055import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080056import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080057import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080058import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070059import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080060import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen53f08952015-06-16 14:27:36 -040061import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090062import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090063import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090064import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090065import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090066import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
67import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060068import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090069import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080070import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090071import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080072import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
73import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080074import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090075import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080076import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
77import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080078import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
79import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
80import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090081import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090082import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060083import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070084import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080085import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090086import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070087import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
88import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +090089import static android.net.shared.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070090import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080091import static android.os.Process.VPN_UID;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +090092import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070093import static android.system.OsConstants.IPPROTO_TCP;
94import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey07e19362017-10-27 17:22:59 -060095
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +090096import static com.android.net.module.util.DeviceConfigUtils.TETHERING_MODULE_NAME;
97
Cody Kesting83bb5fa2020-01-05 14:06:39 -080098import static java.util.Map.Entry;
99
Chalard Jean5b639762020-03-09 21:25:37 +0900100import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000101import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800102import android.annotation.Nullable;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800103import android.annotation.TargetApi;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800104import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800105import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700106import android.app.PendingIntent;
junyulaie7c7d2a2021-01-26 15:29:15 +0800107import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700108import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800109import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800110import android.content.ContentResolver;
111import android.content.Context;
112import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700113import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800114import android.content.pm.PackageManager;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700115import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900116import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900117import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700118import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800119import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800120import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800121import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900122import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800123import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900124import android.net.ConnectivityManager.RestrictBackgroundStatus;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900125import android.net.ConnectivityResources;
paulhu90a7a512021-03-17 17:19:09 +0800126import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900127import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800128import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700129import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900130import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800131import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800132import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800133import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800134import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800135import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900136import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900137import android.net.INetworkMonitor;
138import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900139import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900140import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700141import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800142import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900143import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900144import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900145import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800146import android.net.LinkProperties;
Charles He9369e612017-05-15 17:07:18 +0100147import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800148import android.net.NativeNetworkConfig;
149import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800150import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700151import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700152import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900153import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700154import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800155import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700156import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900157import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900158import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000159import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900160import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700161import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900162import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700163import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900164import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700165import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800166import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900167import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700168import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000169import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800170import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900171import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800172import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400173import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700174import android.net.QosCallbackException;
175import android.net.QosFilter;
176import android.net.QosSocketFilter;
177import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700178import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800179import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800180import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800181import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900182import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400183import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800184import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800185import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400186import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800187import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900188import android.net.VpnTransportInfo;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900189import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900190import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800191import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900192import android.net.networkstack.ModuleNetworkStackClient;
193import android.net.networkstack.NetworkStackClientBase;
paulhu7c0a2e62021-01-08 00:51:49 +0800194import android.net.resolv.aidl.DnsHealthEventParcel;
195import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
196import android.net.resolv.aidl.Nat64PrefixEventParcel;
197import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900198import android.net.shared.PrivateDnsConfig;
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900199import android.net.util.MultinetworkPolicyTracker;
lucaslinb961efc2021-01-21 02:03:17 +0800200import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800201import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800202import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700203import android.os.Bundle;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800204import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700205import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700206import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800207import android.os.Looper;
208import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700209import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700210import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900211import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800212import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700213import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700214import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800215import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700216import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900217import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900218import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700219import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700220import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400221import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800222import android.provider.Settings;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900223import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700224import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700225import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700226import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800227import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900228import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000229import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600230import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900231import android.util.Pair;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700232import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700233import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800234
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900235import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400236import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400237import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700238import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900239import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800240import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900241import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800242import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900243import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900244import com.android.net.module.util.DeviceConfigUtils;
Chalard Jean79162542020-08-19 16:07:22 +0900245import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
246import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900247import com.android.net.module.util.LocationPermissionChecker;
lifrade6c2a2021-03-04 14:08:08 +0800248import com.android.net.module.util.NetworkCapabilitiesUtils;
paulhudf23d662021-01-25 18:53:17 +0800249import com.android.net.module.util.PermissionUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000250import com.android.net.module.util.netlink.InetDiagMessage;
Chalard Jean7284daa2019-05-30 14:58:29 +0900251import com.android.server.connectivity.AutodestructReference;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900252import com.android.server.connectivity.ConnectivityFlags;
Erik Kline32120082017-12-13 19:40:49 +0900253import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500254import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700255import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900256import com.android.server.connectivity.FullScore;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900257import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100258import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700259import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700260import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600261import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900262import com.android.server.connectivity.NetworkNotificationManager;
263import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900264import com.android.server.connectivity.NetworkOffer;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900265import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700266import com.android.server.connectivity.PermissionMonitor;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800267import com.android.server.connectivity.ProfileNetworkPreferenceList;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900268import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700269import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800270import com.android.server.connectivity.UidRangeUtils;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600271
Josh Gao461a1222020-06-16 15:58:11 -0700272import libcore.io.IoUtils;
273
The Android Open Source Project28527d22009-03-03 19:31:44 -0800274import java.io.FileDescriptor;
275import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900276import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700277import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700278import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900279import java.net.InetSocketAddress;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700280import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700281import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700282import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700283import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800284import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900285import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800286import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700287import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700288import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700289import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700290import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900291import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700292import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900293import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600294import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900295import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600296import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900297import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800298
299/**
300 * @hide
301 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800302public class ConnectivityService extends IConnectivityManager.Stub
303 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900304 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800305
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900306 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900307 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900308 private static final String NETWORK_ARG = "networks";
309 private static final String REQUEST_ARG = "requests";
Erik Klined364a242017-05-12 16:52:48 +0900310
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900311 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900312 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
313 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800314
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900315 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700316
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100317 /**
318 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
319 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800320 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100321 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
322 * (preferably via runtime resource overlays).
323 */
324 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
325 "http://connectivitycheck.gstatic.com/generate_204";
326
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700327 // TODO: create better separation between radio types and network types
328
Robert Greenwalt2034b912009-08-12 16:08:25 -0700329 // how long to wait before switching back to a radio's default network
330 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
331 // system property that can override the above value
332 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
333 "android.telephony.apn-restore";
334
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900335 // How long to wait before putting up a "This network doesn't have an Internet connection,
336 // connect anyway?" dialog after the user selects a network that doesn't validate.
337 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
338
junyulai0ac374f2020-12-14 18:41:52 +0800339 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900340 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
341 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800342 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700343
344 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900345 @VisibleForTesting
346 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700347
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900348 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700349 @VisibleForTesting
350 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900351
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900352 @VisibleForTesting
353 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800354 @VisibleForTesting
355 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900356 // True if the cell radio of the device is capable of time-sharing.
357 @VisibleForTesting
358 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900359
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800360 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800361 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800362 private final int mReleasePendingIntentDelayMs;
363
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900364 private MockableSystemProperties mSystemProperties;
365
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000366 @VisibleForTesting
367 protected final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700368
Chalard Jean9473c982021-07-29 20:03:04 +0900369 @VisibleForTesting
370 final PerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700371 @VisibleForTesting
372 final PerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700373
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900374 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700375
junyulaif2c67e42018-08-07 19:50:45 +0800376 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000377 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
378 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800379 */
Sudheer Shanka9967d462021-03-18 19:09:25 +0000380 private SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800381
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900382 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900383 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000384 // The Context is created for UserHandle.ALL.
385 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900386 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900387 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700388 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700389 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800390
Chenbo Feng15416292018-11-08 17:36:21 -0800391 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800392 protected IDnsResolver mDnsResolver;
393 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800394 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700395 private DscpPolicyTracker mDscpPolicyTracker = null;
junyulaie7c7d2a2021-01-26 15:29:15 +0800396 private NetworkStatsManager mStatsManager;
paulhu9a9f71b2020-12-29 18:15:13 +0800397 private NetworkPolicyManager mPolicyManager;
lucaslin66f44212021-02-23 01:12:55 +0800398 private final NetdCallback mNetdCallback;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700399
Benedict Wong493e04b2018-11-09 14:45:34 -0800400 /**
401 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
402 * instances.
403 */
404 @GuardedBy("mTNSLock")
405 private TestNetworkService mTNS;
406
407 private final Object mTNSLock = new Object();
408
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700409 private String mCurrentTcpBufferSizes;
410
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900411 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
lifraf3a3492021-03-10 13:58:14 +0800412 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900413
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500414 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400415 // Tear down networks that have no chance (e.g. even if validated) of becoming
416 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500417 // all networks have been rematched against all NetworkRequests.
418 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400419 // Don't reap networks. This should be passed when some networks have not yet been
420 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500421 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900422 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500423
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900424 private enum UnneededFor {
425 LINGER, // Determine whether this network is unneeded and should be lingered.
426 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
427 }
428
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700429 /**
paulhuaa0743d2021-05-26 21:56:03 +0800430 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800431 * should have priority. The order is passed to netd which will use it together
432 * with UID ranges to generate the corresponding IP rule. This serves to
433 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800434 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800435 * Order ints passed to netd must be in the 0~999 range. Larger values code for
paulhuaa0743d2021-05-26 21:56:03 +0800436 * a lower priority, {@see NativeUidRangeConfig}
paulhue9913722021-05-26 15:19:20 +0800437 *
paulhu48291862021-07-14 14:53:57 +0800438 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
439 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800440 */
paulhu48291862021-07-14 14:53:57 +0800441 // Bound for the lowest valid preference order.
442 static final int PREFERENCE_ORDER_LOWEST = 999;
443 // Used when sending to netd to code for "no order".
444 static final int PREFERENCE_ORDER_NONE = 0;
445 // Order for requests that don't code for a per-app preference. As it is
446 // out of the valid range, the corresponding order should be
447 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800448 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800449 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
450 // Order for the default internet request. Since this must always have the
paulhuaa0743d2021-05-26 21:56:03 +0800451 // lowest priority, its value is larger than the largest acceptable value. As
paulhu48291862021-07-14 14:53:57 +0800452 // it is out of the valid range, the corresponding order should be
453 // PREFERENCE_ORDER_NONE when sending to netd.
454 static final int PREFERENCE_ORDER_DEFAULT = 1000;
paulhuaa0743d2021-05-26 21:56:03 +0800455 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800456 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
457 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800458 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800459 static final int PREFERENCE_ORDER_OEM = 10;
460 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800461 // See {@link #setProfileNetworkPreference}.
462 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800463 static final int PREFERENCE_ORDER_PROFILE = 20;
464 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800465 // better scores are connected.
466 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800467 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800468 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
paulhue9913722021-05-26 15:19:20 +0800469
470 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700471 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700472 * from one net to another. Clear happens when we get a new
473 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
474 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700475 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700476 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700477
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700478 /**
479 * used internally to reload global proxy settings
480 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700481 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700482
Robert Greenwalt34848c02011-03-25 13:09:25 -0700483 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400484 * PAC manager has received new port.
485 */
486 private static final int EVENT_PROXY_HAS_CHANGED = 16;
487
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700488 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900489 * used internally when registering NetworkProviders
490 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700491 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900492 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700493
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700494 /**
495 * used internally when registering NetworkAgents
496 * obj = Messenger
497 */
498 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
499
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700500 /**
501 * used to add a network request
502 * includes a NetworkRequestInfo
503 */
504 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
505
506 /**
507 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900508 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700509 * cancel it.
510 * includes a NetworkRequestInfo
511 */
512 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
513
514 /**
515 * used to add a network listener - no request
516 * includes a NetworkRequestInfo
517 */
518 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
519
520 /**
521 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400522 * arg1 = UID of caller
523 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700524 */
525 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
526
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700527 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900528 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700529 * obj = Messenger
530 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900531 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700532
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700533 /**
534 * used internally to expire a wakelock when transitioning
535 * from one net to another. Expire happens when we fail to find
536 * a new network (typically after 1 minute) -
537 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
538 * a replacement network.
539 */
540 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
541
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700542 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800543 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400544 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800545 */
546 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
547
548 /**
549 * used to remove a pending intent and its associated network request.
550 * arg1 = UID of caller
551 * obj = PendingIntent
552 */
553 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
554
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900555 /**
556 * used to specify whether a network should be used even if unvalidated.
557 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
558 * arg2 = whether to remember this choice in the future (1 or 0)
559 * obj = network
560 */
561 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
562
563 /**
564 * used to ask the user to confirm a connection to an unvalidated network.
565 * obj = network
566 */
567 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700568
Erik Kline05f2b402015-04-30 12:58:40 +0900569 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700570 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900571 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700572 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900573
Paul Jensenc8873fc2015-06-17 14:15:39 -0400574 /**
575 * used to add a network listener with a pending intent
576 * obj = NetworkRequestInfo
577 */
578 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
579
Hugo Benichid6b510a2017-04-06 17:22:18 +0900580 /**
581 * used to specify whether a network should not be penalized when it becomes unvalidated.
582 */
583 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
584
585 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700586 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900587 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700588 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900589
Erik Kline31b4a9e2018-01-11 21:07:29 +0900590 // Handle changes in Private DNS settings.
591 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
592
dalyk1720e542018-03-05 12:42:22 -0500593 // Handle private DNS validation status updates.
594 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
595
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900596 /**
597 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
598 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800599 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
600 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
601 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900602 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900603 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900604
605 /**
606 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
607 * config was resolved.
608 * obj = PrivateDnsConfig
609 * arg2 = netid
610 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900611 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900612
613 /**
614 * Request ConnectivityService display provisioning notification.
615 * arg1 = Whether to make the notification visible.
616 * arg2 = NetID.
617 * obj = Intent to be launched when notification selected by user, null if !arg1.
618 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900619 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900620
621 /**
lucaslin2240ef62019-03-12 13:08:03 +0800622 * Used to specify whether a network should be used even if connectivity is partial.
623 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
624 * false)
625 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
626 * obj = network
627 */
lucaslin444d43a2020-02-20 16:56:59 +0800628 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800629
630 /**
lucasline117e2e2019-10-22 18:27:33 +0800631 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
632 * Both of the arguments are bitmasks, and the value of bits come from
633 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
634 * arg1 = A bitmask to describe which probes are completed.
635 * arg2 = A bitmask to describe which probes are successful.
636 */
lucaslin444d43a2020-02-20 16:56:59 +0800637 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800638
639 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900640 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
641 * arg1 = unused
642 * arg2 = netId
643 * obj = captive portal data
644 */
lucaslin444d43a2020-02-20 16:56:59 +0800645 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900646
647 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900648 * Used by setRequireVpnForUids.
649 * arg1 = whether the specified UID ranges are required to use a VPN.
650 * obj = Array of UidRange objects.
651 */
652 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
653
654 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900655 * Used internally when setting the default networks for OemNetworkPreferences.
656 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800657 */
658 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
659
660 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800661 * Used to indicate the system default network becomes active.
662 */
663 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
664
665 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900666 * Used internally when setting a network preference for a user profile.
667 * obj = Pair<ProfileNetworkPreference, Listener>
668 */
669 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
670
671 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000672 * Event to specify that reasons for why an uid is blocked changed.
673 * arg1 = uid
674 * arg2 = blockedReasons
675 */
676 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
677
678 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900679 * Event to register a new network offer
680 * obj = NetworkOffer
681 */
682 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
683
684 /**
685 * Event to unregister an existing network offer
686 * obj = INetworkOfferCallback
687 */
688 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
689
690 /**
paulhu51f77dc2021-06-07 02:34:20 +0000691 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
692 */
693 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
694
695 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800696 * Event to set temporary allow bad wifi within a limited time to override
697 * {@code config_networkAvoidBadWifi}.
698 */
699 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
700
701 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900702 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
703 * should be shown.
704 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900705 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900706
707 /**
708 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
709 * should be hidden.
710 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900711 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900712
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800713 /**
714 * The maximum alive time to allow bad wifi configuration for testing.
715 */
716 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
717
Hugo Benichi47011212017-03-30 10:46:05 +0900718 private static String eventName(int what) {
719 return sMagicDecoderRing.get(what, Integer.toString(what));
720 }
721
paulhua10d8212020-11-10 15:32:56 +0800722 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900723 final DnsResolverServiceManager dsm = context.getSystemService(
724 DnsResolverServiceManager.class);
725 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800726 }
727
Cody Kesting73708bf2019-12-18 10:57:50 -0800728 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900729 @VisibleForTesting
730 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700731 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700732 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700733 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700734 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800735 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
736 @VisibleForTesting
737 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
738
Erik Kline32120082017-12-13 19:40:49 +0900739 private final DnsManager mDnsManager;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900740 private final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700741
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400742 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800743 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400744
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700745 private PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800746 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700747
Chalard Jean5d70ba42018-06-07 16:44:04 +0900748 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
749 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000750 @VisibleForTesting
751 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400752
Erik Kline05f2b402015-04-30 12:58:40 +0900753 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700754
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400755 private UserManager mUserManager;
756
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700757 // the set of network types that can only be enabled by system/sig apps
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900758 private List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700759
Valentin Iftime9fa35092019-09-24 13:32:13 +0200760 private Set<String> mWolSupportedInterfaces;
761
Roshan Pius08c94fb2020-01-16 12:17:17 -0800762 private final TelephonyManager mTelephonyManager;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800763 private final AppOpsManager mAppOpsManager;
764
765 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400766
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900767 private KeepaliveTracker mKeepaliveTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700768 private QosCallbackTracker mQosCallbackTracker;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900769 private NetworkNotificationManager mNotifier;
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +0900770 private LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900771
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700772 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800773 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700774
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900775 // Sequence number for NetworkProvider IDs.
776 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
777 NetworkProvider.FIRST_PROVIDER_ID);
778
Erik Klineedf878b2015-07-09 18:24:03 +0900779 // NetworkRequest activity String log entries.
780 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
781 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
782
Hugo Benichid159fdd2016-07-11 11:05:12 +0900783 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900784 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900785 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
786
Hugo Benichi47011212017-03-30 10:46:05 +0900787 private static final int MAX_WAKELOCK_LOGS = 20;
788 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900789 private int mTotalWakelockAcquisitions = 0;
790 private int mTotalWakelockReleases = 0;
791 private long mTotalWakelockDurationMs = 0;
792 private long mMaxWakelockDurationMs = 0;
793 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900794
Hugo Benichi208c0102016-07-28 17:53:06 +0900795 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900796
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700797 @GuardedBy("mBandwidthRequests")
798 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
799
Erik Kline95ecfee2016-10-02 18:02:14 +0900800 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900801 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900802
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900803 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800804 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
805 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800806
Robert Greenwalt802c1102014-06-02 15:32:02 -0700807 /**
808 * Implements support for the legacy "one network per network type" model.
809 *
810 * We used to have a static array of NetworkStateTrackers, one for each
811 * network type, but that doesn't work any more now that we can have,
812 * for example, more that one wifi network. This class stores all the
813 * NetworkAgentInfo objects that support a given type, but the legacy
814 * API will only see the first one.
815 *
816 * It serves two main purposes:
817 *
818 * 1. Provide information about "the network for a given type" (since this
819 * API only supports one).
820 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
821 * the first network for a given type changes, or if the default network
822 * changes.
823 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900824 @VisibleForTesting
825 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900826
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900827 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900828 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900829
Robert Greenwalt802c1102014-06-02 15:32:02 -0700830 /**
831 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
832 * Each list holds references to all NetworkAgentInfos that are used to
833 * satisfy requests for that network type.
834 *
835 * This array is built out at startup such that an unsupported network
836 * doesn't get an ArrayList instance, making this a tristate:
837 * unsupported, supported but not active and active.
838 *
839 * The actual lists are populated when we scan the network types that
840 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900841 *
842 * Threading model:
843 * - addSupportedType() is only called in the constructor
844 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
845 * They are therefore not thread-safe with respect to each other.
846 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
847 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900848 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900849 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700850 */
Hugo Benichi389633f2016-06-21 09:48:07 +0900851 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900852 @NonNull
853 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700854
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900855 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
856 // an entry have no timer (equivalent to -1). Lazily loaded.
857 @NonNull
858 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
859
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900860 LegacyTypeTracker(@NonNull ConnectivityService service) {
861 mService = service;
862 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700863 }
864
Chiachang Wang3bc52762021-11-25 14:17:57 +0800865 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
866 // addressed.
867 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900868 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
869 final PackageManager pm = ctx.getPackageManager();
870 if (pm.hasSystemFeature(FEATURE_WIFI)) {
871 addSupportedType(TYPE_WIFI);
872 }
873 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
874 addSupportedType(TYPE_WIFI_P2P);
875 }
876 if (tm.isDataCapable()) {
877 // Telephony does not have granular support for these types: they are either all
878 // supported, or none is supported
879 addSupportedType(TYPE_MOBILE);
880 addSupportedType(TYPE_MOBILE_MMS);
881 addSupportedType(TYPE_MOBILE_SUPL);
882 addSupportedType(TYPE_MOBILE_DUN);
883 addSupportedType(TYPE_MOBILE_HIPRI);
884 addSupportedType(TYPE_MOBILE_FOTA);
885 addSupportedType(TYPE_MOBILE_IMS);
886 addSupportedType(TYPE_MOBILE_CBS);
887 addSupportedType(TYPE_MOBILE_IA);
888 addSupportedType(TYPE_MOBILE_EMERGENCY);
889 }
890 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
891 addSupportedType(TYPE_BLUETOOTH);
892 }
893 if (pm.hasSystemFeature(FEATURE_WATCH)) {
894 // TYPE_PROXY is only used on Wear
895 addSupportedType(TYPE_PROXY);
896 }
897 // Ethernet is often not specified in the configs, although many devices can use it via
898 // USB host adapters. Add it as long as the ethernet service is here.
899 if (ctx.getSystemService(Context.ETHERNET_SERVICE) != null) {
900 addSupportedType(TYPE_ETHERNET);
901 }
902
903 // Always add TYPE_VPN as a supported type
904 addSupportedType(TYPE_VPN);
905 }
906
907 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700908 if (mTypeLists[type] != null) {
909 throw new IllegalStateException(
910 "legacy list for type " + type + "already initialized");
911 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900912 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -0700913 }
914
Robert Greenwalt802c1102014-06-02 15:32:02 -0700915 public boolean isTypeSupported(int type) {
916 return isNetworkTypeValid(type) && mTypeLists[type] != null;
917 }
918
919 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +0900920 synchronized (mTypeLists) {
921 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
922 return mTypeLists[type].get(0);
923 }
Robert Greenwalt802c1102014-06-02 15:32:02 -0700924 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900925 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700926 }
927
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900928 public int getRestoreTimerForType(int type) {
929 synchronized (mTypeLists) {
930 if (mRestoreTimers == null) {
931 mRestoreTimers = loadRestoreTimers();
932 }
933 return mRestoreTimers.getOrDefault(type, -1);
934 }
935 }
936
937 private ArrayMap<Integer, Integer> loadRestoreTimers() {
938 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900939 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900940 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
941 for (final String config : configs) {
942 final String[] splits = TextUtils.split(config, ",");
943 if (splits.length != 2) {
944 logwtf("Invalid restore timer token count: " + config);
945 continue;
946 }
947 try {
948 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
949 } catch (NumberFormatException e) {
950 logwtf("Invalid restore timer number format: " + config, e);
951 }
952 }
953 return ret;
954 }
955
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -0700956 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +0900957 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900958 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +0900959 log("Sending " + state
960 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +0900961 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900962 }
963 }
964
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900965 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
966 // network type, to preserve previous behaviour.
967 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
968 if (vpnNai != mService.getLegacyLockdownNai()) return;
969
970 if (vpnNai.declaredUnderlyingNetworks == null
971 || vpnNai.declaredUnderlyingNetworks.length != 1) {
972 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
973 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
974 return;
975 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +0900976 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900977 vpnNai.declaredUnderlyingNetworks[0]);
978 if (underlyingNai == null) return;
979
980 final int type = underlyingNai.networkInfo.getType();
981 final DetailedState state = DetailedState.CONNECTED;
982 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
983 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
984 }
985
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900986 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -0700987 public void add(int type, NetworkAgentInfo nai) {
988 if (!isTypeSupported(type)) {
989 return; // Invalid network type.
990 }
991 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
992
993 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
994 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700995 return;
996 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900997 synchronized (mTypeLists) {
998 list.add(nai);
999 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001000
Chalard Jean5b409c72021-02-04 13:12:59 +09001001 // Send a broadcast if this is the first network of its type or if it's the default.
1002 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001003
1004 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1005 // to preserve previous behaviour.
1006 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001007 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001008 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1009 mService.sendLegacyNetworkBroadcast(nai, state, type);
1010 }
1011
1012 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1013 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001014 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001015 }
1016
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001017 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001018 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001019 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1020 if (list == null || list.isEmpty()) {
1021 return;
1022 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001023 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001024
Hugo Benichi389633f2016-06-21 09:48:07 +09001025 synchronized (mTypeLists) {
1026 if (!list.remove(nai)) {
1027 return;
1028 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001029 }
1030
Lorenzo Colitti49767722015-05-01 00:30:10 +09001031 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001032 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1033 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001034 }
1035
1036 if (!list.isEmpty() && wasFirstNetwork) {
1037 if (DBG) log("Other network available for type " + type +
1038 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001039 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001040 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001041 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001042 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001043 }
1044 }
1045
1046 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001047 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1048 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001049 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001050 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001051 }
1052 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001053
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001054 // send out another legacy broadcast - currently only used for suspend/unsuspend
1055 // toggle
1056 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001057 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001058 final DetailedState state = nai.networkInfo.getDetailedState();
1059 for (int type = 0; type < mTypeLists.length; type++) {
1060 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001061 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001062 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001063 if (isFirst || contains && isDefault) {
1064 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001065 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001066 }
1067 }
1068 }
1069
Robert Greenwalt94e22142014-07-30 16:31:24 -07001070 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001071 pw.println("mLegacyTypeTracker:");
1072 pw.increaseIndent();
1073 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001074 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001075 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001076 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001077 pw.println();
1078 pw.println("Current state:");
1079 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001080 synchronized (mTypeLists) {
1081 for (int type = 0; type < mTypeLists.length; type++) {
1082 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1083 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001084 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001085 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001086 }
1087 }
1088 pw.decreaseIndent();
1089 pw.decreaseIndent();
1090 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001091 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001092 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001093 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001094
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001095 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001096 /**
1097 * Helper class which parses out priority arguments and dumps sections according to their
1098 * priority. If priority arguments are omitted, function calls the legacy dump command.
1099 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001100 private class LocalPriorityDump {
1101 private static final String PRIORITY_ARG = "--dump-priority";
1102 private static final String PRIORITY_ARG_HIGH = "HIGH";
1103 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1104
1105 LocalPriorityDump() {}
1106
1107 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1108 doDump(fd, pw, new String[] {DIAG_ARG});
1109 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001110 }
1111
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001112 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1113 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001114 }
1115
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001116 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1117 if (args == null) {
1118 dumpNormal(fd, pw, args);
1119 return;
1120 }
1121
1122 String priority = null;
1123 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1124 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1125 argIndex++;
1126 priority = args[argIndex];
1127 }
1128 }
1129
1130 if (PRIORITY_ARG_HIGH.equals(priority)) {
1131 dumpHigh(fd, pw);
1132 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1133 dumpNormal(fd, pw, args);
1134 } else {
1135 // ConnectivityService publishes binder service using publishBinderService() with
1136 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001137 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1138 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001139 // TODO: Integrate into signal dump.
1140 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001141 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001142 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001143 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001144
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001145 /**
Daniel Brightf9e945b2020-06-15 16:10:01 -07001146 * Keeps track of the number of requests made under different uids.
1147 */
1148 public static class PerUidCounter {
1149 private final int mMaxCountPerUid;
1150
1151 // Map from UID to number of NetworkRequests that UID has filed.
James Mattis20a4a8b2021-03-28 17:41:09 -07001152 @VisibleForTesting
Daniel Brightf9e945b2020-06-15 16:10:01 -07001153 @GuardedBy("mUidToNetworkRequestCount")
James Mattis20a4a8b2021-03-28 17:41:09 -07001154 final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
Daniel Brightf9e945b2020-06-15 16:10:01 -07001155
1156 /**
1157 * Constructor
1158 *
1159 * @param maxCountPerUid the maximum count per uid allowed
1160 */
1161 public PerUidCounter(final int maxCountPerUid) {
1162 mMaxCountPerUid = maxCountPerUid;
1163 }
1164
1165 /**
1166 * Increments the request count of the given uid. Throws an exception if the number
1167 * of open requests for the uid exceeds the value of maxCounterPerUid which is the value
1168 * passed into the constructor. see: {@link #PerUidCounter(int)}.
1169 *
1170 * @throws ServiceSpecificException with
1171 * {@link ConnectivityManager.Errors.TOO_MANY_REQUESTS} if the number of requests for
1172 * the uid exceed the allowed number.
1173 *
1174 * @param uid the uid that the request was made under
1175 */
1176 public void incrementCountOrThrow(final int uid) {
1177 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001178 incrementCountOrThrow(uid, 1 /* numToIncrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001179 }
1180 }
1181
James Mattis20a4a8b2021-03-28 17:41:09 -07001182 private void incrementCountOrThrow(final int uid, final int numToIncrement) {
1183 final int newRequestCount =
1184 mUidToNetworkRequestCount.get(uid, 0) + numToIncrement;
Chalard Jean9473c982021-07-29 20:03:04 +09001185 if (newRequestCount >= mMaxCountPerUid
1186 // HACK : the system server is allowed to go over the request count limit
1187 // when it is creating requests on behalf of another app (but not itself,
1188 // so it can still detect its own request leaks). This only happens in the
1189 // per-app API flows in which case the old requests for that particular
1190 // UID will be removed soon.
1191 // TODO : instead of this hack, addPerAppDefaultNetworkRequests and other
1192 // users of transact() should unregister the requests to decrease the count
1193 // before they increase it again by creating a new NRI. Then remove the
1194 // transact() method.
1195 && (Process.myUid() == uid || Process.myUid() != Binder.getCallingUid())) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001196 throw new ServiceSpecificException(
Chalard Jean9473c982021-07-29 20:03:04 +09001197 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
1198 "Uid " + uid + " exceeded its allotted requests limit");
James Mattis20a4a8b2021-03-28 17:41:09 -07001199 }
1200 mUidToNetworkRequestCount.put(uid, newRequestCount);
1201 }
1202
Daniel Brightf9e945b2020-06-15 16:10:01 -07001203 /**
1204 * Decrements the request count of the given uid.
1205 *
1206 * @param uid the uid that the request was made under
1207 */
1208 public void decrementCount(final int uid) {
1209 synchronized (mUidToNetworkRequestCount) {
James Mattis20a4a8b2021-03-28 17:41:09 -07001210 decrementCount(uid, 1 /* numToDecrement */);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001211 }
1212 }
James Mattis20a4a8b2021-03-28 17:41:09 -07001213
1214 private void decrementCount(final int uid, final int numToDecrement) {
1215 final int newRequestCount =
1216 mUidToNetworkRequestCount.get(uid, 0) - numToDecrement;
1217 if (newRequestCount < 0) {
1218 logwtf("BUG: too small request count " + newRequestCount + " for UID " + uid);
1219 } else if (newRequestCount == 0) {
1220 mUidToNetworkRequestCount.delete(uid);
1221 } else {
1222 mUidToNetworkRequestCount.put(uid, newRequestCount);
1223 }
1224 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07001225 }
1226
1227 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001228 * Dependencies of ConnectivityService, for injection in tests.
1229 */
1230 @VisibleForTesting
1231 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001232 public int getCallingUid() {
1233 return Binder.getCallingUid();
1234 }
1235
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001236 /**
1237 * Get system properties to use in ConnectivityService.
1238 */
1239 public MockableSystemProperties getSystemProperties() {
1240 return new MockableSystemProperties();
1241 }
1242
1243 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001244 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1245 */
1246 public ConnectivityResources getResources(@NonNull Context ctx) {
1247 return new ConnectivityResources(ctx);
1248 }
1249
1250 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001251 * Create a HandlerThread to use in ConnectivityService.
1252 */
1253 public HandlerThread makeHandlerThread() {
1254 return new HandlerThread("ConnectivityServiceThread");
1255 }
1256
1257 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001258 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001259 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001260 public NetworkStackClientBase getNetworkStack() {
1261 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001262 }
1263
1264 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001265 * @see ProxyTracker
1266 */
1267 public ProxyTracker makeProxyTracker(@NonNull Context context,
1268 @NonNull Handler connServiceHandler) {
1269 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1270 }
1271
1272 /**
1273 * @see NetIdManager
1274 */
1275 public NetIdManager makeNetIdManager() {
1276 return new NetIdManager();
1277 }
1278
1279 /**
1280 * @see NetworkUtils#queryUserAccess(int, int)
1281 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001282 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1283 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001284 }
1285
1286 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001287 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1288 * requires CAP_NET_ADMIN, which the unit tests do not have.
1289 */
1290 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1291 InetSocketAddress remote) {
1292 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1293 }
1294
1295 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001296 * @see MultinetworkPolicyTracker
1297 */
1298 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1299 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1300 return new MultinetworkPolicyTracker(c, h, r);
1301 }
1302
Aaron Huang330a4c02020-10-27 03:36:19 +08001303 /**
1304 * @see BatteryStatsManager
1305 */
1306 public void reportNetworkInterfaceForTransports(Context context, String iface,
1307 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001308 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001309 context.getSystemService(BatteryStatsManager.class);
1310 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1311 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001312
1313 public boolean getCellular464XlatEnabled() {
1314 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1315 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001316
1317 /**
1318 * @see PendingIntent#intentFilterEquals
1319 */
1320 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1321 return a.intentFilterEquals(b);
1322 }
1323
1324 /**
1325 * @see LocationPermissionChecker
1326 */
1327 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1328 return new LocationPermissionChecker(context);
1329 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001330
1331 /**
1332 * @see DeviceConfigUtils#isFeatureEnabled
1333 */
1334 public boolean isFeatureEnabled(Context context, String name, boolean defaultEnabled) {
1335 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, name,
1336 TETHERING_MODULE_NAME, defaultEnabled);
1337 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001338 }
1339
junyulaie7c7d2a2021-01-26 15:29:15 +08001340 public ConnectivityService(Context context) {
1341 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001342 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1343 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001344 }
1345
1346 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001347 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1348 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001349 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001350
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001351 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001352 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001353 mSystemProperties = mDeps.getSystemProperties();
1354 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001355 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001356 mResources = deps.getResources(mContext);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001357 mNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_UID);
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09001358 mSystemNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001359
Hugo Benichi208c0102016-07-28 17:53:06 +09001360 mMetricsLog = logger;
Chalard Jean96a4f4b2019-12-10 22:16:53 +09001361 mNetworkRanker = new NetworkRanker();
James Mattis45d81842021-01-10 14:24:24 -08001362 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1363 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001364 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001365 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001366 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001367 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1368 mDefaultNetworkRequests.add(mDefaultRequest);
1369 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001370
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001371 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001372 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001373
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001374 // The default WiFi request is a background request so that apps using WiFi are
1375 // migrated to a better network (typically ethernet) when one comes up, instead
1376 // of staying on WiFi forever.
1377 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1378 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1379
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001380 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1381 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1382 NetworkRequest.Type.BACKGROUND_REQUEST);
1383
Chalard Jean0702f982021-09-16 21:50:07 +09001384 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1385 // TODO: Consider making the timer customizable.
1386 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1387 mCellularRadioTimesharingCapable =
1388 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1389
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001390 mHandlerThread = mDeps.makeHandlerThread();
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001391 mHandlerThread.start();
1392 mHandler = new InternalHandler(mHandlerThread.getLooper());
1393 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001394 mConnectivityDiagnosticsHandler =
1395 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001396
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001397 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001398 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001399
junyulaie7c7d2a2021-01-26 15:29:15 +08001400 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001401 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001402 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001403 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001404
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001405 mNetd = netd;
Wink Saville32506bc2013-06-29 21:10:57 -07001406 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001407 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001408 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001409
Sudheer Shanka9967d462021-03-18 19:09:25 +00001410 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001411 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1412 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001413 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001414
1415 final PowerManager powerManager = (PowerManager) context.getSystemService(
1416 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001417 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001418 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001419
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001420 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1421 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001422 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001423 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001424 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001425 mProtectedNetworks.add(p);
1426 } else {
1427 if (DBG) loge("Ignoring protectedNetwork " + p);
1428 }
1429 }
1430
soma, kawata29444ae2019-05-23 09:30:40 +09001431 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1432
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001433 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -07001434
James Mattis02220e22021-03-13 19:27:21 -08001435 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001436 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001437 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001438 final IntentFilter userIntentFilter = new IntentFilter();
1439 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1440 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1441 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1442 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001443
James Mattis02220e22021-03-13 19:27:21 -08001444 // Listen to package add/removes for netd
1445 final IntentFilter packageIntentFilter = new IntentFilter();
1446 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1447 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1448 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1449 packageIntentFilter.addDataScheme("package");
1450 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001451 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001452
lucaslind5c2d072021-02-20 18:59:47 +08001453 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001454
lucaslin66f44212021-02-23 01:12:55 +08001455 mNetdCallback = new NetdCallback();
1456 try {
1457 mNetd.registerUnsolicitedEventListener(mNetdCallback);
1458 } catch (RemoteException | ServiceSpecificException e) {
1459 loge("Error registering event listener :" + e);
1460 }
1461
Erik Kline05f2b402015-04-30 12:58:40 +09001462 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1463 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001464
junyulai7e06ad42019-03-04 22:45:36 +08001465 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001466 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001467 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001468
1469 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001470 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001471 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1472 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001473 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001474 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1475 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001476
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001477 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001478 mContext, mHandler, () -> updateAvoidBadWifi());
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001479 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001480
Chiachang Wangc1215d32020-10-20 15:38:58 +08001481 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001482 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001483
Chalard Jean28018572020-12-21 18:36:52 +09001484 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1485 // request that doesn't allow fallback to the default network. It should never be visible
1486 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1487 // arguments like the handler or the DnsResolver.
1488 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001489 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001490 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001491 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001492 new LinkProperties(), new NetworkCapabilities(),
1493 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001494 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1495 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001496
1497 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001498 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1499 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1500 // Even if it could, running on S would at least require mocking out the BPF map,
1501 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1502 // the bpf syscall. http://aosp/1907693
1503 if (SdkLevel.isAtLeastT()) {
1504 mDscpPolicyTracker = new DscpPolicyTracker();
1505 }
Tyler Wear72388212021-09-09 14:49:02 -07001506 } catch (ErrnoException e) {
1507 loge("Unable to create DscpPolicyTracker");
1508 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001509 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001510
Chalard Jean46adcf32018-04-18 20:18:38 +09001511 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001512 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1513 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001514 }
1515
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001516 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1517 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001518 final NetworkCapabilities netCap = new NetworkCapabilities();
1519 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001520 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001521 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001522 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001523 return netCap;
1524 }
1525
James Mattis45d81842021-01-10 14:24:24 -08001526 private NetworkRequest createDefaultRequest() {
1527 return createDefaultInternetRequestForTransport(
1528 TYPE_NONE, NetworkRequest.Type.REQUEST);
1529 }
1530
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001531 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001532 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001533 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001534 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001535 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001536 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001537 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001538 netCap.addTransportType(transportType);
1539 }
James Mattis45d81842021-01-10 14:24:24 -08001540 return createNetworkRequest(type, netCap);
1541 }
1542
1543 private NetworkRequest createNetworkRequest(
1544 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001545 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001546 }
1547
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001548 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1549 NetworkRequest.Type type) {
1550 final NetworkCapabilities netCap = new NetworkCapabilities();
1551 netCap.clearAll();
1552 netCap.addCapability(capability);
1553 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1554 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1555 }
1556
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001557 // Used only for testing.
1558 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001559 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001560 // changing ContentResolver to make registerContentObserver non-final).
1561 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1562 // by subclassing SettingsObserver.
1563 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001564 void updateAlwaysOnNetworks() {
1565 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001566 }
1567
Erik Kline9a62f012018-03-21 07:18:33 -07001568 // See FakeSettingsProvider comment above.
1569 @VisibleForTesting
1570 void updatePrivateDnsSettings() {
1571 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1572 }
1573
paulhu51f77dc2021-06-07 02:34:20 +00001574 @VisibleForTesting
1575 void updateMobileDataPreferredUids() {
1576 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1577 }
1578
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09001579 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, int id) {
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001580 final boolean enable = mContext.getResources().getBoolean(id);
1581 handleAlwaysOnNetworkRequest(networkRequest, enable);
1582 }
1583
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001584 private void handleAlwaysOnNetworkRequest(
1585 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001586 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001587 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001588 handleAlwaysOnNetworkRequest(networkRequest, enable);
1589 }
1590
1591 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001592 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001593 if (enable == isEnabled) {
1594 return; // Nothing to do.
1595 }
1596
1597 if (enable) {
1598 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001599 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001600 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001601 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001602 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001603 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1604 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001605 }
1606 }
1607
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001608 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001609 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1610 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1611 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1612 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001613 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1614 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001615 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001616 }
1617
paulhu51f77dc2021-06-07 02:34:20 +00001618 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001619 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001620 private void registerSettingsCallbacks() {
1621 // Watch for global HTTP proxy changes.
1622 mSettingsObserver.observe(
1623 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1624 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1625
1626 // Watch for whether or not to keep mobile data always on.
1627 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001628 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001629 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1630
1631 // Watch for whether or not to keep wifi always on.
1632 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001633 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001634 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001635
1636 // Watch for mobile data preferred uids changes.
1637 mSettingsObserver.observe(
1638 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1639 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001640 }
1641
Erik Kline31b4a9e2018-01-11 21:07:29 +09001642 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001643 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1644 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001645 }
1646 }
1647
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001648 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001649 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1650 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001651 return mNextNetworkRequestId++;
1652 }
1653
junyulai74f9a8b2018-06-13 15:00:37 +08001654 @VisibleForTesting
1655 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001656 if (network == null) {
1657 return null;
1658 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001659 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001660 }
1661
1662 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001663 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001664 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001665 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001666 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001667
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001668 // TODO: determine what to do when more than one VPN applies to |uid|.
1669 private NetworkAgentInfo getVpnForUid(int uid) {
1670 synchronized (mNetworkForNetId) {
1671 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1672 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
1673 if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) {
1674 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001675 }
1676 }
1677 }
1678 return null;
1679 }
1680
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001681 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001682 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001683 final NetworkAgentInfo nai = getVpnForUid(uid);
1684 if (nai != null) return nai.declaredUnderlyingNetworks;
1685 return null;
1686 }
1687
Lorenzo Colittia7574052021-01-19 01:33:05 +09001688 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001689 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001690
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001691 final Network[] networks = getVpnUnderlyingNetworks(uid);
1692 if (networks != null) {
1693 // getUnderlyingNetworks() returns:
1694 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1695 // empty array => the VPN explicitly said "no default network".
1696 // non-empty array => the VPN specified one or more default networks; we use the
1697 // first one.
1698 if (networks.length > 0) {
1699 nai = getNetworkAgentInfoForNetwork(networks[0]);
1700 } else {
1701 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001702 }
1703 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001704 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001705 }
1706
1707 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001708 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001709 */
paulhu7aeba372020-12-30 00:42:19 +08001710 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1711 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001712 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001713 if (ignoreBlocked) {
1714 return false;
1715 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001716 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001717 final long ident = Binder.clearCallingIdentity();
1718 try {
1719 final boolean metered = nc == null ? true : nc.isMetered();
1720 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1721 } finally {
1722 Binder.restoreCallingIdentity(ident);
1723 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001724 }
1725
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001726 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001727 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1728 return;
1729 }
Hugo Benichi47011212017-03-30 10:46:05 +09001730 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001731 synchronized (mBlockedAppUids) {
1732 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001733 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001734 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001735 blocked = false;
1736 } else {
1737 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001738 }
1739 }
Hugo Benichi47011212017-03-30 10:46:05 +09001740 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1741 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1742 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001743 }
1744
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001745 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001746 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1747 return;
1748 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001749 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001750 final int requestId = nri.getActiveRequest() != null
1751 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001752 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001753 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001754 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001755 }
1756
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001757 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001758 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001759 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001760 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001761 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001762 @NonNull
1763 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1764 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001765 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1766 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1767 // but only exists if an app asks about them or requests them. Ensure the requesting app
1768 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001769 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001770 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1771 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1772 null /* extraInfo */);
1773 }
1774 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001775 return filtered;
1776 }
1777
1778 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1779 boolean ignoreBlocked) {
1780 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1781 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001782 }
1783
1784 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001785 * Return NetworkInfo for the active (i.e., connected) network interface.
1786 * It is assumed that at most one network is active at a time. If more
1787 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001788 * @return the info for the active network, or {@code null} if none is
1789 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001790 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001791 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001792 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001793 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001794 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001795 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1796 if (nai == null) return null;
1797 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1798 maybeLogBlockedNetworkInfo(networkInfo, uid);
1799 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001800 }
1801
Paul Jensen1f567382015-02-13 14:18:39 -05001802 @Override
1803 public Network getActiveNetwork() {
1804 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001805 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00001806 }
1807
1808 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001809 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001810 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001811 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001812 }
1813
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001814 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001815 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1816 if (vpnNai != null) {
1817 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1818 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1819 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09001820 }
Paul Jensen1f567382015-02-13 14:18:39 -05001821 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001822
James Mattis2516da32021-01-31 17:06:19 -08001823 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001824 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1825 ignoreBlocked)) {
1826 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001827 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001828 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05001829 }
1830
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001831 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001832 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhudf23d662021-01-25 18:53:17 +08001833 PermissionUtils.enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001834 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1835 if (nai == null) return null;
1836 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001837 }
1838
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001839 /** Returns a NetworkInfo object for a network that doesn't exist. */
1840 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1841 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1842 getNetworkTypeName(networkType), "" /* subtypeName */);
1843 info.setIsAvailable(true);
1844 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1845 // background data is restricted.
1846 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1847 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1848 ? DetailedState.BLOCKED
1849 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001850 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1851 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001852 return info;
1853 }
1854
Lorenzo Colittia7574052021-01-19 01:33:05 +09001855 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001856 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1857 return null;
1858 }
1859 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001860 if (nai == null) {
1861 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001862 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001863 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1864 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001865 }
1866
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001867 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001868 public NetworkInfo getNetworkInfo(int networkType) {
1869 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001870 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001871 if (getVpnUnderlyingNetworks(uid) != null) {
1872 // A VPN is active, so we may need to return one of its underlying networks. This
1873 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09001874 // getNetworkAgentInfoForUid.
1875 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1876 if (nai == null) return null;
1877 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1878 if (networkInfo.getType() == networkType) {
1879 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001880 }
1881 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001882 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001883 }
1884
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001885 @Override
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001886 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001887 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001888 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001889 if (nai == null) return null;
1890 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001891 }
1892
1893 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001894 public NetworkInfo[] getAllNetworkInfo() {
1895 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08001896 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04001897 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1898 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001899 NetworkInfo info = getNetworkInfo(networkType);
1900 if (info != null) {
1901 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001902 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001903 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001904 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001905 }
1906
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001907 @Override
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001908 public Network getNetworkForType(int networkType) {
1909 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001910 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1911 return null;
1912 }
1913 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1914 if (nai == null) {
1915 return null;
1916 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001917 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001918 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
1919 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001920 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001921 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07001922 }
1923
1924 @Override
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001925 public Network[] getAllNetworks() {
1926 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001927 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04001928 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001929 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04001930 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001931 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04001932 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001933 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001934 }
1935
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001936 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08001937 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08001938 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001939 // The basic principle is: if an app's traffic could possibly go over a
1940 // network, without the app doing anything multinetwork-specific,
1941 // (hence, by "default"), then include that network's capabilities in
1942 // the array.
1943 //
1944 // In the normal case, app traffic only goes over the system's default
1945 // network connection, so that's the only network returned.
1946 //
1947 // With a VPN in force, some app traffic may go into the VPN, and thus
1948 // over whatever underlying networks the VPN specifies, while other app
1949 // traffic may go over the system default network (e.g.: a split-tunnel
1950 // VPN, or an app disallowed by the VPN), so the set of networks
1951 // returned includes the VPN's underlying networks and the system
1952 // default.
1953 enforceAccessPermission();
1954
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001955 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001956
James Mattis2516da32021-01-31 17:06:19 -08001957 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
1958 if (!nri.isBeingSatisfied()) {
1959 continue;
1960 }
1961 final NetworkAgentInfo nai = nri.getSatisfier();
1962 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
1963 if (null != nc
1964 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
1965 && !result.containsKey(nai.network)) {
1966 result.put(
1967 nai.network,
1968 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08001969 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08001970 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
1971 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08001972 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001973 }
1974
Lorenzo Colittidfab3032020-12-15 00:49:41 +09001975 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09001976 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08001977 if (null != networks) {
1978 for (final Network network : networks) {
1979 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
1980 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08001981 result.put(
1982 network,
1983 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08001984 nc,
1985 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08001986 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08001987 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09001988 }
1989 }
1990 }
1991
1992 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1993 out = result.values().toArray(out);
1994 return out;
1995 }
1996
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07001997 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001998 public boolean isNetworkSupported(int networkType) {
1999 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002000 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002001 }
2002
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002003 /**
2004 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002005 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002006 * @return the ip properties for the active network, or {@code null} if
2007 * none is active
2008 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002009 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002010 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002011 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002012 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002013 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2014 if (nai == null) return null;
2015 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002016 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002017 }
2018
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002019 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002020 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002021 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002022 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002023 final LinkProperties lp = getLinkProperties(nai);
2024 if (lp == null) return null;
2025 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002026 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002027 }
2028
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002029 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002030 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002031 public LinkProperties getLinkProperties(Network network) {
2032 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002033 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2034 if (lp == null) return null;
2035 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002036 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002037 }
2038
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002039 @Nullable
2040 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002041 if (nai == null) {
2042 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002043 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002044 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002045 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002046 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002047 }
2048
Qingxi Lib2748102020-01-08 12:51:49 -08002049 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2050 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2051 }
2052
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002053 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002054 if (nai == null) return null;
2055 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002056 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002057 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002058 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002059 }
2060
2061 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002062 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2063 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002064 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002065 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002066 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002067 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002068 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002069 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002070 }
2071
Qingxi Libb8da982020-01-17 17:54:27 -08002072 @VisibleForTesting
2073 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002074 NetworkCapabilities nc, int callerPid, int callerUid) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002075 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002076 if (!checkSettingsPermission(callerPid, callerUid)) {
2077 newNc.setUids(null);
2078 newNc.setSSID(null);
lucaslin6adf5ac2021-10-19 15:04:56 +08002079 newNc.setUnderlyingNetworks(null);
Chalard Jean46adcf32018-04-18 20:18:38 +09002080 }
Etan Cohen107ae952018-12-30 17:59:59 -08002081 if (newNc.getNetworkSpecifier() != null) {
2082 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2083 }
Cody Kesting5ab1f552020-03-16 18:15:28 -07002084 newNc.setAdministratorUids(new int[0]);
Benedict Wong53de25f2021-03-24 14:01:51 -07002085 if (!checkAnyPermissionOf(
2086 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
junyulai2217bec2021-04-14 23:33:31 +08002087 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002088 }
Qingxi Libb8da982020-01-17 17:54:27 -08002089
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002090 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002091 }
2092
Roshan Pius98f59ec2021-02-23 08:47:39 -08002093 /**
2094 * Wrapper used to cache the permission check results performed for the corresponding
2095 * app. This avoid performing multiple permission checks for different fields in
2096 * NetworkCapabilities.
2097 * Note: This wrapper does not support any sort of invalidation and thus must not be
2098 * persistent or long-lived. It may only be used for the time necessary to
2099 * compute the redactions required by one particular NetworkCallback or
2100 * synchronous call.
2101 */
2102 private class RedactionPermissionChecker {
2103 private final int mCallingPid;
2104 private final int mCallingUid;
2105 @NonNull private final String mCallingPackageName;
2106 @Nullable private final String mCallingAttributionTag;
2107
2108 private Boolean mHasLocationPermission = null;
2109 private Boolean mHasLocalMacAddressPermission = null;
2110 private Boolean mHasSettingsPermission = null;
2111
2112 RedactionPermissionChecker(int callingPid, int callingUid,
2113 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2114 mCallingPid = callingPid;
2115 mCallingUid = callingUid;
2116 mCallingPackageName = callingPackageName;
2117 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002118 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002119
2120 private boolean hasLocationPermissionInternal() {
2121 final long token = Binder.clearCallingIdentity();
2122 try {
2123 return mLocationPermissionChecker.checkLocationPermission(
2124 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2125 null /* message */);
2126 } finally {
2127 Binder.restoreCallingIdentity(token);
2128 }
2129 }
2130
2131 /**
2132 * Returns whether the app holds location permission or not (might return cached result
2133 * if the permission was already checked before).
2134 */
2135 public boolean hasLocationPermission() {
2136 if (mHasLocationPermission == null) {
2137 // If there is no cached result, perform the check now.
2138 mHasLocationPermission = hasLocationPermissionInternal();
2139 }
2140 return mHasLocationPermission;
2141 }
2142
2143 /**
2144 * Returns whether the app holds local mac address permission or not (might return cached
2145 * result if the permission was already checked before).
2146 */
2147 public boolean hasLocalMacAddressPermission() {
2148 if (mHasLocalMacAddressPermission == null) {
2149 // If there is no cached result, perform the check now.
2150 mHasLocalMacAddressPermission =
2151 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2152 }
2153 return mHasLocalMacAddressPermission;
2154 }
2155
2156 /**
2157 * Returns whether the app holds settings permission or not (might return cached
2158 * result if the permission was already checked before).
2159 */
2160 public boolean hasSettingsPermission() {
2161 if (mHasSettingsPermission == null) {
2162 // If there is no cached result, perform the check now.
2163 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2164 }
2165 return mHasSettingsPermission;
2166 }
2167 }
2168
2169 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2170 @NetworkCapabilities.NetCapability long redaction) {
2171 return (redactions & redaction) != 0;
2172 }
2173
2174 /**
2175 * Use the provided |applicableRedactions| to check the receiving app's
2176 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2177 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2178 * before being sent to the corresponding app.
2179 */
2180 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2181 @NetworkCapabilities.RedactionType long applicableRedactions,
2182 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2183 boolean includeLocationSensitiveInfo) {
2184 long redactions = applicableRedactions;
2185 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2186 if (includeLocationSensitiveInfo
2187 && redactionPermissionChecker.hasLocationPermission()) {
2188 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2189 }
2190 }
2191 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2192 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2193 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2194 }
2195 }
2196 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2197 if (redactionPermissionChecker.hasSettingsPermission()) {
2198 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2199 }
2200 }
2201 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002202 }
2203
Qingxi Lib2748102020-01-08 12:51:49 -08002204 @VisibleForTesting
2205 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002206 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002207 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002208 int callingPid, int callingUid, @NonNull String callingPkgName,
2209 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002210 if (nc == null) {
2211 return null;
2212 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002213 // Avoid doing location permission check if the transport info has no location sensitive
2214 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002215 final RedactionPermissionChecker redactionPermissionChecker =
2216 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2217 callingAttributionTag);
2218 final long redactions = retrieveRequiredRedactions(
2219 nc.getApplicableRedactions(), redactionPermissionChecker,
2220 includeLocationSensitiveInfo);
2221 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002222 // Reset owner uid if not destined for the owner app.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002223 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002224 newNc.setOwnerUid(INVALID_UID);
2225 return newNc;
2226 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002227 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2228 if (nc.hasTransport(TRANSPORT_VPN)) {
2229 // Owner UIDs already checked above. No need to re-check.
2230 return newNc;
2231 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002232 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2233 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002234 // compatibility for older apps.
2235 if (!includeLocationSensitiveInfo
2236 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002237 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002238 newNc.setOwnerUid(INVALID_UID);
2239 return newNc;
2240 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002241 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002242 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002243 newNc.setOwnerUid(INVALID_UID);
2244 }
Qingxi Lib2748102020-01-08 12:51:49 -08002245 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002246 }
2247
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002248 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2249 LinkProperties lp, int callerPid, int callerUid) {
2250 if (lp == null) return new LinkProperties();
2251
2252 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2253 final boolean needsSanitization =
2254 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2255 if (!needsSanitization) {
2256 return new LinkProperties(lp);
2257 }
2258
2259 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002260 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002261 }
2262
2263 final LinkProperties newLp = new LinkProperties(lp);
2264 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2265 // object gets parceled.
2266 newLp.setCaptivePortalApiUrl(null);
2267 newLp.setCaptivePortalData(null);
2268 return newLp;
2269 }
2270
Roshan Pius08c94fb2020-01-16 12:17:17 -08002271 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2272 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002273 // There is no need to track the effective UID of the request here. If the caller
2274 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002275 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002276 // Unprivileged apps can only pass in null or their own UID.
2277 if (nc.getUids() == null) {
2278 // If the caller passes in null, the callback will also match networks that do not
2279 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2280 // In this case, redact everything in the request immediately. This ensures that the
2281 // app is not able to get any redacted information by filing an unredacted request
2282 // and observing whether the request matches something.
2283 if (nc.getNetworkSpecifier() != null) {
2284 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2285 }
2286 } else {
2287 nc.setSingleUid(callerUid);
2288 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002289 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002290 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002291 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002292
2293 // Clear owner UID; this can never come from an app.
2294 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002295 }
2296
Chalard Jean38354d12018-03-20 19:13:57 +09002297 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002298 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002299 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2300 }
2301 }
2302
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002303 @Override
2304 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2305 enforceAccessPermission();
2306 final int callerUid = Binder.getCallingUid();
2307 final long token = Binder.clearCallingIdentity();
2308 try {
2309 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2310 } finally {
2311 Binder.restoreCallingIdentity(token);
2312 }
2313 }
2314
junyulaiebd15162021-03-03 12:09:05 +08002315 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002316 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002317 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002318 // This contains IMSI details, so make sure the caller is privileged.
paulhudf23d662021-01-25 18:53:17 +08002319 PermissionUtils.enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002320
Serik Beketayev05130302021-01-15 16:47:25 -08002321 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002322 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002323 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2324 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002325 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002326 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002327 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002328 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2329 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002330 }
2331 }
2332 return result.toArray(new NetworkState[result.size()]);
2333 }
2334
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002335 @Override
junyulaiebd15162021-03-03 12:09:05 +08002336 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002337 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002338 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002339 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002340
2341 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2342 for (Network network : getAllNetworks()) {
2343 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Junyu Laiddecb662021-08-17 08:44:36 +00002344 if (nai != null && nai.everConnected) {
junyulaiebd15162021-03-03 12:09:05 +08002345 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2346 // NetworkCapabilities, which may contain UIDs of apps to which the
2347 // network applies. Should the UIDs be cleared so as not to leak or
2348 // interfere ?
2349 result.add(nai.getNetworkStateSnapshot());
2350 }
2351 }
2352 return result;
2353 }
2354
2355 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002356 public boolean isActiveNetworkMetered() {
2357 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002358
Qingxi Lib2748102020-01-08 12:51:49 -08002359 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002360 if (caps != null) {
2361 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2362 } else {
2363 // Always return the most conservative value
2364 return true;
2365 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002366 }
2367
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002368 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002369 * Ensures that the system cannot call a particular method.
2370 */
2371 private boolean disallowedBecauseSystemCaller() {
2372 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002373 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2374 // for devices launched with Q and above. However, existing devices upgrading to Q and
2375 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002376 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002377 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002378 log("This method exists only for app backwards compatibility"
2379 + " and must not be called by system services.");
2380 return true;
2381 }
2382 return false;
2383 }
2384
paulhub2c28682021-08-18 18:35:54 +08002385 private int getAppUid(final String app, final UserHandle user) {
2386 final PackageManager pm =
2387 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2388 final long token = Binder.clearCallingIdentity();
2389 try {
2390 return pm.getPackageUid(app, 0 /* flags */);
2391 } catch (PackageManager.NameNotFoundException e) {
2392 return -1;
2393 } finally {
2394 Binder.restoreCallingIdentity(token);
2395 }
2396 }
2397
2398 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2399 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2400 if (getAppUid(packageName, user) != callingUid) {
2401 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2402 }
2403 }
2404
Lorenzo Colitti23862912018-09-28 11:31:55 +09002405 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002406 * Ensure that a network route exists to deliver traffic to the specified
2407 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002408 * @param networkType the type of the network over which traffic to the
2409 * specified host is to be routed
2410 * @param hostAddress the IP address of the host to which the route is
2411 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002412 * @return {@code true} on success, {@code false} on failure
2413 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002414 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002415 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2416 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002417 if (disallowedBecauseSystemCaller()) {
2418 return false;
2419 }
paulhub2c28682021-08-18 18:35:54 +08002420 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002421 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002422 if (mProtectedNetworks.contains(networkType)) {
paulhu8e96a752019-08-12 16:25:11 +08002423 enforceConnectivityRestrictedNetworksPermission();
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002424 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002425
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002426 InetAddress addr;
2427 try {
2428 addr = InetAddress.getByAddress(hostAddress);
2429 } catch (UnknownHostException e) {
2430 if (DBG) log("requestRouteToHostAddress got " + e.toString());
2431 return false;
2432 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002433
The Android Open Source Project28527d22009-03-03 19:31:44 -08002434 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002435 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002436 return false;
2437 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002438
2439 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2440 if (nai == null) {
2441 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
2442 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2443 } else {
2444 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2445 }
2446 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002447 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002448
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002449 DetailedState netState;
2450 synchronized (nai) {
2451 netState = nai.networkInfo.getDetailedState();
2452 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002453
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002454 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002455 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002456 log("requestRouteToHostAddress on down network "
2457 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002458 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002459 }
2460 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002461 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002462
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002463 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002464 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002465 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002466 LinkProperties lp;
2467 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002468 synchronized (nai) {
2469 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002470 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002471 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002472 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002473 if (DBG) {
2474 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2475 }
Wink Saville32506bc2013-06-29 21:10:57 -07002476 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002477 } finally {
2478 Binder.restoreCallingIdentity(token);
2479 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002480 }
2481
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002482 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002483 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002484 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002485 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002486 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002487 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002488 if (bestRoute.getGateway().equals(addr)) {
2489 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002490 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002491 } else {
2492 // if we will connect to this through another route, add a direct route
2493 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002494 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002495 }
2496 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002497 if (DBG) log("Adding legacy route " + bestRoute +
2498 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002499
2500 final String dst = bestRoute.getDestinationLinkAddress().toString();
2501 final String nextHop = bestRoute.hasGateway()
2502 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002503 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002504 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2505 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002506 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002507 return false;
2508 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002509 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002510 }
2511
paulhu7c0a2e62021-01-08 00:51:49 +08002512 class DnsResolverUnsolicitedEventCallback extends
2513 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002514 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002515 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002516 try {
2517 mHandler.sendMessage(mHandler.obtainMessage(
2518 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002519 new PrivateDnsValidationUpdate(event.netId,
2520 InetAddresses.parseNumericAddress(event.ipAddress),
2521 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002522 } catch (IllegalArgumentException e) {
2523 loge("Error parsing ip address in validation event");
2524 }
2525 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002526
2527 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002528 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2529 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002530 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2531 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2532 // event callback for certain nai. e.g. cellular. Register here to pass to
2533 // NetworkMonitor instead.
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002534 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allow one
2535 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2536 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002537 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002538 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002539 }
2540 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002541
2542 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002543 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2544 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2545 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002546 }
dalyk1720e542018-03-05 12:42:22 -05002547
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002548 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002549 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002550 return this.VERSION;
2551 }
2552
2553 @Override
2554 public String getInterfaceHash() {
2555 return this.HASH;
2556 }
paulhu7c0a2e62021-01-08 00:51:49 +08002557 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002558
2559 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002560 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2561 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002562
paulhu7c0a2e62021-01-08 00:51:49 +08002563 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002564 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002565 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002566 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002567 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002568 }
2569 }
2570
Sudheer Shanka9967d462021-03-18 19:09:25 +00002571 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002572 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002573 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002574 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2575 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002576 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002577 };
2578
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002579 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002580 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002581 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002582 }
2583
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002584 private boolean checkAnyPermissionOf(String... permissions) {
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002585 for (String permission : permissions) {
2586 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002587 return true;
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002588 }
2589 }
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002590 return false;
2591 }
2592
paulhu1a407652019-03-22 16:35:06 +08002593 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2594 for (String permission : permissions) {
2595 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2596 return true;
2597 }
2598 }
2599 return false;
2600 }
2601
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002602 private void enforceAnyPermissionOf(String... permissions) {
2603 if (!checkAnyPermissionOf(permissions)) {
2604 throw new SecurityException("Requires one of the following permissions: "
2605 + String.join(", ", permissions) + ".");
2606 }
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002607 }
2608
Paul Jensen83f5d572014-08-29 09:54:01 -04002609 private void enforceInternetPermission() {
2610 mContext.enforceCallingOrSelfPermission(
2611 android.Manifest.permission.INTERNET,
2612 "ConnectivityService");
2613 }
2614
The Android Open Source Project28527d22009-03-03 19:31:44 -08002615 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002616 mContext.enforceCallingOrSelfPermission(
2617 android.Manifest.permission.ACCESS_NETWORK_STATE,
2618 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002619 }
2620
paulhua6ee2122021-02-22 15:40:43 +08002621 /**
2622 * Performs a strict and comprehensive check of whether a calling package is allowed to
2623 * change the state of network, as the condition differs for pre-M, M+, and
2624 * privileged/preinstalled apps. The caller is expected to have either the
2625 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2626 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2627 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2628 * permission and cannot be revoked. See http://b/23597341
2629 *
2630 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2631 * of this app will be updated to the current time.
2632 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002633 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002634 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2635 == PackageManager.PERMISSION_GRANTED) {
2636 return;
2637 }
2638
2639 if (callingPkg == null) {
2640 throw new SecurityException("Calling package name is null.");
2641 }
2642
2643 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2644 final int uid = mDeps.getCallingUid();
2645 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2646 callingPkg, callingAttributionTag, null /* message */);
2647
2648 if (mode == AppOpsManager.MODE_ALLOWED) {
2649 return;
2650 }
2651
2652 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2653 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2654 return;
2655 }
2656
2657 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2658 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2659 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002660 }
2661
Charles He9369e612017-05-15 17:07:18 +01002662 private void enforceSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002663 enforceAnyPermissionOf(
Charles He9369e612017-05-15 17:07:18 +01002664 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002665 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002666 }
2667
paulhu8e96a752019-08-12 16:25:11 +08002668 private void enforceNetworkFactoryPermission() {
paulhub6ba8e82020-03-04 09:43:41 +08002669 enforceAnyPermissionOf(
paulhu8e96a752019-08-12 16:25:11 +08002670 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002671 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002672 }
2673
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002674 private void enforceNetworkFactoryOrSettingsPermission() {
2675 enforceAnyPermissionOf(
2676 android.Manifest.permission.NETWORK_SETTINGS,
2677 android.Manifest.permission.NETWORK_FACTORY,
2678 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2679 }
2680
2681 private void enforceNetworkFactoryOrTestNetworksPermission() {
2682 enforceAnyPermissionOf(
2683 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2684 android.Manifest.permission.NETWORK_FACTORY,
2685 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2686 }
2687
Chalard Jean9a396cc2018-02-21 18:43:54 +09002688 private boolean checkSettingsPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002689 return checkAnyPermissionOf(
2690 android.Manifest.permission.NETWORK_SETTINGS,
2691 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002692 }
2693
2694 private boolean checkSettingsPermission(int pid, int uid) {
2695 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002696 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2697 || PERMISSION_GRANTED == mContext.checkPermission(
2698 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002699 }
2700
paulhu8e96a752019-08-12 16:25:11 +08002701 private void enforceNetworkStackOrSettingsPermission() {
2702 enforceAnyPermissionOf(
2703 android.Manifest.permission.NETWORK_SETTINGS,
2704 android.Manifest.permission.NETWORK_STACK,
2705 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2706 }
2707
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002708 private void enforceNetworkStackSettingsOrSetup() {
2709 enforceAnyPermissionOf(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002710 android.Manifest.permission.NETWORK_SETTINGS,
2711 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002712 android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002713 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002714 }
2715
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002716 private void enforceAirplaneModePermission() {
2717 enforceAnyPermissionOf(
2718 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2719 android.Manifest.permission.NETWORK_SETTINGS,
2720 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2721 android.Manifest.permission.NETWORK_STACK,
2722 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2723 }
2724
James Mattis8378aec2021-01-26 14:05:36 -08002725 private void enforceOemNetworkPreferencesPermission() {
2726 mContext.enforceCallingOrSelfPermission(
2727 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2728 "ConnectivityService");
2729 }
2730
James Mattisfa270db2021-05-31 17:11:10 -07002731 private void enforceManageTestNetworksPermission() {
2732 mContext.enforceCallingOrSelfPermission(
2733 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2734 "ConnectivityService");
2735 }
2736
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002737 private boolean checkNetworkStackPermission() {
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002738 return checkAnyPermissionOf(
2739 android.Manifest.permission.NETWORK_STACK,
2740 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002741 }
2742
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002743 private boolean checkNetworkStackPermission(int pid, int uid) {
2744 return checkAnyPermissionOf(pid, uid,
2745 android.Manifest.permission.NETWORK_STACK,
2746 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2747 }
2748
paulhu1a407652019-03-22 16:35:06 +08002749 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2750 return checkAnyPermissionOf(pid, uid,
2751 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002752 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2753 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002754 }
2755
Hugo Benichibd0cc762016-07-19 15:59:27 +09002756 private void enforceConnectivityRestrictedNetworksPermission() {
2757 try {
2758 mContext.enforceCallingOrSelfPermission(
2759 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2760 "ConnectivityService");
2761 return;
2762 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
paulhu8e96a752019-08-12 16:25:11 +08002763 // TODO: Remove this fallback check after all apps have declared
2764 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2765 mContext.enforceCallingOrSelfPermission(
2766 android.Manifest.permission.CONNECTIVITY_INTERNAL,
2767 "ConnectivityService");
Hugo Benichibd0cc762016-07-19 15:59:27 +09002768 }
2769
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002770 private void enforceKeepalivePermission() {
Lorenzo Colittif25beee2015-09-08 13:21:48 +09002771 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002772 }
2773
Roshan Pius98f59ec2021-02-23 08:47:39 -08002774 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2775 return PERMISSION_GRANTED == mContext.checkPermission(
2776 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2777 }
2778
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002779 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002780 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002781 }
2782
2783 private void sendInetConditionBroadcast(NetworkInfo info) {
2784 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2785 }
2786
Wink Saville4f0de1e2011-08-04 15:01:58 -07002787 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002788 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002789 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002790 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002791 if (info.isFailover()) {
2792 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2793 info.setFailover(false);
2794 }
2795 if (info.getReason() != null) {
2796 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2797 }
2798 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002799 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2800 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002801 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002802 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002803 return intent;
2804 }
2805
2806 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2807 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2808 }
2809
Chiachang Wang3bc52762021-11-25 14:17:57 +08002810 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
2811 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002812 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09002813 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09002814 if (!mSystemReady
2815 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002816 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002817 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002818 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002819 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002820 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002821 }
2822
Dianne Hackborn66dd0332015-12-09 17:22:26 -08002823 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07002824 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002825 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07002826 final NetworkInfo ni = intent.getParcelableExtra(
2827 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08002828 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2829 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2830 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08002831 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002832 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07002833 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00002834 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002835 } finally {
2836 Binder.restoreCallingIdentity(ident);
2837 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002838 }
2839 }
2840
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002841 /**
Aaron Huang96011892020-06-27 07:18:23 +08002842 * Called by SystemServer through ConnectivityManager when the system is ready.
2843 */
2844 @Override
2845 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002846 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08002847 throw new SecurityException("Calling Uid is not system uid.");
2848 }
2849 systemReadyInternal();
2850 }
2851
2852 /**
2853 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09002854 */
2855 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08002856 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09002857 // Load flags after PackageManager is ready to query module version
2858 mFlags.loadFlags(mDeps, mContext);
2859
Aaron Huang9a57acf2020-12-08 10:03:29 +08002860 // Since mApps in PermissionMonitor needs to be populated first to ensure that
2861 // listening network request which is sent by MultipathPolicyTracker won't be added
2862 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
2863 // be called after PermissionMonitor#startMonitoring().
2864 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
2865 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
2866 // to ensure the tracking will be initialized correctly.
paulhuc62d3c22019-11-19 17:55:31 +08002867 mPermissionMonitor.startMonitoring();
Chalard Jeane4f9bd92018-06-08 12:47:42 +09002868 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08002869 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07002870
Hugo Benichie5220992017-04-26 14:53:28 +09002871 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002872 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08002873 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07002874 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08002875 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002876 }
2877 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07002878
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002879 // Create network requests for always-on networks.
2880 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00002881
2882 // Update mobile data preference if necessary.
2883 // Note that empty uid list can be skip here only because no uid rules applied before system
2884 // ready. Normally, the empty uid list means to clear the uids rules on netd.
2885 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
2886 updateMobileDataPreferredUids();
2887 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002888 }
2889
The Android Open Source Project28527d22009-03-03 19:31:44 -08002890 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002891 * Start listening for default data network activity state changes.
2892 */
2893 @Override
2894 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08002895 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002896 }
2897
2898 /**
2899 * Stop listening for default data network activity state changes.
2900 */
2901 @Override
2902 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08002903 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002904 }
2905
2906 /**
2907 * Check whether the default network radio is currently active.
2908 */
2909 @Override
2910 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08002911 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08002912 }
2913
2914 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09002915 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09002916 * and set it on it's iface.
2917 */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002918 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2919 final String iface = newLp.getInterfaceName();
2920 final int mtu = newLp.getMtu();
Pierre Imai07c53a32016-02-08 16:01:40 +09002921 if (oldLp == null && mtu == 0) {
2922 // Silently ignore unset MTU value.
2923 return;
2924 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002925 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2926 if (VDBG) log("identical MTU - not setting");
2927 return;
2928 }
paulhucbbc3db2019-03-08 16:35:20 +08002929 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002930 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002931 return;
2932 }
sy.yun4aa73922013-09-02 05:24:09 +09002933
w19976e714f1d2014-08-05 15:18:11 -07002934 // Cannot set MTU without interface name
2935 if (TextUtils.isEmpty(iface)) {
2936 loge("Setting MTU size with null iface.");
2937 return;
2938 }
2939
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002940 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09002941 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08002942 mNetd.interfaceSetMtu(iface, mtu);
2943 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08002944 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07002945 }
2946 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002947
Chenbo Feng15416292018-11-08 17:36:21 -08002948 @VisibleForTesting
2949 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04002950
lucaslin821c9782018-11-28 19:27:52 +08002951 private void updateTcpBufferSizes(String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002952 String[] values = null;
2953 if (tcpBufferSizes != null) {
2954 values = tcpBufferSizes.split(",");
2955 }
2956
2957 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07002958 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002959 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2960 values = tcpBufferSizes.split(",");
2961 }
2962
2963 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2964
2965 try {
Aaron Huang6616df32020-10-30 22:04:25 +08002966 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002967
Chenbo Feng15416292018-11-08 17:36:21 -08002968 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2969 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2970 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002971 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08002972 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07002973 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002974 }
2975 }
2976
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07002977 @Override
2978 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09002979 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07002980 NETWORK_RESTORE_DELAY_PROP_NAME);
2981 if(restoreDefaultNetworkDelayStr != null &&
2982 restoreDefaultNetworkDelayStr.length() != 0) {
2983 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01002984 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07002985 } catch (NumberFormatException e) {
2986 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002987 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002988 // if the system property isn't set, use the value for the apn type
2989 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2990
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09002991 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
2992 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07002993 }
2994 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002995 }
2996
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09002997 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2998 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2999 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003000 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003001 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003002 // Start gathering diagnostic information.
3003 netDiags.add(new NetworkDiagnostics(
3004 nai.network,
3005 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003006 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003007 DIAG_TIME_MS));
3008 }
3009
3010 for (NetworkDiagnostics netDiag : netDiags) {
3011 pw.println();
3012 netDiag.waitForMeasurements();
3013 netDiag.dump(pw);
3014 }
3015 }
3016
The Android Open Source Project28527d22009-03-03 19:31:44 -08003017 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003018 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3019 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003020 if (!checkDumpPermission(mContext, TAG, writer)) return;
3021
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003022 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003023 }
3024
lucaslin99473f62020-12-10 15:10:54 +08003025 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3026 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3027 != PackageManager.PERMISSION_GRANTED) {
3028 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003029 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003030 + " due to missing android.permission.DUMP permission");
3031 return false;
3032 } else {
3033 return true;
3034 }
3035 }
3036
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003037 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003038 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003039
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003040 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003041 dumpNetworkDiagnostics(pw);
3042 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003043 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003044 dumpNetworks(pw);
3045 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003046 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003047 dumpNetworkRequests(pw);
3048 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003049 }
Erik Kline9647f382015-06-05 17:47:34 +09003050
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003051 pw.print("NetworkProviders for:");
3052 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
3053 pw.print(" " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003054 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09003055 pw.println();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003056 pw.println();
3057
Chalard Jean5b409c72021-02-04 13:12:59 +09003058 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003059 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003060 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003061 pw.println("none");
3062 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003063 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003064 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003065 pw.println();
3066
James Mattis8b298a02021-06-01 22:34:04 -07003067 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003068 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003069 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003070 pw.decreaseIndent();
3071 pw.println();
3072
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003073 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003074 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003075 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003076 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003077 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003078
junyulaif2c67e42018-08-07 19:50:45 +08003079 pw.println("Status for known UIDs:");
3080 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003081 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003082 for (int i = 0; i < size; i++) {
3083 // Don't crash if the array is modified while dumping in bugreports.
3084 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003085 final int uid = mUidBlockedReasons.keyAt(i);
3086 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3087 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003088 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003089 } catch (ArrayIndexOutOfBoundsException e) {
3090 pw.println(" ArrayIndexOutOfBoundsException");
3091 } catch (ConcurrentModificationException e) {
3092 pw.println(" ConcurrentModificationException");
3093 }
3094 }
3095 pw.println();
3096 pw.decreaseIndent();
3097
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003098 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003099 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003100 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003101 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003102 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003103
Robert Greenwalt94e22142014-07-30 16:31:24 -07003104 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003105
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003106 pw.println();
markchien5e866652019-09-30 14:40:57 +08003107 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003108
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003109 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003110 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003111
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003112 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003113
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003114 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003115 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003116 pw.println("mNetworkRequestInfoLogs (most recent first):");
3117 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003118 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003119 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003120
3121 pw.println();
3122 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3123 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003124 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003125 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003126
3127 pw.println();
3128 pw.println("NetTransition WakeLock activity (most recent first):");
3129 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003130 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3131 pw.println("total releases: " + mTotalWakelockReleases);
3132 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3133 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3134 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3135 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3136 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3137 }
James Mattiscb1e0362021-04-06 17:07:42 -07003138 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003139
3140 pw.println();
3141 pw.println("bandwidth update requests (by uid):");
3142 pw.increaseIndent();
3143 synchronized (mBandwidthRequests) {
3144 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3145 pw.println("[" + mBandwidthRequests.keyAt(i)
3146 + "]: " + mBandwidthRequests.valueAt(i));
3147 }
3148 }
3149 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003150 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003151
James Mattiscb1e0362021-04-06 17:07:42 -07003152 pw.println();
3153 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3154 pw.increaseIndent();
3155 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003156 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003157 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003158
3159 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003160
3161 pw.println();
3162 pw.println("Permission Monitor:");
3163 pw.increaseIndent();
3164 mPermissionMonitor.dump(pw);
3165 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003166
3167 pw.println();
3168 pw.println("Legacy network activity:");
3169 pw.increaseIndent();
3170 mNetworkActivityTracker.dump(pw);
3171 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003172 }
3173
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003174 private void dumpNetworks(IndentingPrintWriter pw) {
3175 for (NetworkAgentInfo nai : networksSortedById()) {
3176 pw.println(nai.toString());
3177 pw.increaseIndent();
3178 pw.println(String.format(
3179 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3180 nai.numForegroundNetworkRequests(),
3181 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3182 nai.numBackgroundNetworkRequests(),
3183 nai.numNetworkRequests()));
3184 pw.increaseIndent();
3185 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3186 pw.println(nai.requestAt(i).toString());
3187 }
3188 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003189 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003190 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003191 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003192 pw.decreaseIndent();
3193 pw.decreaseIndent();
3194 }
3195 }
3196
James Mattis8b298a02021-06-01 22:34:04 -07003197 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3198 if (!mProfileNetworkPreferences.isEmpty()) {
3199 pw.println("Profile preferences:");
3200 pw.increaseIndent();
3201 pw.println(mProfileNetworkPreferences.preferences);
3202 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003203 }
James Mattis8b298a02021-06-01 22:34:04 -07003204 if (!mOemNetworkPreferences.isEmpty()) {
3205 pw.println("OEM preferences:");
3206 pw.increaseIndent();
3207 pw.println(mOemNetworkPreferences);
3208 pw.decreaseIndent();
3209 }
3210 if (!mMobileDataPreferredUids.isEmpty()) {
3211 pw.println("Mobile data preferred UIDs:");
3212 pw.increaseIndent();
3213 pw.println(mMobileDataPreferredUids);
3214 pw.decreaseIndent();
3215 }
James Mattis45d81842021-01-10 14:24:24 -08003216
James Mattis8b298a02021-06-01 22:34:04 -07003217 pw.println("Default requests:");
3218 pw.increaseIndent();
3219 dumpPerAppDefaultRequests(pw);
3220 pw.decreaseIndent();
3221 }
3222
3223 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003224 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3225 if (mDefaultRequest == defaultRequest) {
3226 continue;
3227 }
3228
James Mattis8b298a02021-06-01 22:34:04 -07003229 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3230 final String networkOutput;
3231 if (null == satisfier) {
3232 networkOutput = "null";
3233 } else if (mNoServiceNetwork.equals(satisfier)) {
3234 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003235 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003236 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003237 }
James Mattis8b298a02021-06-01 22:34:04 -07003238 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3239 ? "" : " asUid: " + defaultRequest.mAsUid;
3240 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3241 + defaultRequest.mPid + asUidString + "]";
3242 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3243 + " Preference order: " + defaultRequest.mPreferenceOrder
3244 + " Tracked UIDs: " + defaultRequest.getUids();
3245 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003246 }
3247 }
3248
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003249 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003250 NetworkRequestInfo[] infos = null;
3251 while (infos == null) {
3252 try {
3253 infos = requestsSortedById();
3254 } catch (ConcurrentModificationException e) {
3255 // mNetworkRequests should only be accessed from handler thread, except dump().
3256 // As dump() is never called in normal usage, it would be needlessly expensive
3257 // to lock the collection only for its benefit. Instead, retry getting the
3258 // requests if ConcurrentModificationException is thrown during dump().
3259 }
3260 }
3261 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003262 pw.println(nri.toString());
3263 }
3264 }
3265
Chalard Jean524f0b12021-10-25 21:11:56 +09003266 private void dumpAllRequestInfoLogsToLogcat() {
3267 try (PrintWriter logPw = new PrintWriter(new Writer() {
3268 @Override
3269 public void write(final char[] cbuf, final int off, final int len) {
3270 // This method is called with 0-length and 1-length arrays for empty strings
3271 // or strings containing only the DEL character.
3272 if (len <= 1) return;
3273 Log.e(TAG, new String(cbuf, off, len));
3274 }
3275 @Override public void flush() {}
3276 @Override public void close() {}
3277 })) {
3278 mNetworkRequestInfoLogs.dump(logPw);
3279 }
3280 }
3281
Hugo Benichia480ba52018-09-03 08:19:02 +09003282 /**
3283 * Return an array of all current NetworkAgentInfos sorted by network id.
3284 */
3285 private NetworkAgentInfo[] networksSortedById() {
3286 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003287 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003288 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003289 return networks;
3290 }
3291
3292 /**
3293 * Return an array of all current NetworkRequest sorted by request id.
3294 */
James Mattis258ea3c2020-11-15 15:04:40 -08003295 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003296 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003297 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003298 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003299 // Sort the array based off the NRI containing the min requestId in its requests.
3300 Arrays.sort(requests,
3301 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3302 Comparator.comparingInt(req -> req.requestId)).requestId
3303 )
3304 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003305 return requests;
3306 }
3307
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003308 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003309 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003310 if (officialNai != null && officialNai.equals(nai)) return true;
3311 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003312 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003313 " - " + nai);
3314 }
3315 return false;
3316 }
3317
Robert Greenwalt2034b912009-08-12 16:08:25 -07003318 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003319 private class NetworkStateTrackerHandler extends Handler {
3320 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003321 super(looper);
3322 }
3323
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003324 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003325 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3326 final NetworkAgentInfo nai = arg.first;
3327 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003328 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003329 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003330 }
3331 return;
3332 }
3333
3334 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003335 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003336 NetworkCapabilities networkCapabilities = (NetworkCapabilities) arg.second;
lucaslin2240ef62019-03-12 13:08:03 +08003337 if (networkCapabilities.hasConnectivityManagedCapability()) {
Aaron Huang6616df32020-10-30 22:04:25 +08003338 Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003339 }
Chalard Jean5b639762020-03-09 21:25:37 +09003340 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
3341 // Make sure the original object is not mutated. NetworkAgent normally
3342 // makes a copy of the capabilities when sending the message through
3343 // the Messenger, but if this ever changes, not making a defensive copy
3344 // here will give attack vectors to clients using this code path.
3345 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Chiachang Wangc07315a2021-08-10 15:13:39 +08003346 networkCapabilities.restrictCapabilitiesForTestNetwork(nai.creatorUid);
Chalard Jean5b639762020-03-09 21:25:37 +09003347 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003348 processCapabilitiesFromAgent(nai, networkCapabilities);
Hugo Benichibbc15192016-09-15 18:18:48 +09003349 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003350 break;
3351 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003352 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003353 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003354 processLinkPropertiesFromAgent(nai, newLp);
3355 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003356 break;
3357 }
3358 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003359 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003360 updateNetworkInfo(nai, info);
3361 break;
3362 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003363 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003364 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003365 break;
3366 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003367 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003368 if (nai.everConnected) {
3369 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003370 // Note that if the NAI had been connected, this would affect the
3371 // score, and therefore would require re-mixing the score and performing
3372 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003373 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003374 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3375 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003376 // Mark the network as temporarily accepting partial connectivity so that it
3377 // will be validated (and possibly become default) even if it only provides
3378 // partial internet access. Note that if user connects to partial connectivity
3379 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3380 // out of wifi coverage) and if the same wifi is available again, the device
3381 // will auto connect to this wifi even though the wifi has "no internet".
3382 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003383 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003384 break;
3385 }
junyulai011b1f12019-01-03 18:50:15 +08003386 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003387 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003388 break;
3389 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003390 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003391 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003392 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003393
3394 if (isLegacyLockdownNai(nai)
3395 && (underlying == null || underlying.size() != 1)) {
3396 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3397 + " must have exactly one underlying network: " + underlying);
3398 }
3399
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003400 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3401 nai.declaredUnderlyingNetworks = (underlying != null)
3402 ? underlying.toArray(new Network[0]) : null;
3403
3404 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3405 if (DBG) {
3406 log(nai.toShortString() + " changed underlying networks to "
3407 + Arrays.toString(nai.declaredUnderlyingNetworks));
3408 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003409 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003410 notifyIfacesChangedForNetworkStats();
3411 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003412 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003413 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003414 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3415 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3416 nai.teardownDelayMs = msg.arg1;
3417 } else {
3418 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3419 }
Chalard Jean550b5212021-03-05 23:07:53 +09003420 break;
3421 }
3422 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3423 nai.setLingerDuration((int) arg.second);
3424 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003425 }
Tyler Wear72388212021-09-09 14:49:02 -07003426 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3427 DscpPolicy policy = (DscpPolicy) arg.second;
3428 if (mDscpPolicyTracker != null) {
3429 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3430 }
3431 break;
3432 }
3433 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3434 if (mDscpPolicyTracker != null) {
3435 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3436 }
3437 break;
3438 }
3439 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3440 if (mDscpPolicyTracker != null) {
3441 mDscpPolicyTracker.removeAllDscpPolicies(nai);
3442 }
3443 break;
3444 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003445 }
3446 }
3447
3448 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
3449 switch (msg.what) {
3450 default:
3451 return false;
lucasline117e2e2019-10-22 18:27:33 +08003452 case EVENT_PROBE_STATUS_CHANGED: {
3453 final Integer netId = (Integer) msg.obj;
3454 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3455 if (nai == null) {
3456 break;
3457 }
3458 final boolean probePrivateDnsCompleted =
3459 ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
3460 final boolean privateDnsBroken =
3461 ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
3462 if (probePrivateDnsCompleted) {
3463 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3464 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003465 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003466 }
3467 // Only show the notification when the private DNS is broken and the
3468 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003469 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003470 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3471 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003472 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003473 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3474 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3475 // private DNS is broken, it means this network is being reevaluated.
3476 // Either probing private DNS is not necessary any more or it hasn't been
3477 // done yet. In either case, the networkCapabilities should be updated to
3478 // reflect the new status.
3479 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003480 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003481 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003482 }
3483 break;
3484 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003485 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003486 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3487
3488 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(results.mNetId);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003489 if (nai == null) break;
3490
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003491 handleNetworkTested(nai, results.mTestResult,
3492 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003493 break;
3494 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003495 case EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09003496 final int netId = msg.arg2;
Hugo Benichif4210292017-04-21 15:07:12 +09003497 final boolean visible = toBool(msg.arg1);
Erik Kline9a62f012018-03-21 07:18:33 -07003498 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Calvin Ondada1452016-10-11 15:10:46 -07003499 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04003500 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3501 nai.lastCaptivePortalDetected = visible;
3502 nai.everCaptivePortalDetected |= visible;
Calvin Ondada1452016-10-11 15:10:46 -07003503 if (nai.lastCaptivePortalDetected &&
paulhu56e09df2021-03-17 20:30:33 +08003504 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3505 == getCaptivePortalMode()) {
Chalard Jean49707572019-12-10 21:07:02 +09003506 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003507 nai.onPreventAutomaticReconnect();
Calvin Ondada1452016-10-11 15:10:46 -07003508 teardownUnneededNetwork(nai);
3509 break;
3510 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003511 updateCapabilitiesForNetwork(nai);
Paul Jensen53f08952015-06-16 14:27:36 -04003512 }
3513 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003514 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003515 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003516 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3517 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003518 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003519 if (nai == null) {
3520 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3521 break;
3522 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003523 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003524 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003525 (PendingIntent) msg.obj,
3526 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003527 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003528 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003529 break;
3530 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003531 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline9a62f012018-03-21 07:18:33 -07003532 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003533 if (nai == null) break;
3534
Erik Kline9a62f012018-03-21 07:18:33 -07003535 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003536 break;
3537 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003538 case EVENT_CAPPORT_DATA_CHANGED: {
3539 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3540 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003541 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003542 break;
3543 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003544 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003545 return true;
3546 }
3547
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003548 private void handleNetworkTested(
3549 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
3550 final boolean wasPartial = nai.partialConnectivity;
3551 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3552 final boolean partialConnectivityChanged =
3553 (wasPartial != nai.partialConnectivity);
3554
3555 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3556 final boolean wasValidated = nai.lastValidated;
Chalard Jean5b409c72021-02-04 13:12:59 +09003557 final boolean wasDefault = isDefaultNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003558
3559 if (DBG) {
3560 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3561 ? " with redirect to " + redirectUrl
3562 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003563 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003564 }
3565 if (valid != nai.lastValidated) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003566 final int oldScore = nai.getCurrentScore();
3567 nai.lastValidated = valid;
3568 nai.everValidated |= valid;
3569 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003570 if (valid) {
3571 handleFreshlyValidatedNetwork(nai);
3572 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3573 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003574 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003575 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003576 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003577 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003578 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003579 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003580 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003581 NotificationType.PRIVATE_DNS_BROKEN);
3582 // If network becomes valid, the hasShownBroken should be reset for
3583 // that network so that the notification will be fired when the private
3584 // DNS is broken again.
3585 nai.networkAgentConfig.hasShownBroken = false;
3586 }
3587 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003588 updateCapabilitiesForNetwork(nai);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003589 }
3590 updateInetCondition(nai);
3591 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003592 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003593 nai.onValidationStatusChanged(
3594 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3595 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003596
3597 // If NetworkMonitor detects partial connectivity before
3598 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3599 // immediately. Re-notify partial connectivity silently if no internet
3600 // notification already there.
3601 if (!wasPartial && nai.partialConnectivity) {
3602 // Remove delayed message if there is a pending message.
3603 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3604 handlePromptUnvalidated(nai.network);
3605 }
3606
3607 if (wasValidated && !nai.lastValidated) {
3608 handleNetworkUnvalidated(nai);
3609 }
3610 }
3611
Calvin Ondada1452016-10-11 15:10:46 -07003612 private int getCaptivePortalMode() {
3613 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08003614 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3615 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07003616 }
3617
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003618 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3619 switch (msg.what) {
3620 default:
3621 return false;
3622 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3623 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3624 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3625 handleLingerComplete(nai);
3626 }
3627 break;
3628 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003629 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3630 handleNetworkAgentRegistered(msg);
3631 break;
3632 }
3633 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3634 handleNetworkAgentDisconnected(msg);
3635 break;
3636 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003637 }
3638 return true;
3639 }
3640
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003641 @Override
3642 public void handleMessage(Message msg) {
lifraf3a3492021-03-10 13:58:14 +08003643 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09003644 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003645 maybeHandleNetworkAgentMessage(msg);
3646 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003647 }
3648 }
3649
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003650 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09003651 private final int mNetId;
3652 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003653
3654 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003655 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003656 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003657 }
3658
3659 @Override
3660 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3661 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09003662 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003663 }
3664
3665 @Override
3666 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003667 // Legacy version of notifyNetworkTestedWithExtras.
3668 // Would only be called if the system has a NetworkStack module older than the
3669 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08003670 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003671 }
3672
3673 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003674 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09003675 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3676 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003677 final Message msg = mTrackerHandler.obtainMessage(
3678 EVENT_NETWORK_TESTED,
3679 new NetworkTestedResults(
3680 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003681 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003682
3683 // Invoke ConnectivityReport generation for this Network test event.
3684 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3685 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003686
Cody Kestingf1120be2020-08-03 18:01:40 -07003687 // NetworkMonitor reports the network validation result as a bitmask while
3688 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
3689 // logical value for ConnectivityDiagnostics.
3690 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
3691 p.result);
3692
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003693 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07003694 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003695 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3696 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3697
Aaron Huang959d3642021-01-21 15:47:41 +08003698 ConnectivityReportEvent reportEvent =
3699 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3700 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
3701 ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003702 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003703 }
3704
3705 @Override
3706 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3707 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3708 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09003709 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003710 }
3711
3712 @Override
lucasline117e2e2019-10-22 18:27:33 +08003713 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3714 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3715 EVENT_PROBE_STATUS_CHANGED,
3716 probesCompleted, probesSucceeded, new Integer(mNetId)));
3717 }
3718
3719 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003720 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3721 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3722 EVENT_CAPPORT_DATA_CHANGED,
3723 0, mNetId, data));
3724 }
3725
3726 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003727 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003728 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003729 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003730
3731 final PendingIntent pendingIntent;
3732 // Only the system server can register notifications with package "android"
3733 final long token = Binder.clearCallingIdentity();
3734 try {
paulhu7746e4e2020-06-09 19:07:03 +08003735 pendingIntent = PendingIntent.getBroadcast(
3736 mContext,
3737 0 /* requestCode */,
3738 intent,
3739 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003740 } finally {
3741 Binder.restoreCallingIdentity(token);
3742 }
3743 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3744 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09003745 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003746 }
3747
3748 @Override
3749 public void hideProvisioningNotification() {
3750 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09003751 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003752 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003753
3754 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003755 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003756 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08003757 }
3758
3759 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09003760 public int getInterfaceVersion() {
3761 return this.VERSION;
3762 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09003763
3764 @Override
3765 public String getInterfaceHash() {
3766 return this.HASH;
3767 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003768 }
3769
Cody Kestingf1120be2020-08-03 18:01:40 -07003770 /**
3771 * Converts the given NetworkMonitor-specific validation result bitmask to a
3772 * ConnectivityDiagnostics-specific validation result int.
3773 */
3774 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
3775 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
3776 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
3777 }
3778 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
3779 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
3780 }
3781 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
3782 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
3783 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
3784 }
3785
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003786 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07003787 log("Data stall detected with methods: " + p.detectionMethod);
3788
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003789 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07003790 int detectionMethod = 0;
3791 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
3792 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
3793 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
3794 }
3795 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
3796 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
3797 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
3798 p.tcpMetricsCollectionPeriodMillis);
3799 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003800 }
3801
Cody Kestingf53a0752020-04-15 12:33:28 -07003802 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07003803 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08003804 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07003805
3806 // NetworkStateTrackerHandler currently doesn't take any actions based on data
3807 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
3808 // the cost of going through two handlers.
3809 mConnectivityDiagnosticsHandler.sendMessage(msg);
3810 }
3811
Cody Kestingb37958e2020-05-15 10:36:01 -07003812 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
3813 return (p.detectionMethod & detectionMethod) != 0;
3814 }
3815
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003816 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
3817 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07003818 }
3819
Erik Klinea73af002018-06-26 18:53:43 +09003820 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
3821 if (nai == null) return;
3822 // If the Private DNS mode is opportunistic, reprogram the DNS servers
3823 // in order to restart a validation pass from within netd.
3824 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3825 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003826 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09003827 }
3828 }
3829
Erik Kline31b4a9e2018-01-11 21:07:29 +09003830 private void handlePrivateDnsSettingsChanged() {
3831 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3832
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003833 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07003834 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003835 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05003836 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3837 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09003838 }
3839 }
3840
Erik Kline9a62f012018-03-21 07:18:33 -07003841 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
3842 // Private DNS only ever applies to networks that might provide
3843 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09003844 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09003845
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003846 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07003847 // schedule DNS resolutions. If a DNS resolution is required the
3848 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09003849 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07003850
3851 // With Private DNS bypass support, we can proceed to update the
3852 // Private DNS config immediately, even if we're in strict mode
3853 // and have not yet resolved the provider name into a set of IPs.
3854 updatePrivateDns(nai, cfg);
3855 }
3856
3857 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
3858 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003859 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09003860 }
3861
dalyk1720e542018-03-05 12:42:22 -05003862 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
3863 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
3864 if (nai == null) {
3865 return;
3866 }
3867 mDnsManager.updatePrivateDnsValidation(update);
3868 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3869 }
3870
paulhu7c0a2e62021-01-08 00:51:49 +08003871 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003872 int prefixLength) {
3873 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
3874 if (nai == null) return;
3875
paulhu7c0a2e62021-01-08 00:51:49 +08003876 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
3877 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003878
3879 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08003880 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003881 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003882 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003883 prefixLength);
3884 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003885 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003886 return;
3887 }
3888 }
3889
Lorenzo Colittid523d142020-04-01 20:16:30 +09003890 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003891 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3892 }
3893
Hai Shalome58bdc62021-01-11 18:45:34 -08003894 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003895 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08003896 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003897 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
3898 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3899 }
3900
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003901 /**
junyulai2b6f0c22021-02-03 20:15:30 +08003902 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003903 * @param nai the agent info to update
3904 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08003905 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003906 */
junyulai2b6f0c22021-02-03 20:15:30 +08003907 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
3908 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
3909 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003910 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08003911 // one lingered request, set inactive.
3912 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08003913 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08003914 if (DBG) log("Unsetting inactive " + nai.toShortString());
3915 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003916 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08003917 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003918 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08003919 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
3920 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003921 }
junyulai2b6f0c22021-02-03 20:15:30 +08003922 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003923 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003924 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003925 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09003926 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05003927 }
3928
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003929 private void handleNetworkAgentRegistered(Message msg) {
3930 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3931 if (!mNetworkAgentInfos.contains(nai)) {
3932 return;
3933 }
3934
3935 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
3936 if (VDBG) log("NetworkAgent registered");
3937 } else {
3938 loge("Error connecting NetworkAgent");
3939 mNetworkAgentInfos.remove(nai);
3940 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09003941 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003942 synchronized (mNetworkForNetId) {
3943 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07003944 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003945 mNetIdManager.releaseNetId(nai.network.getNetId());
3946 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09003947 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003948 }
3949 }
3950 }
Paul Jensend5f53392014-11-25 15:26:53 -05003951
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003952 private void handleNetworkAgentDisconnected(Message msg) {
3953 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07003954 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003955 }
3956
Chalard Jeand9fffc32018-05-11 20:19:20 +09003957 // Destroys a network, remove references to it from the internal state managed by
3958 // ConnectivityService, free its interfaces and clean up.
3959 // Must be called on the Handler thread.
3960 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09003961 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07003962
3963 if (!mNetworkAgentInfos.contains(nai)) return;
3964
Chalard Jeand9fffc32018-05-11 20:19:20 +09003965 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09003966 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003967 }
lucaslinb25c9a62019-02-12 15:30:13 +08003968 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003969 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09003970 // A network agent has disconnected.
3971 // TODO - if we move the logic to the network agent (have them disconnect
3972 // because they lost all their requests or because their score isn't good)
3973 // then they would disconnect organically, report their new state and then
3974 // disconnect the channel.
3975 if (nai.networkInfo.isConnected()) {
3976 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3977 null, null);
3978 }
Chalard Jean5b409c72021-02-04 13:12:59 +09003979 final boolean wasDefault = isDefaultNetwork(nai);
3980 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09003981 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09003982 }
3983 notifyIfacesChangedForNetworkStats();
3984 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
3985 // by other networks that are already connected. Perhaps that can be done by
3986 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
3987 // of rematchAllNetworksAndRequests
3988 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08003989 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07003990
3991 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09003992 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
3993 // Disable wakeup packet monitoring for each interface.
3994 wakeupModifyInterface(iface, nai.networkCapabilities, false);
3995 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09003996 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003997 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09003998 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09003999 synchronized (mNetworkForNetId) {
4000 // Remove the NetworkAgent, but don't mark the netId as
4001 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004002 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004003 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004004 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004005 // Remove all previously satisfied requests.
4006 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004007 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004008 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004009 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004010 if (currentNetwork != null
4011 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004012 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004013 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4014 // rematch not to keep disconnected agents instead of setting it here ; this
4015 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004016 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004017 for (final NetworkOfferInfo noi : mNetworkOffers) {
4018 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004019 }
James Mattise3ef1912020-12-20 11:09:58 -08004020
Chalard Jean5b409c72021-02-04 13:12:59 +09004021 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004022 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004023 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004024 // network, because while incorrect this is the closest to the old (also
4025 // incorrect) behavior.
4026 mNetworkActivityTracker.updateDataActivityTracking(
4027 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004028 ensureNetworkTransitionWakelock(nai.toShortString());
4029 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004030 }
4031 }
junyulai2b6f0c22021-02-03 20:15:30 +08004032 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004033 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004034 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004035 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004036 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004037 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004038 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004039
4040 // Immediate teardown.
4041 if (nai.teardownDelayMs == 0) {
4042 destroyNetwork(nai);
4043 return;
4044 }
4045
4046 // Delayed teardown.
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304047 if (nai.created) {
4048 try {
4049 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4050 } catch (RemoteException e) {
4051 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4052 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004053 }
4054 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4055 }
4056
4057 private void destroyNetwork(NetworkAgentInfo nai) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004058 if (nai.created) {
4059 // Tell netd to clean up the configuration for this network
4060 // (routing rules, DNS, etc).
4061 // This may be slow as it requires a lot of netd shelling out to ip and
4062 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004063 // after we've rematched networks with requests (which might change the default
4064 // network or service a new request from an app), so network traffic isn't interrupted
4065 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004066 destroyNativeNetwork(nai);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004067 mDnsManager.removeNetwork(nai.network);
4068 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004069 mNetIdManager.releaseNetId(nai.network.getNetId());
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004070 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004071 }
4072
Ken Chen6df7a902021-04-09 15:08:42 +08004073 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004074 try {
4075 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004076 final NativeNetworkConfig config;
4077 if (nai.isVPN()) {
4078 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004079 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004080 return false;
4081 }
4082 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4083 INetd.PERMISSION_NONE,
4084 (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass),
Chiachang Wang9164c102022-01-13 10:54:32 +08004085 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004086 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004087 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
4088 getNetworkPermission(nai.networkCapabilities), /*secure=*/ false,
Chiachang Wangbf6b8792022-01-11 10:48:07 +08004089 VpnManager.TYPE_VPN_NONE, /*excludeLocalRoutes=*/ false);
Luke Huangfdd11f82019-04-09 18:41:49 +08004090 }
Ken Chen6df7a902021-04-09 15:08:42 +08004091 mNetd.networkCreate(config);
4092 mDnsResolver.createNetworkCache(nai.network.getNetId());
4093 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4094 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004095 return true;
4096 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004097 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004098 return false;
4099 }
4100 }
4101
Ken Chen6df7a902021-04-09 15:08:42 +08004102 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004103 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004104 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004105 } catch (RemoteException | ServiceSpecificException e) {
4106 loge("Exception destroying network(networkDestroy): " + e);
4107 }
4108 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004109 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004110 } catch (RemoteException | ServiceSpecificException e) {
4111 loge("Exception destroying network: " + e);
4112 }
4113 }
4114
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004115 // If this method proves to be too slow then we can maintain a separate
4116 // pendingIntent => NetworkRequestInfo map.
4117 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4118 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004119 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4120 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4121 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004122 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004123 return entry.getValue();
4124 }
4125 }
4126 return null;
4127 }
4128
Chalard Jean524f0b12021-10-25 21:11:56 +09004129 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4130 if (SdkLevel.isAtLeastT()) {
4131 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4132 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4133 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4134 // bug is fixed.
4135 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004136 throw new IllegalStateException("This NRI is already registered. New : " + nri
4137 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004138 }
4139 }
4140 }
4141 }
4142
James Mattisf7027322020-12-13 16:28:14 -08004143 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004144 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004145 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4146 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4147 final NetworkRequestInfo existingRequest =
4148 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004149 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004150 if (DBG) {
4151 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4152 + nri.mRequests.get(0) + " because their intents matched.");
4153 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004154 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004155 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004156 }
Erik Kline05f2b402015-04-30 12:58:40 +09004157 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004158 }
4159
James Mattisf7027322020-12-13 16:28:14 -08004160 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004161 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004162 }
4163
James Mattis3ce3d3c2021-02-09 18:18:28 -08004164 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004165 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004166 for (final NetworkRequestInfo nri : nris) {
4167 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004168 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004169 for (final NetworkRequest req : nri.mRequests) {
4170 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004171 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004172 if (req.isListen()) {
4173 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4174 if (req.networkCapabilities.hasSignalStrength()
4175 && network.satisfiesImmutableCapabilitiesOf(req)) {
4176 updateSignalStrengthThresholds(network, "REGISTER", req);
4177 }
James Mattisf7027322020-12-13 16:28:14 -08004178 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004179 }
4180 }
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004181 // If this NRI has a satisfier already, it is replacing an older request that
4182 // has been removed. Track it.
4183 final NetworkRequest activeRequest = nri.getActiveRequest();
4184 if (null != activeRequest) {
4185 // If there is an active request, then for sure there is a satisfier.
4186 nri.getSatisfier().addRequest(activeRequest);
4187 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004188 }
James Mattisf7027322020-12-13 16:28:14 -08004189
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004190 if (mFlags.noRematchAllRequestsOnRegister()) {
4191 rematchNetworksAndRequests(nris);
4192 } else {
4193 rematchAllNetworksAndRequests();
4194 }
James Mattis45d81842021-01-10 14:24:24 -08004195
Chalard Jean0354d8c2021-01-12 10:58:56 +09004196 // Requests that have not been matched to a network will not have been sent to the
4197 // providers, because the old satisfier and the new satisfier are the same (null in this
4198 // case). Send these requests to the providers.
4199 for (final NetworkRequestInfo nri : nris) {
4200 for (final NetworkOfferInfo noi : mNetworkOffers) {
4201 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004202 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004203 }
4204 }
4205
James Mattisf7027322020-12-13 16:28:14 -08004206 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4207 final int callingUid) {
4208 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004209 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004210 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4211 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4212 handleReleaseNetworkRequest(
4213 nri.mRequests.get(0),
4214 callingUid,
4215 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004216 }
4217 }
4218
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004219 // Determines whether the network is the best (or could become the best, if it validated), for
4220 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4221 // on the value of reason:
4222 //
4223 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4224 // then it should be torn down.
4225 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4226 // then it should be lingered.
4227 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004228 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004229
4230 if (!nai.everConnected || nai.isVPN() || nai.isInactive()
4231 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4232 return false;
4233 }
4234
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004235 final int numRequests;
4236 switch (reason) {
4237 case TEARDOWN:
4238 numRequests = nai.numRequestNetworkRequests();
4239 break;
4240 case LINGER:
4241 numRequests = nai.numForegroundNetworkRequests();
4242 break;
4243 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004244 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004245 return true;
4246 }
4247
Chalard Jean947acd42021-03-08 22:29:27 +09004248 if (numRequests > 0) return false;
4249
Paul Jensende49eb12015-06-25 15:30:08 -04004250 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004251 if (reason == UnneededFor.LINGER
4252 && !nri.isMultilayerRequest()
4253 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004254 // Background requests don't affect lingering.
4255 continue;
4256 }
4257
James Mattis3d229892020-11-16 16:46:28 -08004258 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004259 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004260 }
4261 }
Paul Jensende49eb12015-06-25 15:30:08 -04004262 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004263 }
4264
James Mattis3d229892020-11-16 16:46:28 -08004265 private boolean isNetworkPotentialSatisfier(
4266 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4267 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004268 // request, return immediately. For multilayer requests, check to see if any of the
4269 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004270 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4271 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004272 return false;
4273 }
4274 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004275 // This multilayer listen request is satisfied therefore no further requests need to be
4276 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004277 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004278 return false;
4279 }
James Mattis3d229892020-11-16 16:46:28 -08004280 // As non-multilayer listen requests have already returned, the below would only happen
4281 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004282 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004283 continue;
4284 }
4285 // If this Network is already the highest scoring Network for a request, or if
4286 // there is hope for it to become one if it validated, then it is needed.
4287 if (candidate.satisfies(req)) {
4288 // As soon as a network is found that satisfies a request, return. Specifically for
4289 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4290 // is important so as to not evaluate lower priority requests further in
4291 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004292 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4293 ? nri.getSatisfier() : null;
4294 // Note that this catches two important cases:
4295 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4296 // is currently satisfying the request. This is desirable when
4297 // cellular ends up validating but WiFi does not.
4298 // 2. Unvalidated WiFi will not be reaped when validated cellular
4299 // is currently satisfying the request. This is desirable when
4300 // WiFi ends up validating and out scoring cellular.
4301 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004302 }
4303 }
4304
4305 return false;
4306 }
4307
Erik Kline0c04b742016-07-07 16:50:58 +09004308 private NetworkRequestInfo getNriForAppRequest(
4309 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004310 // Looking up the app passed param request in mRequests isn't possible since it may return
4311 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4312 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004313 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4314 // to avoid potential race conditions when validating a package->uid mapping when sending
4315 // the callback on the very low-chance that an application shuts down prior to the callback
4316 // being sent.
4317 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4318 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004319
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004320 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004321 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004322 log(String.format("UID %d attempted to %s for unowned request %s",
4323 callingUid, requestedOperation, nri));
4324 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004325 }
Erik Kline0c04b742016-07-07 16:50:58 +09004326 }
4327
4328 return nri;
4329 }
4330
James Mattisf7027322020-12-13 16:28:14 -08004331 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4332 final String callingMethod) {
4333 if (nri.isMultilayerRequest()) {
4334 throw new IllegalStateException(
4335 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004336 }
4337 }
4338
James Mattisf7027322020-12-13 16:28:14 -08004339 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004340 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004341 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4342 // single NetworkRequest and thus does not apply to multilayer requests.
4343 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4344 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004345 return;
4346 }
James Mattis2516da32021-01-31 17:06:19 -08004347 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004348 return;
4349 }
James Mattisf7027322020-12-13 16:28:14 -08004350 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4351 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004352 }
4353 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004354 callCallbackForRequest(
4355 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004356 }
4357
James Mattisf7027322020-12-13 16:28:14 -08004358 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4359 final int callingUid,
4360 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004361 final NetworkRequestInfo nri =
4362 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4363 if (nri == null) {
4364 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004365 }
James Mattisf7027322020-12-13 16:28:14 -08004366 if (VDBG || (DBG && request.isRequest())) {
4367 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004368 }
4369 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004370 if (callOnUnavailable) {
4371 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4372 }
Erik Kline155a59a2015-11-25 12:49:38 +09004373 }
Erik Kline0c04b742016-07-07 16:50:58 +09004374
James Mattisa076c532020-12-02 14:12:41 -08004375 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004376 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004377 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004378 if (null == mNetworkRequests.remove(req)) {
4379 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4380 continue;
4381 }
James Mattisa076c532020-12-02 14:12:41 -08004382 if (req.isListen()) {
4383 removeListenRequestFromNetworks(req);
4384 }
4385 }
James Mattis8f036802021-06-20 16:26:01 -07004386 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004387 if (mDefaultNetworkRequests.remove(nri)) {
4388 // If this request was one of the defaults, then the UID rules need to be updated
4389 // WARNING : if the app(s) for which this network request is the default are doing
4390 // traffic, this will kill their connected sockets, even if an equivalent request
4391 // is going to be reinstated right away ; unconnected traffic will go on the default
4392 // until the new default is set, which will happen very soon.
4393 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4394 // remove ranges for those requests that won't have a replacement
4395 final NetworkAgentInfo satisfier = nri.getSatisfier();
4396 if (null != satisfier) {
4397 try {
paulhu0e79d952021-06-09 16:11:35 +08004398 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4399 satisfier.network.getNetId(),
4400 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004401 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004402 } catch (RemoteException e) {
4403 loge("Exception setting network preference default network", e);
4404 }
4405 }
4406 }
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09004407 nri.decrementRequestCount();
Erik Kline0c04b742016-07-07 16:50:58 +09004408 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004409 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004410
4411 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004412 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004413 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004414 }
4415 }
4416
Chalard Jean0354d8c2021-01-12 10:58:56 +09004417 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4418 // needed for this offer.
4419 for (final NetworkOfferInfo noi : mNetworkOffers) {
4420 for (final NetworkRequest req : nri.mRequests) {
4421 if (req.isRequest() && noi.offer.neededFor(req)) {
4422 noi.offer.onNetworkUnneeded(req);
4423 }
4424 }
4425 }
James Mattisa076c532020-12-02 14:12:41 -08004426 }
4427
James Mattis3ce3d3c2021-02-09 18:18:28 -08004428 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4429 for (final NetworkRequestInfo nri : nris) {
4430 if (mDefaultRequest == nri) {
4431 // Make sure we never remove the default request.
4432 continue;
4433 }
4434 handleRemoveNetworkRequest(nri);
4435 }
4436 }
4437
James Mattisa076c532020-12-02 14:12:41 -08004438 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4439 // listens don't have a singular affected Network. Check all networks to see
4440 // if this listen request applies and remove it.
4441 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4442 nai.removeRequest(req.requestId);
4443 if (req.networkCapabilities.hasSignalStrength()
4444 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4445 updateSignalStrengthThresholds(nai, "RELEASE", req);
4446 }
4447 }
4448 }
4449
4450 /**
4451 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4452 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4453 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4454 */
4455 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4456 boolean wasKept = false;
4457 final NetworkAgentInfo nai = nri.getSatisfier();
4458 if (nai != null) {
4459 final int requestLegacyType = nri.getActiveRequest().legacyType;
4460 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4461 nai.removeRequest(nri.getActiveRequest().requestId);
4462 if (VDBG || DDBG) {
4463 log(" Removing from current network " + nai.toShortString()
4464 + ", leaving " + nai.numNetworkRequests() + " requests.");
4465 }
4466 // If there are still lingered requests on this network, don't tear it down,
4467 // but resume lingering instead.
4468 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004469 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004470 notifyNetworkLosing(nai, now);
4471 }
4472 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4473 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4474 teardownUnneededNetwork(nai);
4475 } else {
4476 wasKept = true;
4477 }
James Mattisa076c532020-12-02 14:12:41 -08004478 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4479 // Went from foreground to background.
4480 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004481 }
4482
Erik Kline0c04b742016-07-07 16:50:58 +09004483 // Maintain the illusion. When this request arrived, we might have pretended
4484 // that a network connected to serve it, even though the network was already
4485 // connected. Now that this request has gone away, we might have to pretend
4486 // that the network disconnected. LegacyTypeTracker will generate that
4487 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004488 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004489 boolean doRemove = true;
4490 if (wasKept) {
4491 // check if any of the remaining requests for this network are for the
4492 // same legacy type - if so, don't remove the nai
4493 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4494 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004495 if (otherRequest.legacyType == requestLegacyType
4496 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004497 if (DBG) log(" still have other legacy request - leaving");
4498 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004499 }
4500 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004501 }
4502
Erik Kline0c04b742016-07-07 16:50:58 +09004503 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004504 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004505 }
4506 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004507 }
4508 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004509
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004510 private PerUidCounter getRequestCounter(NetworkRequestInfo nri) {
4511 return checkAnyPermissionOf(
4512 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4513 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4514 }
4515
Lorenzo Colittid6459092016-07-04 12:55:44 +09004516 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004517 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004518 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004519 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004520 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004521 }
4522
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004523 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004524 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4525 enforceNetworkStackSettingsOrSetup();
4526 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4527 encodeBool(accept), encodeBool(always), network));
4528 }
4529
4530 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004531 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004532 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004533 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4534 }
4535
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004536 @Override
4537 public void setTestAllowBadWifiUntil(long timeMs) {
4538 enforceSettingsPermission();
4539 if (!Build.isDebuggable()) {
4540 throw new IllegalStateException("Does not support in non-debuggable build");
4541 }
4542
4543 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4544 throw new IllegalArgumentException("It should not exceed "
4545 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4546 }
4547
4548 mHandler.sendMessage(
4549 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
4550 }
4551
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004552 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4553 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4554 " accept=" + accept + " always=" + always);
4555
4556 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4557 if (nai == null) {
4558 // Nothing to do.
4559 return;
4560 }
4561
4562 if (nai.everValidated) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004563 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004564 return;
4565 }
4566
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004567 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08004568 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004569 }
4570
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004571 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4572 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004573 // If network becomes partial connectivity and user already accepted to use this
4574 // network, we should respect the user's option and don't need to popup the
4575 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004576 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004577 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004578 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004579 }
4580
4581 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004582 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004583 }
4584
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004585 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04004586 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004587 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09004588 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04004589 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004590 }
4591
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004592 }
4593
lucaslin2240ef62019-03-12 13:08:03 +08004594 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4595 boolean always) {
4596 if (DBG) {
4597 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4598 + " always=" + always);
4599 }
4600
4601 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4602 if (nai == null) {
4603 // Nothing to do.
4604 return;
4605 }
4606
4607 if (nai.lastValidated) {
4608 // The network validated while the dialog box was up. Take no action.
4609 return;
4610 }
4611
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004612 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4613 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004614 }
4615
4616 // TODO: Use the current design or save the user choice into IpMemoryStore.
4617 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004618 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08004619 }
4620
4621 if (!accept) {
4622 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004623 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08004624 // Tear down the network.
4625 teardownUnneededNetwork(nai);
4626 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08004627 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4628 // result in a partial connectivity result which will be processed by
4629 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08004630 //
4631 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4632 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004633 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08004634 }
4635 }
4636
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004637 private void handleSetAvoidUnvalidated(Network network) {
4638 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4639 if (nai == null || nai.lastValidated) {
4640 // Nothing to do. The network either disconnected or revalidated.
4641 return;
4642 }
4643 if (!nai.avoidUnvalidated) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004644 nai.avoidUnvalidated = true;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004645 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004646 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004647 }
4648 }
4649
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004650 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09004651 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004652 mHandler.sendMessageDelayed(
4653 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4654 PROMPT_UNVALIDATED_DELAY_MS);
4655 }
4656
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004657 @Override
4658 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08004659 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004660 mHandler.post(() -> {
4661 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4662 if (nai == null) return;
4663 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004664 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004665 });
4666 }
4667
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004668 /**
4669 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4670 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004671 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004672 * @param appExtras Bundle to use as intent extras for the captive portal application.
4673 * Must be treated as opaque to avoid preventing the captive portal app to
4674 * update its arguments.
4675 */
4676 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004677 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08004678 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4679 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004680
4681 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4682 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004683 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4684 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004685 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4686
lucaslin75ff7022020-12-17 04:14:35 +08004687 final long token = Binder.clearCallingIdentity();
4688 try {
4689 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4690 } finally {
4691 Binder.restoreCallingIdentity(token);
4692 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004693 }
4694
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004695 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4696 private final Network mNetwork;
4697
4698 private CaptivePortalImpl(Network network) {
4699 mNetwork = network;
4700 }
4701
4702 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004703 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004704 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
4705 enforceSettingsPermission();
4706 }
4707
Chiachang Wang938bfba2020-01-09 13:50:55 +08004708 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004709 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004710 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004711 }
4712
4713 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08004714 public void appRequest(final int request) {
4715 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4716 if (nm == null) return;
4717
4718 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08004719 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09004720 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08004721 }
4722 }
4723
4724 @Nullable
4725 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
4726 // getNetworkAgentInfoForNetwork is thread-safe
4727 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4728 if (nai == null) return null;
4729
4730 // nai.networkMonitor() is thread-safe
4731 return nai.networkMonitor();
4732 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004733 }
4734
Hugo Benichic9048bc2016-09-14 23:23:08 +00004735 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004736 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09004737 }
4738
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09004739 /**
4740 * Return whether the device should maintain continuous, working connectivity by switching away
4741 * from WiFi networks having no connectivity.
4742 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
4743 */
4744 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09004745 if (!checkNetworkStackPermission()) {
4746 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
4747 }
4748 return avoidBadWifi();
4749 }
4750
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004751 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09004752 ensureRunningOnConnectivityServiceThread();
4753 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004754 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09004755 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09004756 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09004757 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
4758 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
4759 for (final NetworkOfferInfo noi : offersToUpdate) {
4760 updateOfferScore(noi.offer);
4761 }
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004762 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004763 }
4764
Erik Kline95ecfee2016-10-02 18:02:14 +09004765 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004766 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004767 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004768 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004769 if (!configRestrict) {
4770 pw.println("Bad Wi-Fi avoidance: unrestricted");
4771 return;
4772 }
4773
4774 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
4775 pw.increaseIndent();
4776 pw.println("Config restrict: " + configRestrict);
4777
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09004778 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004779 String description;
4780 // Can't use a switch statement because strings are legal case labels, but null is not.
4781 if ("0".equals(value)) {
4782 description = "get stuck";
4783 } else if (value == null) {
4784 description = "prompt";
4785 } else if ("1".equals(value)) {
4786 description = "avoid";
4787 } else {
4788 description = value + " (?)";
4789 }
4790 pw.println("User setting: " + description);
4791 pw.println("Network overrides:");
4792 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09004793 for (NetworkAgentInfo nai : networksSortedById()) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004794 if (nai.avoidUnvalidated) {
Chalard Jean49707572019-12-10 21:07:02 +09004795 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004796 }
4797 }
4798 pw.decreaseIndent();
4799 pw.decreaseIndent();
4800 }
4801
paulhu7746e4e2020-06-09 19:07:03 +08004802 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
4803 // unify the method.
4804 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
4805 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
4806 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
4807 return settingsComponent != null
4808 ? settingsComponent.getPackageName() : "com.android.settings";
4809 }
4810
lucaslinb1e8e382019-01-24 15:55:30 +08004811 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004812 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004813 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004814 switch (type) {
4815 case NO_INTERNET:
4816 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004817 // High priority because it is only displayed for explicitly selected networks.
4818 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004819 break;
lucasline117e2e2019-10-22 18:27:33 +08004820 case PRIVATE_DNS_BROKEN:
4821 action = Settings.ACTION_WIRELESS_SETTINGS;
4822 // High priority because we should let user know why there is no internet.
4823 highPriority = true;
4824 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004825 case LOST_INTERNET:
4826 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004827 // High priority because it could help the user avoid unexpected data usage.
4828 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004829 break;
lucaslin2240ef62019-03-12 13:08:03 +08004830 case PARTIAL_CONNECTIVITY:
4831 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004832 // Don't bother the user with a high-priority notification if the network was not
4833 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004834 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08004835 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004836 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004837 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004838 return;
4839 }
4840
4841 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08004842 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08004843 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08004844 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08004845 // Some OEMs have their own Settings package. Thus, need to get the current using
4846 // Settings package name instead of just use default name "com.android.settings".
4847 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
4848 intent.setClassName(settingsPkgName,
4849 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08004850 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004851
paulhu2af50222020-10-11 22:52:27 +08004852 PendingIntent pendingIntent = PendingIntent.getActivity(
4853 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08004854 0 /* requestCode */,
4855 intent,
paulhu2af50222020-10-11 22:52:27 +08004856 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09004857
Serik Beketayevec8ad212020-12-07 22:43:07 -08004858 mNotifier.showNotification(
4859 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004860 }
4861
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004862 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
4863 // Don't prompt if the network is validated, and don't prompt on captive portals
4864 // because we're already prompting the user to sign in.
4865 if (nai.everValidated || nai.everCaptivePortalDetected) {
4866 return false;
4867 }
4868
4869 // If a network has partial connectivity, always prompt unless the user has already accepted
4870 // partial connectivity and selected don't ask again. This ensures that if the device
4871 // automatically connects to a network that has partial Internet access, the user will
4872 // always be able to use it, either because they've already chosen "don't ask again" or
4873 // because we have prompt them.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004874 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004875 return true;
4876 }
4877
4878 // If a network has no Internet access, only prompt if the network was explicitly selected
4879 // and if the user has not already told us to use the network regardless of whether it
4880 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004881 if (nai.networkAgentConfig.explicitlySelected
4882 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004883 return true;
4884 }
4885
4886 return false;
4887 }
4888
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004889 private void handlePromptUnvalidated(Network network) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09004890 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004891 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4892
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09004893 if (nai == null || !shouldPromptUnvalidated(nai)) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004894 return;
4895 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09004896
4897 // Stop automatically reconnecting to this network in the future. Automatically connecting
4898 // to a network that provides no or limited connectivity is not useful, because the user
4899 // cannot use that network except through the notification shown by this method, and the
4900 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004901 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09004902
lucaslin2240ef62019-03-12 13:08:03 +08004903 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
4904 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
4905 // popup the notification immediately when the network is partial connectivity.
4906 if (nai.partialConnectivity) {
lucasline0118ab2019-03-21 11:59:22 +08004907 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08004908 } else {
4909 showNetworkNotification(nai, NotificationType.NO_INTERNET);
4910 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004911 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004912
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004913 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
4914 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09004915 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07004916
lucaslin2240ef62019-03-12 13:08:03 +08004917 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4918 return;
4919 }
4920
4921 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08004922 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09004923 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004924 }
4925
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004926 @Override
4927 public int getMultipathPreference(Network network) {
4928 enforceAccessPermission();
4929
4930 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06004931 if (nai != null && nai.networkCapabilities
4932 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004933 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
4934 }
4935
Aaron Huang9a57acf2020-12-08 10:03:29 +08004936 final NetworkPolicyManager netPolicyManager =
4937 mContext.getSystemService(NetworkPolicyManager.class);
4938
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09004939 final long token = Binder.clearCallingIdentity();
4940 final int networkPreference;
4941 try {
4942 networkPreference = netPolicyManager.getMultipathPreference(network);
4943 } finally {
4944 Binder.restoreCallingIdentity(token);
4945 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08004946 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09004947 return networkPreference;
4948 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09004949 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
4950 }
4951
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004952 @Override
4953 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09004954 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004955 }
4956
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004957 private class InternalHandler extends Handler {
4958 public InternalHandler(Looper looper) {
4959 super(looper);
4960 }
4961
4962 @Override
4963 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004964 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07004965 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004966 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09004967 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07004968 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004969 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07004970 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09004971 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07004972 break;
4973 }
Jason Monka69f1b02013-10-10 14:02:51 -04004974 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08004975 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
4976 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04004977 break;
4978 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09004979 case EVENT_REGISTER_NETWORK_PROVIDER: {
4980 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07004981 break;
4982 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09004983 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
4984 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004985 break;
4986 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09004987 case EVENT_REGISTER_NETWORK_OFFER: {
4988 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
4989 break;
4990 }
4991 case EVENT_UNREGISTER_NETWORK_OFFER: {
4992 final NetworkOfferInfo offer =
4993 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
4994 if (null != offer) {
4995 handleUnregisterNetworkOffer(offer);
4996 }
4997 break;
4998 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004999 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005000 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5001 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5002 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005003 break;
5004 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005005 case EVENT_REGISTER_NETWORK_REQUEST:
5006 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005007 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005008 break;
5009 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005010 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5011 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005012 handleRegisterNetworkRequestWithIntent(msg);
5013 break;
5014 }
Erik Kline155a59a2015-11-25 12:49:38 +09005015 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5016 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5017 handleTimedOutNetworkRequest(nri);
5018 break;
5019 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005020 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5021 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5022 break;
5023 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005024 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005025 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5026 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005027 break;
5028 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005029 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005030 Network network = (Network) msg.obj;
5031 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005032 break;
5033 }
lucaslin2240ef62019-03-12 13:08:03 +08005034 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5035 Network network = (Network) msg.obj;
5036 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5037 toBool(msg.arg2));
5038 break;
5039 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005040 case EVENT_SET_AVOID_UNVALIDATED: {
5041 handleSetAvoidUnvalidated((Network) msg.obj);
5042 break;
5043 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005044 case EVENT_PROMPT_UNVALIDATED: {
5045 handlePromptUnvalidated((Network) msg.obj);
5046 break;
5047 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005048 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5049 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005050 break;
5051 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005052 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005053 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005054 mKeepaliveTracker.handleStartKeepalive(msg);
5055 break;
5056 }
5057 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005058 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005059 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5060 int slot = msg.arg1;
5061 int reason = msg.arg2;
5062 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
5063 break;
5064 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005065 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5066 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5067 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005068 break;
5069 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005070 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5071 handlePrivateDnsSettingsChanged();
5072 break;
dalyk1720e542018-03-05 12:42:22 -05005073 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5074 handlePrivateDnsValidationUpdate(
5075 (PrivateDnsValidationUpdate) msg.obj);
5076 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005077 case EVENT_UID_BLOCKED_REASON_CHANGED:
5078 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005079 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005080 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5081 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5082 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005083 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005084 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5085 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005086 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005087 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005088 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005089 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005090 final Pair<List<ProfileNetworkPreferenceList.Preference>,
5091 IOnCompleteListener> arg =
5092 (Pair<List<ProfileNetworkPreferenceList.Preference>,
5093 IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005094 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005095 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005096 }
lucaslin1193a5d2021-01-21 02:04:15 +08005097 case EVENT_REPORT_NETWORK_ACTIVITY:
5098 mNetworkActivityTracker.handleReportNetworkActivity();
5099 break;
paulhu51f77dc2021-06-07 02:34:20 +00005100 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5101 handleMobileDataPreferredUidsChanged();
5102 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005103 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5104 final long timeMs = ((Long) msg.obj).longValue();
5105 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5106 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005107 }
5108 }
5109 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005110
Lorenzo Colittid6459092016-07-04 12:55:44 +09005111 @Override
markchien5776f962019-12-16 20:15:20 +08005112 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005113 public int getLastTetherError(String iface) {
markchien5776f962019-12-16 20:15:20 +08005114 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5115 Context.TETHERING_SERVICE);
5116 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005117 }
5118
Lorenzo Colittid6459092016-07-04 12:55:44 +09005119 @Override
markchien5776f962019-12-16 20:15:20 +08005120 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005121 public String[] getTetherableIfaces() {
markchien5776f962019-12-16 20:15:20 +08005122 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5123 Context.TETHERING_SERVICE);
5124 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005125 }
5126
Lorenzo Colittid6459092016-07-04 12:55:44 +09005127 @Override
markchien5776f962019-12-16 20:15:20 +08005128 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005129 public String[] getTetheredIfaces() {
markchien5776f962019-12-16 20:15:20 +08005130 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5131 Context.TETHERING_SERVICE);
5132 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005133 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005134
markchien5776f962019-12-16 20:15:20 +08005135
Lorenzo Colittid6459092016-07-04 12:55:44 +09005136 @Override
markchien5776f962019-12-16 20:15:20 +08005137 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005138 public String[] getTetheringErroredIfaces() {
markchien5776f962019-12-16 20:15:20 +08005139 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5140 Context.TETHERING_SERVICE);
5141
5142 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005143 }
5144
Lorenzo Colittid6459092016-07-04 12:55:44 +09005145 @Override
markchien5776f962019-12-16 20:15:20 +08005146 @Deprecated
5147 public String[] getTetherableUsbRegexs() {
5148 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5149 Context.TETHERING_SERVICE);
5150
5151 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005152 }
5153
Udam Saini8f7d6a72017-06-07 12:06:28 -07005154 @Override
markchien5776f962019-12-16 20:15:20 +08005155 @Deprecated
5156 public String[] getTetherableWifiRegexs() {
5157 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5158 Context.TETHERING_SERVICE);
5159 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005160 }
5161
Robert Greenwalte0b00512014-07-02 09:59:16 -07005162 // Called when we lose the default network and have no replacement yet.
5163 // This will automatically be cleared after X seconds or a new default network
5164 // becomes CONNECTED, whichever happens first. The timer is started by the
5165 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005166 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005167 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005168 if (mNetTransitionWakeLock.isHeld()) {
5169 return;
5170 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005171 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005172 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5173 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005174 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005175 mWakelockLogs.log("ACQUIRE for " + forWhom);
5176 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005177 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005178 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005179 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005180 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005181
Hugo Benichi471b62a2017-03-30 23:18:10 +09005182 // Called when we gain a new default network to release the network transition wakelock in a
5183 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5184 // message is cancelled.
5185 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005186 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005187 if (!mNetTransitionWakeLock.isHeld()) {
5188 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005189 }
5190 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005191 // Cancel self timeout on wakelock hold.
5192 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5193 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5194 mHandler.sendMessageDelayed(msg, 1000);
5195 }
5196
5197 // Called when either message of ensureNetworkTransitionWakelock or
5198 // scheduleReleaseNetworkTransitionWakelock is processed.
5199 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5200 String event = eventName(eventId);
5201 synchronized (this) {
5202 if (!mNetTransitionWakeLock.isHeld()) {
5203 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005204 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005205 return;
5206 }
5207 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005208 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5209 mTotalWakelockDurationMs += lockDuration;
5210 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5211 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005212 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005213 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005214 }
5215
Robert Greenwalt986c7412010-09-08 15:24:47 -07005216 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005217 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005218 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005219 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005220 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005221 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005222 }
5223
Lorenzo Colittid6459092016-07-04 12:55:44 +09005224 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005225 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005226 enforceAccessPermission();
5227 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005228 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005229 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005230
5231 final NetworkAgentInfo nai;
5232 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005233 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005234 } else {
5235 nai = getNetworkAgentInfoForNetwork(network);
5236 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005237
5238 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005239 mHandler.obtainMessage(
5240 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005241 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005242
Hugo Benichid6b510a2017-04-06 17:22:18 +09005243 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005244 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005245 if (nai == null
5246 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005247 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005248 return;
5249 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005250 // Revalidate if the app report does not match our current validated state.
Hugo Benichie9d321b2017-04-06 16:01:44 +09005251 if (hasConnectivity == nai.lastValidated) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005252 mConnectivityDiagnosticsHandler.sendMessage(
5253 mConnectivityDiagnosticsHandler.obtainMessage(
5254 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5255 new ReportedNetworkConnectivityInfo(
5256 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005257 return;
5258 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005259 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005260 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005261 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005262 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005263 // Validating a network that has not yet connected could result in a call to
5264 // rematchNetworkAndRequests() which is not meant to work on such networks.
5265 if (!nai.everConnected) {
5266 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005267 }
paulhu7aeba372020-12-30 00:42:19 +08005268 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5269 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005270 return;
5271 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005272
5273 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5274 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5275 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5276 // completed.
5277 mConnectivityDiagnosticsHandler.sendMessage(
5278 mConnectivityDiagnosticsHandler.obtainMessage(
5279 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5280 new ReportedNetworkConnectivityInfo(
5281 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005282 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005283 }
5284
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005285 // TODO: call into netd.
5286 private boolean queryUserAccess(int uid, Network network) {
5287 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5288 if (nai == null) return false;
5289
5290 // Any UID can use its default network.
5291 if (nai == getDefaultNetworkForUid(uid)) return true;
5292
5293 // Privileged apps can use any network.
5294 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5295 return true;
5296 }
5297
5298 // An unprivileged UID can use a VPN iff the VPN applies to it.
5299 if (nai.isVPN()) {
5300 return nai.networkCapabilities.appliesToUid(uid);
5301 }
5302
5303 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5304 // sockets, i.e., if it is the owner.
5305 final NetworkAgentInfo vpn = getVpnForUid(uid);
5306 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5307 && uid != vpn.networkCapabilities.getOwnerUid()) {
5308 return false;
5309 }
5310
5311 // The UID's permission must be at least sufficient for the network. Since the restricted
5312 // permission was already checked above, that just leaves background networks.
5313 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5314 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5315 }
5316
5317 // Unrestricted network. Anyone gets to use it.
5318 return true;
5319 }
5320
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005321 /**
5322 * Returns information about the proxy a certain network is using. If given a null network, it
5323 * it will return the proxy for the bound network for the caller app or the default proxy if
5324 * none.
5325 *
5326 * @param network the network we want to get the proxy information for.
5327 * @return Proxy information if a network has a proxy configured, or otherwise null.
5328 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005329 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005330 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005331 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005332 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005333 if (network == null) {
5334 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005335 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005336 true);
5337 if (activeNetwork == null) {
5338 return null;
5339 }
5340 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005341 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005342 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5343 // caller may not have.
5344 return getLinkPropertiesProxyInfo(network);
5345 }
5346 // No proxy info available if the calling UID does not have network access.
5347 return null;
5348 }
5349
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005350
5351 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005352 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5353 if (nai == null) return null;
5354 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005355 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5356 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005357 }
5358 }
5359
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005360 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005361 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhudf23d662021-01-25 18:53:17 +08005362 PermissionUtils.enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005363 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005364 }
5365
Chalard Jean777e2e52018-06-07 18:02:37 +09005366 @Override
5367 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005368 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005369 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005370 }
5371
Jason Monk4d5e20f2014-04-25 15:00:09 -04005372 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005373 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005374 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005375 proxy = null;
5376 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005377 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005378 }
5379
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005380 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5381 // when any network changes proxy.
5382 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5383 // multi-network world where an app might be bound to a non-default network.
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005384 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
Paul Jensenc0618a62014-12-10 15:12:18 -05005385 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5386 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5387
Chalard Jean7d97afc2018-06-07 17:41:29 +09005388 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005389 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005390 }
5391 }
5392
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005393 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005394 final private HashMap<Uri, Integer> mUriEventMap;
5395 final private Context mContext;
5396 final private Handler mHandler;
5397
5398 SettingsObserver(Context context, Handler handler) {
5399 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005400 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005401 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005402 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005403 }
5404
Erik Kline05f2b402015-04-30 12:58:40 +09005405 void observe(Uri uri, int what) {
5406 mUriEventMap.put(uri, what);
5407 final ContentResolver resolver = mContext.getContentResolver();
5408 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005409 }
5410
5411 @Override
5412 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005413 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005414 }
5415
5416 @Override
5417 public void onChange(boolean selfChange, Uri uri) {
5418 final Integer what = mUriEventMap.get(uri);
5419 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005420 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005421 } else {
5422 loge("No matching event to send for URI=" + uri);
5423 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005424 }
5425 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005426
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005427 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005428 Log.d(TAG, s);
5429 }
5430
5431 private static void logw(String s) {
5432 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005433 }
5434
Daniel Brightf9e945b2020-06-15 16:10:01 -07005435 private static void logwtf(String s) {
5436 Log.wtf(TAG, s);
5437 }
5438
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005439 private static void logwtf(String s, Throwable t) {
5440 Log.wtf(TAG, s, t);
5441 }
5442
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005443 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005444 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005445 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005446
Hugo Benichi39621362017-02-11 17:04:43 +09005447 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005448 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005449 }
5450
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005451 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005452 * Return the information of all ongoing VPNs.
5453 *
5454 * <p>This method is used to update NetworkStatsService.
5455 *
5456 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08005457 */
junyulai2050bed2021-01-23 09:46:34 +08005458 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005459 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09005460 if (mLockdownEnabled) {
5461 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08005462 }
junyulai2050bed2021-01-23 09:46:34 +08005463 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005464 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08005465 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005466 if (info != null) {
5467 infoList.add(info);
5468 }
5469 }
junyulai2050bed2021-01-23 09:46:34 +08005470 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08005471 }
5472
5473 /**
5474 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00005475 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08005476 */
junyulai2050bed2021-01-23 09:46:34 +08005477 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005478 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08005479 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5480 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09005481 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5482 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5483 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08005484 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5485 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00005486 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00005487 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08005488 }
5489 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005490
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005491 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005492
5493 List<String> interfaces = new ArrayList<>();
5494 for (Network network : underlyingNetworks) {
5495 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5496 if (underlyingNai == null) continue;
5497 LinkProperties lp = underlyingNai.linkProperties;
5498 for (String iface : lp.getAllInterfaceNames()) {
5499 if (!TextUtils.isEmpty(iface)) {
5500 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00005501 }
5502 }
Benedict Wong34857f82019-06-12 17:46:15 +00005503 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005504
5505 if (interfaces.isEmpty()) return null;
5506
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005507 // Must be non-null or NetworkStatsService will crash.
5508 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5509 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08005510 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08005511 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005512
junyulai2050bed2021-01-23 09:46:34 +08005513 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5514 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08005515 }
5516
James Mattisd31bdfa2020-12-23 16:37:26 -08005517 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08005518 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5519 Network[] underlyingNetworks) {
5520 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005521 if (underlyingNetworks == null && defaultNetwork != null) {
5522 // null underlying networks means to track the default.
5523 underlyingNetworks = new Network[] { defaultNetwork };
5524 }
5525 return underlyingNetworks;
5526 }
5527
5528 // Returns true iff |network| is an underlying network of |nai|.
5529 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5530 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5531 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09005532 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08005533 final Network[] underlying = underlyingNetworksOrDefault(
5534 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005535 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005536 }
5537
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005538 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005539 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005540 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005541 * When underlying networks change, such networks may have to update capabilities to reflect
5542 * things like the metered bit, their transports, and so on. The capabilities are calculated
5543 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005544 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005545 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005546 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005547 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005548 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005549 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005550 }
5551 }
5552 }
5553
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005554 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5555 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5556 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5557 // a VPN is not up.
5558 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5559 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5560 for (UidRange range : blockedUidRanges) {
5561 if (range.contains(uid)) return true;
5562 }
5563 return false;
5564 }
5565
5566 @Override
5567 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08005568 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005569 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5570 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5571 }
5572
5573 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5574 if (DBG) {
5575 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5576 + Arrays.toString(ranges));
5577 }
5578 // Cannot use a Set since the list of UID ranges might contain duplicates.
5579 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5580 for (int i = 0; i < ranges.length; i++) {
5581 if (requireVpn) {
5582 newVpnBlockedUidRanges.add(ranges[i]);
5583 } else {
5584 newVpnBlockedUidRanges.remove(ranges[i]);
5585 }
5586 }
5587
5588 try {
5589 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5590 } catch (RemoteException | ServiceSpecificException e) {
5591 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5592 + Arrays.toString(ranges) + "): netd command failed: " + e);
5593 }
5594
5595 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5596 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00005597 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5598 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005599 }
5600
5601 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5602 }
5603
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07005604 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005605 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08005606 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005607 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01005608 }
5609
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005610 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5611 return mLockdownEnabled
5612 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5613 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00005614 }
5615
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005616 private NetworkAgentInfo getLegacyLockdownNai() {
5617 if (!mLockdownEnabled) {
5618 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005619 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005620 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005621 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5622 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005623
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005624 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005625 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5626 // a local variable. There is no need to make a copy because its contents cannot change.
5627 final Network[] underlying = nai.declaredUnderlyingNetworks;
5628 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005629 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005630 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005631
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005632 // The legacy lockdown VPN always uses the default network.
5633 // If the VPN's underlying network is no longer the current default network, it means that
5634 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005635 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5636 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005637 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005638 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005639 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005640 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005641
5642 return nai;
5643 };
5644
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005645 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5646 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5647 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005648 private DetailedState getLegacyLockdownState(DetailedState origState) {
5649 if (origState != DetailedState.CONNECTED) {
5650 return origState;
5651 }
5652 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5653 ? DetailedState.CONNECTING
5654 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005655 }
5656
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005657 private void filterForLegacyLockdown(NetworkInfo ni) {
5658 if (!mLockdownEnabled || !ni.isConnected()) return;
5659 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5660 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5661 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5662 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5663 // network, this time with a state of CONNECTED.
5664 //
5665 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5666 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5667 // is not too far off the truth, since an always-on VPN, when not connected, is always
5668 // trying to reconnect.
5669 if (getLegacyLockdownNai() == null) {
5670 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5671 }
5672 }
5673
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005674 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005675 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04005676 String action) {
paulhu8e96a752019-08-12 16:25:11 +08005677 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09005678 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5679 return;
5680 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04005681 final long ident = Binder.clearCallingIdentity();
5682 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09005683 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09005684 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09005685 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04005686 } finally {
5687 Binder.restoreCallingIdentity(ident);
5688 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07005689 }
Wink Savillecb117d32013-08-29 14:57:08 -07005690
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005691 @Override
5692 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01005693 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005694 final long ident = Binder.clearCallingIdentity();
5695 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005696 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09005697 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07005698 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5699 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08005700 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07005701 } finally {
5702 Binder.restoreCallingIdentity(ident);
5703 }
5704 }
5705
James Mattis02220e22021-03-13 19:27:21 -08005706 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005707 mPermissionMonitor.onUserAdded(user);
James Mattisae9aeb02021-03-01 17:09:11 -08005708 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5709 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5710 }
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005711 }
5712
James Mattis02220e22021-03-13 19:27:21 -08005713 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005714 mPermissionMonitor.onUserRemoved(user);
Chalard Jean0f57a492021-03-09 21:09:20 +09005715 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005716 handleSetProfileNetworkPreference(
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08005717 List.of(new ProfileNetworkPreferenceList.Preference(user, null, true)),
Chalard Jean0f57a492021-03-09 21:09:20 +09005718 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08005719 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5720 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5721 }
junyulaid91e7052020-08-28 13:44:33 +08005722 }
5723
James Mattis02220e22021-03-13 19:27:21 -08005724 private void onPackageChanged(@NonNull final String packageName) {
5725 // This is necessary in case a package is added or removed, but also when it's replaced to
5726 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5727 // as one in the preferences, then it should follow the same routing as that other package,
5728 // which means updating the rules is never to be needed in this case (whether it joins or
5729 // leaves a UID with a preference).
5730 if (isMappedInOemNetworkPreference(packageName)) {
5731 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5732 }
5733 }
5734
5735 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005736 @Override
5737 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09005738 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005739 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005740 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08005741
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005742 // User should be filled for below intents, check the existence.
5743 if (user == null) {
5744 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5745 return;
5746 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005747
Lorenzo Colitticd675292021-02-04 17:32:07 +09005748 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005749 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07005750 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09005751 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09005752 } else {
junyulaid91e7052020-08-28 13:44:33 +08005753 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07005754 }
5755 }
5756 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07005757
James Mattis02220e22021-03-13 19:27:21 -08005758 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5759 @Override
5760 public void onReceive(Context context, Intent intent) {
5761 ensureRunningOnConnectivityServiceThread();
5762 switch (intent.getAction()) {
5763 case Intent.ACTION_PACKAGE_ADDED:
5764 case Intent.ACTION_PACKAGE_REMOVED:
5765 case Intent.ACTION_PACKAGE_REPLACED:
5766 onPackageChanged(intent.getData().getSchemeSpecificPart());
5767 break;
5768 default:
5769 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5770 }
5771 }
5772 };
5773
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005774 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005775 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005776
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005777 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005778 public final String name;
5779 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005780 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005781 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005782
lifraf3a3492021-03-10 13:58:14 +08005783 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5784 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005785 this.name = name;
5786 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005787 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005788 mDeathRecipient = deathRecipient;
5789
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005790 if (mDeathRecipient == null) {
5791 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005792 }
5793 }
5794
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005795 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09005796 try {
5797 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5798 } catch (RemoteException e) {
5799 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09005800 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09005801 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005802 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005803
James Mattis4fce5d12020-11-12 15:53:42 -08005804 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
5805 for (int i = 0; i < requests.size(); i++) {
5806 ensureNetworkRequestHasType(requests.get(i));
5807 }
5808 }
5809
Lorenzo Colitti70964d32016-07-05 01:22:13 +09005810 private void ensureNetworkRequestHasType(NetworkRequest request) {
5811 if (request.type == NetworkRequest.Type.NONE) {
5812 throw new IllegalArgumentException(
5813 "All NetworkRequests in ConnectivityService must have a type");
5814 }
5815 }
5816
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005817 /**
5818 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08005819 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07005820 */
James Mattis258ea3c2020-11-15 15:04:40 -08005821 @VisibleForTesting
5822 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08005823 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
5824 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08005825 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08005826
James Mattisa076c532020-12-02 14:12:41 -08005827 // mSatisfier and mActiveRequest rely on one another therefore set them together.
5828 void setSatisfier(
5829 @Nullable final NetworkAgentInfo satisfier,
5830 @Nullable final NetworkRequest activeRequest) {
5831 mSatisfier = satisfier;
5832 mActiveRequest = activeRequest;
5833 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005834
James Mattisd31bdfa2020-12-23 16:37:26 -08005835 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005836 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09005837 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08005838 private NetworkAgentInfo mSatisfier;
5839 NetworkAgentInfo getSatisfier() {
5840 return mSatisfier;
5841 }
5842
5843 // The request in mRequests assigned to a network agent. This is null if none of the
5844 // requests in mRequests can be satisfied. This member has the constraint of only being
5845 // accessible on the handler thread.
5846 @Nullable
5847 private NetworkRequest mActiveRequest;
5848 NetworkRequest getActiveRequest() {
5849 return mActiveRequest;
5850 }
5851
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005852 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08005853 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08005854 @Nullable
5855 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005856
5857 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08005858 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005859 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005860 final int mPid;
5861 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08005862 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005863 @Nullable
5864 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005865
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005866 // Counter keeping track of this NRI.
5867 final PerUidCounter mPerUidCounter;
5868
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005869 // Effective UID of this request. This is different from mUid when a privileged process
5870 // files a request on behalf of another UID. This UID is used to determine blocked status,
5871 // UID matching, and so on. mUid above is used for permission checks and to enforce the
5872 // maximum limit of registered callbacks per UID.
5873 final int mAsUid;
5874
paulhu48291862021-07-14 14:53:57 +08005875 // Preference order of this request.
5876 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08005877
James Mattis3ce3d3c2021-02-09 18:18:28 -08005878 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
5879 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
5880 // maintained for keying off of. This is only a concern when the original nri
5881 // mNetworkRequests changes which happens currently for apps that register callbacks to
5882 // track the default network. In those cases, the nri is updated to have mNetworkRequests
5883 // that match the per-app default nri that currently tracks the calling app's uid so that
5884 // callbacks are fired at the appropriate time. When the callbacks fire,
5885 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
5886 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
5887 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
5888 @NonNull
5889 private final NetworkRequest mNetworkRequestForCallback;
5890 NetworkRequest getNetworkRequestForCallback() {
5891 return mNetworkRequestForCallback;
5892 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005893
James Mattisd31bdfa2020-12-23 16:37:26 -08005894 /**
5895 * Get the list of UIDs this nri applies to.
5896 */
5897 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00005898 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08005899 // networkCapabilities.getUids() returns a defensive copy.
5900 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00005901 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
5902 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08005903 }
5904
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005905 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
5906 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08005907 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08005908 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08005909 }
5910
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005911 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08005912 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08005913 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005914 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08005915 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08005916 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005917 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08005918 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005919 mBinder = null;
5920 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005921 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005922 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005923 mPerUidCounter = getRequestCounter(this);
5924 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005925 /**
5926 * Location sensitive data not included in pending intent. Only included in
5927 * {@link NetworkCallback}.
5928 */
5929 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005930 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08005931 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005932 }
5933
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005934 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08005935 @Nullable final IBinder binder,
5936 @NetworkCallback.Flag int callbackFlags,
5937 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005938 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
5939 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08005940 }
5941
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005942 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08005943 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08005944 @Nullable final IBinder binder,
5945 @NetworkCallback.Flag int callbackFlags,
5946 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005947 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08005948 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08005949 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08005950 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08005951 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005952 mBinder = binder;
5953 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005954 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005955 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005956 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005957 mPerUidCounter = getRequestCounter(this);
5958 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005959 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08005960 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08005961 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07005962 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005963 }
5964
James Mattis3ce3d3c2021-02-09 18:18:28 -08005965 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
5966 @NonNull final List<NetworkRequest> r) {
5967 super();
5968 ensureAllNetworkRequestsHaveType(r);
5969 mRequests = initializeRequests(r);
5970 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005971 final NetworkAgentInfo satisfier = nri.getSatisfier();
5972 if (null != satisfier) {
5973 // If the old NRI was satisfied by an NAI, then it may have had an active request.
5974 // The active request is necessary to figure out what callbacks to send, in
5975 // particular then a network updates its capabilities.
5976 // As this code creates a new NRI with a new set of requests, figure out which of
5977 // the list of requests should be the active request. It is always the first
5978 // request of the list that can be satisfied by the satisfier since the order of
5979 // requests is a priority order.
5980 // Note even in the presence of a satisfier there may not be an active request,
5981 // when the satisfier is the no-service network.
5982 NetworkRequest activeRequest = null;
5983 for (final NetworkRequest candidate : r) {
5984 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
5985 activeRequest = candidate;
5986 break;
5987 }
5988 }
5989 setSatisfier(satisfier, activeRequest);
5990 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08005991 mMessenger = nri.mMessenger;
5992 mBinder = nri.mBinder;
5993 mPid = nri.mPid;
5994 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09005995 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08005996 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09005997 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09005998 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08005999 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006000 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006001 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006002 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006003 }
6004
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006005 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006006 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006007 }
6008
paulhue9913722021-05-26 15:19:20 +08006009 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006010 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006011 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006012 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006013 }
6014
James Mattis2516da32021-01-31 17:06:19 -08006015 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6016 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6017 // false.
6018 boolean isBeingSatisfied() {
6019 return (null != mSatisfier && null != mActiveRequest);
6020 }
6021
James Mattis3d229892020-11-16 16:46:28 -08006022 boolean isMultilayerRequest() {
6023 return mRequests.size() > 1;
6024 }
6025
James Mattis45d81842021-01-10 14:24:24 -08006026 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6027 // Creating a defensive copy to prevent the sender from modifying the list being
6028 // reflected in the return value of this method.
6029 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006030 return Collections.unmodifiableList(tempRequests);
6031 }
6032
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006033 void decrementRequestCount() {
6034 mPerUidCounter.decrementCount(mUid);
6035 }
6036
James Mattisb1392002021-03-31 13:57:52 -07006037 void linkDeathRecipient() {
6038 if (null != mBinder) {
6039 try {
6040 mBinder.linkToDeath(this, 0);
6041 } catch (RemoteException e) {
6042 binderDied();
6043 }
6044 }
6045 }
6046
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006047 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006048 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006049 try {
6050 mBinder.unlinkToDeath(this, 0);
6051 } catch (NoSuchElementException e) {
6052 // Temporary workaround for b/194394697 pending analysis of additional logs
6053 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6054 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006055 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006056 }
6057
paulhu48291862021-07-14 14:53:57 +08006058 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6059 // Compare two preference orders.
6060 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006061 }
6062
paulhu48291862021-07-14 14:53:57 +08006063 int getPreferenceOrderForNetd() {
6064 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6065 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6066 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006067 }
paulhu48291862021-07-14 14:53:57 +08006068 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006069 }
6070
James Mattis4fce5d12020-11-12 15:53:42 -08006071 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006072 public void binderDied() {
6073 log("ConnectivityService NetworkRequestInfo binderDied(" +
Chalard Jean524f0b12021-10-25 21:11:56 +09006074 "uid/pid:" + mUid + "/" + mPid + ", " + mRequests + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09006075 // As an immutable collection, mRequests cannot change by the time the
6076 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6077 // is acceptable. Use handleReleaseNetworkRequest and not directly
6078 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6079 // the app already unregistered the request.
6080 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6081 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006082 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006083
James Mattis4fce5d12020-11-12 15:53:42 -08006084 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006085 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006086 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6087 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006088 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006089 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006090 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006091 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006092 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006093 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006094 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006095 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006096 }
6097
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006098 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
6099 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
6100 if (badCapability != null) {
6101 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenee52d232015-06-16 15:11:58 -04006102 }
6103 }
6104
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006105 // This checks that the passed capabilities either do not request a
6106 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006107 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006108 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006109 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006110 throw new SecurityException("Insufficient permissions to request a specific SSID");
6111 }
paulhu1a407652019-03-22 16:35:06 +08006112
6113 if (nc.hasSignalStrength()
6114 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6115 throw new SecurityException(
6116 "Insufficient permissions to request a specific signal strength");
6117 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006118 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006119
junyulai2217bec2021-04-14 23:33:31 +08006120 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006121 enforceNetworkFactoryPermission();
6122 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006123 }
6124
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006125 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006126 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006127 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006128 // mNetworkRequests may contain the same value multiple times in case of
6129 // multilayer requests. It won't matter in this case because the thresholds
6130 // will then be the same and be deduplicated as they enter the `thresholds` set.
6131 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006132 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6133 for (final NetworkRequest req : nri.mRequests) {
6134 if (req.networkCapabilities.hasSignalStrength()
6135 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6136 thresholds.add(req.networkCapabilities.getSignalStrength());
6137 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006138 }
6139 }
6140 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006141 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006142 }
6143
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006144 private void updateSignalStrengthThresholds(
6145 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006146 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006147
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006148 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006149 String detail;
6150 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6151 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6152 } else {
6153 detail = reason;
6154 }
6155 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006156 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006157 }
6158
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006159 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006160 }
6161
Etan Cohen1b6d4182017-04-03 17:42:34 -07006162 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
6163 if (nc == null) {
6164 return;
6165 }
6166 NetworkSpecifier ns = nc.getNetworkSpecifier();
6167 if (ns == null) {
6168 return;
6169 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006170 if (ns instanceof MatchAllNetworkSpecifier) {
6171 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6172 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006173 }
6174
lucasline117e2e2019-10-22 18:27:33 +08006175 private void ensureValid(NetworkCapabilities nc) {
6176 ensureValidNetworkSpecifier(nc);
6177 if (nc.isPrivateDnsBroken()) {
6178 throw new IllegalArgumentException("Can't request broken private DNS");
6179 }
6180 }
6181
Chiachang Wang3bc52762021-11-25 14:17:57 +08006182 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6183 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006184 private boolean isTargetSdkAtleast(int version, int callingUid,
6185 @NonNull String callingPackageName) {
6186 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006187 final PackageManager pm =
6188 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006189 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006190 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006191 if (callingVersion < version) return false;
6192 } catch (PackageManager.NameNotFoundException e) { }
6193 return true;
6194 }
6195
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006196 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006197 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006198 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006199 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006200 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006201 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006202 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6203 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006204 throw new SecurityException("Insufficient permissions to specify legacy type");
6205 }
markchienfac84a22020-03-18 21:16:15 +08006206 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006207 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006208 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006209 // Privileged callers can track the default network of another UID by passing in a UID.
6210 if (asUid != Process.INVALID_UID) {
6211 enforceSettingsPermission();
6212 } else {
6213 asUid = callingUid;
6214 }
junyulaiad010792021-01-11 16:53:38 +08006215 final NetworkRequest.Type reqType;
6216 try {
6217 reqType = NetworkRequest.Type.values()[reqTypeInt];
6218 } catch (ArrayIndexOutOfBoundsException e) {
6219 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6220 }
6221 switch (reqType) {
6222 case TRACK_DEFAULT:
6223 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006224 // is unused and will be replaced by ones appropriate for the UID (usually, the
6225 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006226 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006227 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006228 enforceAccessPermission();
6229 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006230 case TRACK_SYSTEM_DEFAULT:
6231 enforceSettingsPermission();
6232 networkCapabilities = new NetworkCapabilities(defaultNc);
6233 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006234 case BACKGROUND_REQUEST:
6235 enforceNetworkStackOrSettingsPermission();
6236 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006237 case REQUEST:
6238 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6239 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6240 callingAttributionTag);
6241 // TODO: this is incorrect. We mark the request as metered or not depending on
6242 // the state of the app when the request is filed, but we never change the
6243 // request if the app changes network state. http://b/29964605
6244 enforceMeteredApnPolicy(networkCapabilities);
6245 break;
junyulai1b1c8742021-03-12 20:05:08 +08006246 case LISTEN_FOR_BEST:
6247 enforceAccessPermission();
6248 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6249 break;
junyulaiad010792021-01-11 16:53:38 +08006250 default:
6251 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006252 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006253 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006254 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006255 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006256
junyulai1b1c8742021-03-12 20:05:08 +08006257 // Enforce FOREGROUND if the caller does not have permission to use background network.
6258 if (reqType == LISTEN_FOR_BEST) {
6259 restrictBackgroundRequestForCaller(networkCapabilities);
6260 }
6261
6262 // Set the UID range for this request to the single UID of the requester, unless the
6263 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006264 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6265 // are no visible methods to set the UIDs, an app could use reflection to try and get
6266 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006267 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006268 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6269 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006270
Etan Cohen85000162017-02-05 10:42:27 -08006271 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006272 throw new IllegalArgumentException("Bad timeout specified");
6273 }
lucasline117e2e2019-10-22 18:27:33 +08006274 ensureValid(networkCapabilities);
Etan Cohen9786d922015-11-18 10:56:15 -08006275
James Mattis3ce3d3c2021-02-09 18:18:28 -08006276 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006277 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006278 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006279 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006280 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006281 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006282
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006283 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6284 // copied from the default request above. (This is necessary to ensure, for example, that
6285 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6286 // changes don't alter request matching.
6287 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6288 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006289 throw new IllegalStateException(
6290 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006291 + networkCapabilities + " vs. " + defaultNc);
6292 }
6293
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006294 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006295 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006296 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006297 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006298 }
6299 return networkRequest;
6300 }
6301
James Mattis3ce3d3c2021-02-09 18:18:28 -08006302 /**
6303 * Return the nri to be used when registering a network request. Specifically, this is used with
6304 * requests registered to track the default request. If there is currently a per-app default
6305 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6306 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006307 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6308 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006309 * @param nr the network request for the nri.
6310 * @param msgr the messenger for the nri.
6311 * @param binder the binder for the nri.
6312 * @param callingAttributionTag the calling attribution tag for the nri.
6313 * @return the nri to register.
6314 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006315 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006316 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006317 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006318 @Nullable String callingAttributionTag) {
6319 final List<NetworkRequest> requests;
6320 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6321 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006322 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006323 } else {
6324 requests = Collections.singletonList(nr);
6325 }
Roshan Pius951c0032020-12-22 15:10:42 -08006326 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006327 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006328 }
6329
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006330 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
6331 String callingPackageName, String callingAttributionTag) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006332 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichibd0cc762016-07-19 15:59:27 +09006333 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006334 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006335 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006336 }
6337 }
6338
fenglu3f357402015-03-20 11:29:56 -07006339 @Override
fenglub00f4882015-04-21 17:12:05 -07006340 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006341 enforceAccessPermission();
6342 NetworkAgentInfo nai = null;
6343 if (network == null) {
6344 return false;
6345 }
6346 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006347 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006348 }
6349 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006350 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006351 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006352 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006353 Integer uidReqs = mBandwidthRequests.get(uid);
6354 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006355 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006356 }
6357 mBandwidthRequests.put(uid, ++uidReqs);
6358 }
fenglu3f357402015-03-20 11:29:56 -07006359 return true;
6360 }
6361 return false;
6362 }
6363
Felipe Leme0a5ae422016-06-20 16:36:29 -07006364 private boolean isSystem(int uid) {
6365 return uid < Process.FIRST_APPLICATION_UID;
6366 }
fenglu3f357402015-03-20 11:29:56 -07006367
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006368 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006369 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006370 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006371 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006372 return;
6373 }
Hugo Benichi39621362017-02-11 17:04:43 +09006374 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6375 // Policy already enforced.
6376 return;
6377 }
paulhuaf50d7d2020-12-24 19:47:34 +08006378 final long ident = Binder.clearCallingIdentity();
6379 try {
6380 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6381 // If UID is restricted, don't allow them to bring up metered APNs.
6382 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6383 }
6384 } finally {
6385 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006386 }
6387 }
6388
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006389 @Override
6390 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006391 PendingIntent operation, @NonNull String callingPackageName,
6392 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006393 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006394 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006395 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006396 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6397 callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006398 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006399 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006400 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006401 Binder.getCallingPid(), callingUid, callingPackageName);
Etan Cohen1b6d4182017-04-03 17:42:34 -07006402 ensureValidNetworkSpecifier(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006403 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6404 callingUid, callingPackageName);
Etan Cohen89134542017-04-03 12:17:51 -07006405
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006406 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006407 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006408 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6409 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006410 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006411 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6412 nri));
6413 return networkRequest;
6414 }
6415
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006416 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6417 mHandler.sendMessageDelayed(
6418 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006419 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006420 }
6421
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006422 @Override
6423 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006424 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006425 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006426 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006427 }
6428
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006429 // In order to implement the compatibility measure for pre-M apps that call
6430 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6431 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6432 // This ensures it has permission to do so.
6433 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6434 if (nc == null) {
6435 return false;
6436 }
6437 int[] transportTypes = nc.getTransportTypes();
6438 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6439 return false;
6440 }
6441 try {
6442 mContext.enforceCallingOrSelfPermission(
6443 android.Manifest.permission.ACCESS_WIFI_STATE,
6444 "ConnectivityService");
6445 } catch (SecurityException e) {
6446 return false;
6447 }
6448 return true;
6449 }
6450
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006451 @Override
6452 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08006453 Messenger messenger, IBinder binder,
6454 @NetworkCallback.Flag int callbackFlags,
6455 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006456 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006457 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6458 enforceAccessPermission();
6459 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006460
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006461 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006462 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006463 Binder.getCallingPid(), callingUid, callingPackageName);
6464 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09006465 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6466 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6467 // onLost and onAvailable callbacks when networks move in and out of the background.
6468 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6469 // can't request networks.
6470 restrictBackgroundRequestForCaller(nc);
lucasline117e2e2019-10-22 18:27:33 +08006471 ensureValid(nc);
Etan Cohen89134542017-04-03 12:17:51 -07006472
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006473 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006474 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08006475 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006476 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08006477 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006478 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006479
6480 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6481 return networkRequest;
6482 }
6483
6484 @Override
6485 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08006486 PendingIntent operation, @NonNull String callingPackageName,
6487 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006488 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006489 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04006490 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6491 enforceAccessPermission();
6492 }
lucasline117e2e2019-10-22 18:27:33 +08006493 ensureValid(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006494 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006495 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006496 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006497 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006498
6499 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006500 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006501 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6502 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006503 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04006504
WeiZhang1cc3f172021-06-03 19:02:04 -05006505 mHandler.sendMessage(mHandler.obtainMessage(
6506 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006507 }
6508
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006509 /** Returns the next Network provider ID. */
6510 public final int nextNetworkProviderId() {
6511 return mNextNetworkProviderId.getAndIncrement();
6512 }
6513
Erik Kline0c04b742016-07-07 16:50:58 +09006514 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006515 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006516 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09006517 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006518 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006519 }
6520
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006521 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6522 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006523 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6524 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6525 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08006526 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006527 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006528 return;
6529 }
6530
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006531 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6532 mNetworkProviderInfos.put(npi.messenger, npi);
6533 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006534 }
6535
6536 @Override
6537 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006538 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08006539 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006540 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08006541 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006542 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6543 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006544 }
6545
6546 @Override
6547 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006548 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006549 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006550 }
6551
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006552 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09006553 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006554 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6555 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09006556 Objects.requireNonNull(score);
6557 Objects.requireNonNull(caps);
6558 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09006559 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006560 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09006561 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
6562 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006563 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6564 }
6565
Chalard Jeanbb902a52021-08-18 01:35:19 +09006566 private void updateOfferScore(final NetworkOffer offer) {
6567 final boolean yieldToBadWiFi =
6568 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
6569 final NetworkOffer newOffer = new NetworkOffer(
6570 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
6571 offer.caps, offer.callback, offer.providerId);
6572 if (offer.equals(newOffer)) return;
6573 handleRegisterNetworkOffer(newOffer);
6574 }
6575
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006576 @Override
6577 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6578 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6579 }
6580
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006581 private void handleUnregisterNetworkProvider(Messenger messenger) {
6582 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6583 if (npi == null) {
6584 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006585 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006586 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006587 // Unregister all the offers from this provider
6588 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6589 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09006590 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006591 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6592 toRemove.add(noi);
6593 }
6594 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09006595 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006596 handleUnregisterNetworkOffer(noi);
6597 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006598 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006599 }
6600
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006601 @Override
James Mattisf7027322020-12-13 16:28:14 -08006602 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006603 if (request.hasTransport(TRANSPORT_TEST)) {
6604 enforceNetworkFactoryOrTestNetworksPermission();
6605 } else {
6606 enforceNetworkFactoryPermission();
6607 }
James Mattisf7027322020-12-13 16:28:14 -08006608 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6609 if (nri != null) {
6610 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6611 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6612 mHandler.post(() -> handleReleaseNetworkRequest(
6613 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6614 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006615 }
6616
Paul Jensen1f567382015-02-13 14:18:39 -05006617 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6618 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006619 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05006620 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006621 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05006622 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006623 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006624
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09006625 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05006626 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006627 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006628
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006629 // UID ranges for users that are currently blocked by VPNs.
6630 // This array is accessed and iterated on multiple threads without holding locks, so its
6631 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6632 // (on the handler thread).
6633 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6634
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006635 // Must only be accessed on the handler thread
6636 @NonNull
6637 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6638
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006639 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006640 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09006641
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006642 // Current OEM network preferences. This object must only be written to on the handler thread.
6643 // Since it is immutable and always non-null, other threads may read it if they only care
6644 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08006645 @NonNull
6646 private OemNetworkPreferences mOemNetworkPreferences =
6647 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006648 // Current per-profile network preferences. This object follows the same threading rules as
6649 // the OEM network preferences above.
6650 @NonNull
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006651 private ProfileNetworkPreferenceList mProfileNetworkPreferences =
6652 new ProfileNetworkPreferenceList();
James Mattis45d81842021-01-10 14:24:24 -08006653
paulhu51f77dc2021-06-07 02:34:20 +00006654 // A set of UIDs that should use mobile data preferentially if available. This object follows
6655 // the same threading rules as the OEM network preferences above.
6656 @NonNull
6657 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
6658
James Mattiscb1e0362021-04-06 17:07:42 -07006659 // OemNetworkPreferences activity String log entries.
6660 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6661 @NonNull
6662 private final LocalLog mOemNetworkPreferencesLogs =
6663 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6664
James Mattis02220e22021-03-13 19:27:21 -08006665 /**
6666 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6667 * @param packageName the package name to check existence of a mapping for.
6668 * @return true if a mapping exists, false otherwise
6669 */
6670 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6671 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6672 }
6673
James Mattise3ef1912020-12-20 11:09:58 -08006674 // The always-on request for an Internet-capable network that apps without a specific default
6675 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08006676 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09006677 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006678 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08006679 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08006680 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08006681 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08006682 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006683
James Mattisd31bdfa2020-12-23 16:37:26 -08006684 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6685 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6686 }
6687
6688 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08006689 * Return the default network request currently tracking the given uid.
6690 * @param uid the uid to check.
6691 * @return the NetworkRequestInfo tracking the given uid.
6692 */
6693 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08006694 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08006695 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006696 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006697 // Checking the first request is sufficient as only multilayer requests will have more
6698 // than one request and for multilayer, all requests will track the same uids.
6699 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08006700 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08006701 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08006702 highestPriorityNri = nri;
6703 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006704 }
6705 }
paulhuaa0743d2021-05-26 21:56:03 +08006706 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006707 }
6708
6709 /**
6710 * Get a copy of the network requests of the default request that is currently tracking the
6711 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006712 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6713 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006714 * @param requestorUid the uid to check the default for.
6715 * @param requestorPackageName the requestor's package name.
6716 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6717 */
6718 @NonNull
6719 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006720 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006721 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006722 getDefaultRequestTrackingUid(asUid).mRequests,
6723 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006724 }
6725
6726 /**
6727 * Copy the given nri's NetworkRequest collection.
6728 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006729 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6730 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006731 * @param requestorUid the uid to set on the copied collection.
6732 * @param requestorPackageName the package name to set on the copied collection.
6733 * @return the copied NetworkRequest collection.
6734 */
6735 @NonNull
6736 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006737 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6738 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006739 final List<NetworkRequest> requests = new ArrayList<>();
6740 for (final NetworkRequest nr : requestsToCopy) {
6741 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006742 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08006743 nr.legacyType, nextNetworkRequestId(), nr.type));
6744 }
6745 return requests;
6746 }
6747
6748 @NonNull
6749 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006750 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6751 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09006752 // These capabilities are for a TRACK_DEFAULT callback, so:
6753 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6754 // mDefaultRequest and a per-UID default request.
6755 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006756 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09006757 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006758 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6759 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006760 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006761 restrictRequestUidsForCallerAndSetRequestorInfo(
6762 netCap, requestorUid, requestorPackageName);
6763 return netCap;
6764 }
6765
6766 /**
6767 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6768 * @param nr the network request to check for equality against.
6769 * @return the nri if one exists, null otherwise.
6770 */
6771 @Nullable
6772 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6773 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6774 if (nri.getNetworkRequestForCallback().equals(nr)) {
6775 return nri;
6776 }
6777 }
6778 return null;
6779 }
6780
6781 /**
6782 * Check if an nri is currently being managed by per-app default networking.
6783 * @param nri the nri to check.
6784 * @return true if this nri is currently being managed by per-app default networking.
6785 */
6786 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
6787 // nri.mRequests.get(0) is only different from the original request filed in
6788 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
6789 // functionality therefore if these two don't match, it means this particular nri is
6790 // currently being managed by a per-app default.
6791 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
6792 }
6793
6794 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08006795 * Determine if an nri is a managed default request that disallows default networking.
6796 * @param nri the request to evaluate
6797 * @return true if device-default networking is disallowed
6798 */
6799 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
6800 // Check if this nri is a managed default that supports the default network at its
6801 // lowest priority request.
6802 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
6803 final NetworkCapabilities lowestPriorityNetCap =
6804 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
6805 return isPerAppDefaultRequest(nri)
6806 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
6807 lowestPriorityNetCap));
6808 }
6809
Erik Kline05f2b402015-04-30 12:58:40 +09006810 // Request used to optionally keep mobile data active even when higher
6811 // priority networks like Wi-Fi are active.
6812 private final NetworkRequest mDefaultMobileDataRequest;
6813
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006814 // Request used to optionally keep wifi data active even when higher
6815 // priority networks like ethernet are active.
6816 private final NetworkRequest mDefaultWifiRequest;
6817
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08006818 // Request used to optionally keep vehicle internal network always active
6819 private final NetworkRequest mDefaultVehicleRequest;
6820
James Mattisd31bdfa2020-12-23 16:37:26 -08006821 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
6822 // network with no service. This NAI should never be matched against, nor should any public API
6823 // ever return the associated network. For this reason, this NAI is not in the list of available
6824 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
6825 // default requests that don't support using the device default network which will ultimately
6826 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
6827 @VisibleForTesting
6828 final NetworkAgentInfo mNoServiceNetwork;
6829
Chalard Jean5b409c72021-02-04 13:12:59 +09006830 // The NetworkAgentInfo currently satisfying the default request, if any.
6831 private NetworkAgentInfo getDefaultNetwork() {
6832 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09006833 }
6834
James Mattis2516da32021-01-31 17:06:19 -08006835 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08006836 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08006837 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6838 // Currently, all network requests will have the same uids therefore checking the first
6839 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006840 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08006841 if (null == uids) {
6842 continue;
6843 }
6844 for (final UidRange range : uids) {
6845 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08006846 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08006847 highestPriorityNri = nri;
6848 }
James Mattis2516da32021-01-31 17:06:19 -08006849 }
6850 }
6851 }
paulhuaa0743d2021-05-26 21:56:03 +08006852 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08006853 }
6854
Varun Ananddf569952019-02-06 10:13:38 -08006855 @Nullable
6856 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
6857 return nai != null ? nai.network : null;
6858 }
6859
6860 private void ensureRunningOnConnectivityServiceThread() {
6861 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
6862 throw new IllegalStateException(
6863 "Not running on ConnectivityService thread: "
6864 + Thread.currentThread().getName());
6865 }
6866 }
6867
Chalard Jean3a3f5f22019-04-10 23:07:55 +09006868 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09006869 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
6870 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006871 }
6872
Chalard Jean29d06db2018-05-02 21:14:54 +09006873 /**
6874 * Register a new agent with ConnectivityService to handle a network.
6875 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006876 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09006877 * @param networkInfo the initial info associated with this network. It can be updated later :
6878 * see {@link #updateNetworkInfo}.
6879 * @param linkProperties the initial link properties of this network. They can be updated
6880 * later : see {@link #updateLinkProperties}.
6881 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09006882 * later : see {@link #updateCapabilities}.
Chalard Jean28018572020-12-21 18:36:52 +09006883 * @param initialScore the initial score of the network. See
Chalard Jean29d06db2018-05-02 21:14:54 +09006884 * {@link NetworkAgentInfo#getCurrentScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006885 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006886 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09006887 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09006888 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006889 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09006890 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09006891 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
6892 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09006893 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
6894 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
6895 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09006896 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09006897 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09006898 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6899 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006900 } else {
6901 enforceNetworkFactoryPermission();
6902 }
6903
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006904 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006905 final long token = Binder.clearCallingIdentity();
6906 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006907 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09006908 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006909 } finally {
6910 Binder.restoreCallingIdentity(token);
6911 }
6912 }
6913
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006914 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006915 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09006916 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
6917 int uid) {
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006918 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
Chalard Jean5b639762020-03-09 21:25:37 +09006919 // Strictly, sanitizing here is unnecessary as the capabilities will be sanitized in
6920 // the call to mixInCapabilities below anyway, but sanitizing here means the NAI never
6921 // sees capabilities that may be malicious, which might prevent mistakes in the future.
6922 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Chiachang Wangc07315a2021-08-10 15:13:39 +08006923 networkCapabilities.restrictCapabilitiesForTestNetwork(uid);
Chalard Jean5b639762020-03-09 21:25:37 +09006924 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006925
Rubin Xuffd77d82017-09-05 18:40:49 +01006926 LinkProperties lp = new LinkProperties(linkProperties);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006927
Chalard Jeana23bc9e2018-01-30 22:41:41 +09006928 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006929 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006930 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo), lp, nc,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09006931 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09006932 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
6933 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006934
6935 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006936 processCapabilitiesFromAgent(nai, nc);
Chalard Jean05edd052019-11-22 22:39:56 +09006937 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
Lorenzo Colitti18a58462020-04-16 01:52:40 +09006938 processLinkPropertiesFromAgent(nai, nai.linkProperties);
6939
Chalard Jeanf2da1772018-04-26 16:16:10 +09006940 final String extraInfo = networkInfo.getExtraInfo();
6941 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09006942 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07006943 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09006944 mDeps.getNetworkStack().makeNetworkMonitor(
6945 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006946 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
6947 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006948 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006949 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09006950 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006951 }
6952
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006953 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
6954 nai.onNetworkMonitorCreated(networkMonitor);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006955 if (VDBG) log("Got NetworkAgent Messenger");
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006956 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05006957 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006958 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05006959 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006960
6961 try {
6962 networkMonitor.start();
6963 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08006964 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006965 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006966 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09006967 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09006968 updateNetworkInfo(nai, networkInfo);
6969 updateUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006970 }
6971
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006972 private class NetworkOfferInfo implements IBinder.DeathRecipient {
6973 @NonNull public final NetworkOffer offer;
6974
6975 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
6976 this.offer = offer;
6977 }
6978
6979 @Override
6980 public void binderDied() {
6981 mHandler.post(() -> handleUnregisterNetworkOffer(this));
6982 }
6983 }
6984
Chalard Jeandd35f2d2021-03-24 14:31:38 +09006985 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
6986 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
6987 if (npi.providerId == providerId) return true;
6988 }
6989 return false;
6990 }
6991
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006992 /**
6993 * Register or update a network offer.
6994 * @param newOffer The new offer. If the callback member is the same as an existing
6995 * offer, it is an update of that offer.
6996 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09006997 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006998 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
6999 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007000 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007001 // This may actually happen if a provider updates its score or registers and then
7002 // immediately unregisters. The offer would still be in the handler queue, but the
7003 // provider would have been removed.
7004 if (DBG) log("Received offer from an unregistered provider");
7005 return;
7006 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007007 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7008 if (null != existingOffer) {
7009 handleUnregisterNetworkOffer(existingOffer);
7010 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007011 if (DBG) {
7012 // handleUnregisterNetworkOffer has already logged the old offer
7013 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7014 }
7015 } else {
7016 if (DBG) {
7017 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7018 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007019 }
7020 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7021 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007022 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007023 } catch (RemoteException e) {
7024 noi.binderDied();
7025 return;
7026 }
7027 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007028 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007029 }
7030
7031 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7032 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007033 if (DBG) {
7034 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7035 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007036
7037 // If the provider removes the offer and dies immediately afterwards this
7038 // function may be called twice in a row, but the array will no longer contain
7039 // the offer.
7040 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007041 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007042 }
7043
7044 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7045 @NonNull final INetworkOfferCallback callback) {
7046 ensureRunningOnConnectivityServiceThread();
7047 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007048 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007049 }
7050 return null;
7051 }
7052
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007053 /**
7054 * Called when receiving LinkProperties directly from a NetworkAgent.
7055 * Stores into |nai| any data coming from the agent that might also be written to the network's
7056 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7057 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007058 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007059 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007060 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7061 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007062 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007063 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007064 }
7065
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007066 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007067 @NonNull LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007068 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007069
Lorenzo Colittid523d142020-04-01 20:16:30 +09007070 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7071 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7072 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007073 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007074
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007075 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007076
7077 // update filtering rules, need to happen after the interface update so netd knows about the
7078 // new interface (the interface name -> index map becomes initialized)
7079 updateVpnFiltering(newLp, oldLp, networkAgent);
7080
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007081 updateMtu(newLp, oldLp);
7082 // TODO - figure out what to do for clat
7083// for (LinkProperties lp : newLp.getStackedLinks()) {
7084// updateMtu(lp, null);
7085// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007086 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007087 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7088 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007089
Erik Klineb9888902016-04-05 13:30:49 +09007090 updateRoutes(newLp, oldLp, netId);
7091 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007092 // Make sure LinkProperties represents the latest private DNS status.
7093 // This does not need to be done before updateDnses because the
7094 // LinkProperties are not the source of the private DNS configuration.
7095 // updateDnses will fetch the private DNS configuration from DnsManager.
7096 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007097
Chalard Jean5b409c72021-02-04 13:12:59 +09007098 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007099 handleApplyDefaultProxy(newLp.getHttpProxy());
7100 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007101 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007102 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007103
7104 updateWakeOnLan(newLp);
7105
Hai Shalome58bdc62021-01-11 18:45:34 -08007106 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7107 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7108 // does, it needs to be merged here.
7109 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7110 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007111
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007112 // TODO - move this check to cover the whole function
7113 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007114 synchronized (networkAgent) {
7115 networkAgent.linkProperties = newLp;
7116 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007117 // Start or stop DNS64 detection and 464xlat according to network state.
7118 networkAgent.clatd.update();
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08007119 notifyIfacesChangedForNetworkStats();
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007120 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7121 new LinkProperties(newLp, true /* parcelSensitiveFields */));
lucaslin74fa3972018-11-28 12:51:55 +08007122 if (networkAgent.everConnected) {
7123 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
7124 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007125 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007126
7127 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007128 }
7129
Hai Shalome58bdc62021-01-11 18:45:34 -08007130 /**
7131 * @param naData captive portal data from NetworkAgent
7132 * @param apiData captive portal data from capport API
7133 */
7134 @Nullable
7135 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7136 CaptivePortalData apiData) {
7137 if (naData == null || apiData == null) {
7138 return naData == null ? apiData : naData;
7139 }
7140 final CaptivePortalData.Builder captivePortalBuilder =
7141 new CaptivePortalData.Builder(naData);
7142
7143 if (apiData.isCaptive()) {
7144 captivePortalBuilder.setCaptive(true);
7145 }
7146 if (apiData.isSessionExtendable()) {
7147 captivePortalBuilder.setSessionExtendable(true);
7148 }
7149 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7150 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7151 // otherwise data would be inconsistent. Prefer the capport API info if present,
7152 // as it can generally be refreshed more often.
7153 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7154 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7155 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7156 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7157 // No source has time / bytes remaining information: surface the newest refresh time
7158 // for other fields
7159 captivePortalBuilder.setRefreshTime(
7160 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7161 }
7162
Hai Shalom7c6ab402021-02-04 19:34:06 -08007163 // Prioritize the user portal URL from the network agent if the source is authenticated.
7164 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7165 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7166 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7167 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007168 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007169 // Prioritize the venue information URL from the network agent if the source is
7170 // authenticated.
7171 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7172 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7173 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7174 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007175 }
7176 return captivePortalBuilder.build();
7177 }
7178
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007179 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007180 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007181 // marks on unsupported interfaces is harmless.
7182 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7183 return;
7184 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007185
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007186 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7187 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7188
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007189 // Mask/mark of zero will not detect anything interesting.
7190 // Don't install rules unless both values are nonzero.
7191 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007192 return;
7193 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007194
7195 final String prefix = "iface:" + iface;
7196 try {
7197 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007198 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007199 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007200 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007201 }
7202 } catch (Exception e) {
7203 loge("Exception modifying wakeup packet monitoring: " + e);
7204 }
7205
Joel Scherpelza235a812017-05-22 13:47:41 +09007206 }
7207
Chalard Jean9589e722019-11-19 19:03:53 +09007208 private void updateInterfaces(final @Nullable LinkProperties newLp,
7209 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007210 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09007211 final CompareResult<String> interfaceDiff = new CompareResult<>(
Rubin Xu2fa7d9e2017-08-22 16:35:52 +01007212 oldLp != null ? oldLp.getAllInterfaceNames() : null,
7213 newLp != null ? newLp.getAllInterfaceNames() : null);
Chalard Jean9589e722019-11-19 19:03:53 +09007214 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007215 for (final String iface : interfaceDiff.added) {
7216 try {
7217 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007218 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09007219 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007220 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7221 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007222 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007223 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007224 }
Paul Jensenbff73492014-04-28 10:33:11 -04007225 }
7226 }
Chalard Jean9589e722019-11-19 19:03:53 +09007227 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007228 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007229 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007230 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007231 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007232 } catch (Exception e) {
7233 loge("Exception removing interface: " + e);
7234 }
7235 }
7236 }
7237
Tyler Weare4314862019-12-05 14:55:30 -08007238 // TODO: move to frameworks/libs/net.
7239 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7240 final String nextHop;
7241
7242 switch (route.getType()) {
7243 case RouteInfo.RTN_UNICAST:
7244 if (route.hasGateway()) {
7245 nextHop = route.getGateway().getHostAddress();
7246 } else {
7247 nextHop = INetd.NEXTHOP_NONE;
7248 }
7249 break;
7250 case RouteInfo.RTN_UNREACHABLE:
7251 nextHop = INetd.NEXTHOP_UNREACHABLE;
7252 break;
7253 case RouteInfo.RTN_THROW:
7254 nextHop = INetd.NEXTHOP_THROW;
7255 break;
7256 default:
7257 nextHop = INetd.NEXTHOP_NONE;
7258 break;
7259 }
7260
7261 final RouteInfoParcel rip = new RouteInfoParcel();
7262 rip.ifName = route.getInterface();
7263 rip.destination = route.getDestination().toString();
7264 rip.nextHop = nextHop;
7265 rip.mtu = route.getMtu();
7266
7267 return rip;
7268 }
7269
Paul Jensene0fd4a82014-08-06 15:51:33 -04007270 /**
7271 * Have netd update routes from oldLp to newLp.
7272 * @return true if routes changed between oldLp and newLp
7273 */
7274 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007275 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007276 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7277 new CompareOrUpdateResult<>(
7278 oldLp != null ? oldLp.getAllRoutes() : null,
7279 newLp != null ? newLp.getAllRoutes() : null,
7280 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007281
7282 // add routes before removing old in case it helps with continuous connectivity
7283
Chalard Jean9dd11612018-06-04 16:52:49 +09007284 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007285 for (RouteInfo route : routeDiff.added) {
7286 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007287 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007288 try {
Tyler Weare4314862019-12-05 14:55:30 -08007289 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007290 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007291 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007292 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007293 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007294 }
7295 }
7296 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007297 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007298 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007299 try {
Tyler Weare4314862019-12-05 14:55:30 -08007300 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007301 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007302 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007303 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007304 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007305 }
7306 }
7307
7308 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007309 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007310 try {
Tyler Weare4314862019-12-05 14:55:30 -08007311 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007312 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007313 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007314 }
7315 }
Tyler Weare4314862019-12-05 14:55:30 -08007316
7317 for (RouteInfo route : routeDiff.updated) {
7318 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7319 try {
7320 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7321 } catch (Exception e) {
7322 loge("Exception in networkUpdateRouteParcel: " + e);
7323 }
7324 }
7325 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7326 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007327 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007328
Erik Klineb9888902016-04-05 13:30:49 +09007329 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
7330 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7331 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007332 }
Erik Klineb9888902016-04-05 13:30:49 +09007333
Erik Kline31b4a9e2018-01-11 21:07:29 +09007334 if (DBG) {
7335 final Collection<InetAddress> dnses = newLp.getDnsServers();
7336 log("Setting DNS servers for network " + netId + " to " + dnses);
7337 }
Erik Klineb9888902016-04-05 13:30:49 +09007338 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007339 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007340 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007341 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007342 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007343 }
Erik Kline54e35c02017-04-07 15:29:29 +09007344 }
7345
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007346 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
7347 NetworkAgentInfo nai) {
7348 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
7349 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
7350 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
7351 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
7352
7353 if (!wasFiltering && !needsFiltering) {
7354 // Nothing to do.
7355 return;
7356 }
7357
7358 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7359 // Nothing changed.
7360 return;
7361 }
7362
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007363 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Qingxi Libb8da982020-01-17 17:54:27 -08007364 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007365 // TODO: this create a window of opportunity for apps to receive traffic between the time
7366 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007367 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007368 // old rules are being removed.
7369 if (wasFiltering) {
7370 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7371 }
7372 if (needsFiltering) {
7373 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7374 }
7375 }
7376
Valentin Iftime9fa35092019-09-24 13:32:13 +02007377 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007378 if (mWolSupportedInterfaces == null) {
7379 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007380 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007381 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007382 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7383 }
7384
Luke Huangb913c812018-08-24 20:33:16 +08007385 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007386 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007387 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007388 }
7389 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007390 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007391 }
Luke Huangb913c812018-08-24 20:33:16 +08007392 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007393 }
7394
Chalard Jean62edfd82019-12-02 18:39:29 +09007395 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7396 @NonNull final NetworkCapabilities newNc) {
7397 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7398 final int newPermission = getNetworkPermission(newNc);
7399 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7400 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007401 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08007402 } catch (RemoteException | ServiceSpecificException e) {
7403 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09007404 }
7405 }
7406 }
7407
Paul Jensen53f08952015-06-16 14:27:36 -04007408 /**
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007409 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7410 * Stores into |nai| any data coming from the agent that might also be written to the network's
7411 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7412 * agent is not lost when updateCapabilities is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007413 * This method should never alter the agent's NetworkCapabilities, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007414 */
7415 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007416 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7417 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7418 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7419 // the owner UID here and behave as if the agent had never tried to change it.
Lorenzo Colitti93401342020-12-09 18:30:52 +09007420 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7421 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7422 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7423 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7424 }
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007425 nai.declaredCapabilities = new NetworkCapabilities(nc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007426 }
7427
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007428 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007429 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09007430 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007431 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08007432 underlyingNetworks = underlyingNetworksOrDefault(
7433 agentCaps.getOwnerUid(), underlyingNetworks);
lifrade6c2a2021-03-04 14:08:08 +08007434 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007435 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7436 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007437 // metered if any underlying is metered, or originally declared metered by the agent.
7438 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007439 boolean roaming = false; // roaming if any underlying is roaming
7440 boolean congested = false; // congested if any underlying is congested
7441 boolean suspended = true; // suspended if all underlying are suspended
7442
7443 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08007444 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007445 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08007446 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007447 for (Network underlyingNetwork : underlyingNetworks) {
7448 final NetworkAgentInfo underlying =
7449 getNetworkAgentInfoForNetwork(underlyingNetwork);
7450 if (underlying == null) continue;
7451
7452 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7453 hadUnderlyingNetworks = true;
7454 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007455 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007456 }
7457
7458 // Merge capabilities of this underlying network. For bandwidth, assume the
7459 // worst case.
7460 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7461 underlyingCaps.getLinkDownstreamBandwidthKbps());
7462 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7463 underlyingCaps.getLinkUpstreamBandwidthKbps());
7464 // If this underlying network is metered, the VPN is metered (it may cost money
7465 // to send packets on this network).
7466 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7467 // If this underlying network is roaming, the VPN is roaming (the billing structure
7468 // is different than the usual, local one).
7469 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7470 // If this underlying network is congested, the VPN is congested (the current
7471 // condition of the network affects the performance of this network).
7472 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7473 // If this network is not suspended, the VPN is not suspended (the VPN
7474 // is able to transfer some data).
7475 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08007476 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007477 }
7478 }
7479 if (!hadUnderlyingNetworks) {
7480 // No idea what the underlying networks are; assume reasonable defaults
7481 metered = true;
7482 roaming = false;
7483 congested = false;
7484 suspended = false;
7485 }
7486
lifrade6c2a2021-03-04 14:08:08 +08007487 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007488 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7489 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7490 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7491 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7492 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7493 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08007494 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007495 }
7496
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007497 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007498 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7499 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7500 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04007501 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007502 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007503 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09007504 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007505 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7506 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007507 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007508 // avoid connect/teardown loops.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007509 if (nai.everConnected &&
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007510 !nai.isVPN() &&
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007511 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7512 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09007513 // does not cause any request (that is not a listen) currently matching that agent to
7514 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007515 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09007516 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007517 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09007518 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007519 }
7520
Paul Jensen53f08952015-06-16 14:27:36 -04007521 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007522 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensende49eb12015-06-25 15:30:08 -04007523 if (nai.lastValidated) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007524 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007525 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007526 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007527 }
Paul Jensende49eb12015-06-25 15:30:08 -04007528 if (nai.lastCaptivePortalDetected) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007529 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007530 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007531 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007532 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007533 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007534 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007535 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007536 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007537 }
lucaslin2240ef62019-03-12 13:08:03 +08007538 if (nai.partialConnectivity) {
7539 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7540 } else {
7541 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7542 }
lucasline117e2e2019-10-22 18:27:33 +08007543 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007544
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007545 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09007546 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7547 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007548 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09007549 }
7550
Lorenzo Colittibd079452021-07-02 11:47:57 +09007551 if (nai.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007552 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7553 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007554 }
7555
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007556 return newNc;
7557 }
7558
Lorenzo Colitti44840702021-01-11 22:27:57 +09007559 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7560 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7561 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7562 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7563 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7564 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7565 if (prevSuspended != suspended) {
7566 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7567 // onResumed have been removed.
7568 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7569 : ConnectivityManager.CALLBACK_RESUMED);
7570 }
7571 if (prevSuspended != suspended || prevRoaming != roaming) {
7572 // updateNetworkInfo will mix in the suspended info from the capabilities and
7573 // take appropriate action for the network having possibly changed state.
7574 updateNetworkInfo(nai, nai.networkInfo);
7575 }
7576 }
7577
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007578 /**
7579 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7580 *
7581 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7582 * capabilities we manage and store in {@code nai}, such as validated status and captive
7583 * portal status)
7584 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7585 * potentially triggers rematches.
7586 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7587 * change.)
7588 *
7589 * @param oldScore score of the network before any of the changes that prompted us
7590 * to call this function.
7591 * @param nai the network having its capabilities updated.
7592 * @param nc the new network capabilities.
7593 */
Chalard Jean62edfd82019-12-02 18:39:29 +09007594 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7595 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007596 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007597 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean62edfd82019-12-02 18:39:29 +09007598 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09007599 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007600
Chalard Jeanb2a49912018-01-16 18:43:05 +09007601 updateUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09007602 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007603
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007604 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007605 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7606 // the change we're processing can't affect any requests, it can only affect the listens
7607 // on this network. We might have been called by rematchNetworkAndRequests when a
7608 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09007609 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007610 } else {
7611 // If the requestable capabilities have changed or the score changed, we can't have been
7612 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09007613 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04007614 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07007615 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09007616 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007617
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007618 final boolean oldMetered = prevNc.isMetered();
7619 final boolean newMetered = newNc.isMetered();
7620 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08007621
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007622 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00007623 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7624 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007625 }
junyulaif2c67e42018-08-07 19:50:45 +08007626
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007627 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7628 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08007629
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007630 // Report changes that are interesting for network statistics tracking.
7631 if (meteredChanged || roamingChanged) {
7632 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06007633 }
7634
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007635 // This network might have been underlying another network. Propagate its capabilities.
7636 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08007637
7638 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007639 mDnsManager.updateTransportsForNetwork(
7640 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08007641 }
lucaslin53e8a262021-06-08 01:43:59 +08007642
7643 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007644 }
7645
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09007646 /** Convenience method to update the capabilities for a given network. */
7647 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7648 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7649 }
7650
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007651 /**
7652 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7653 * network.
7654 *
7655 * Ingress interface filtering enforces that all apps under the given network can only receive
7656 * packets from the network's interface (and loopback). This is important for VPNs because
7657 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7658 * non-VPN interfaces.
7659 *
7660 * As a result, this method should return true iff
7661 * 1. the network is an app VPN (not legacy VPN)
7662 * 2. the VPN does not allow bypass
7663 * 3. the VPN is fully-routed
7664 * 4. the VPN interface is non-null
7665 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007666 * @see INetd#firewallAddUidInterfaceRules
7667 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007668 */
7669 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7670 LinkProperties lp) {
7671 if (nc == null || lp == null) return false;
7672 return nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007673 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08007674 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007675 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08007676 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7677 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007678 }
7679
Chiachang Wang28afaff2020-12-10 22:24:47 +08007680 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7681 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7682 int index = 0;
7683 for (UidRange range : ranges) {
7684 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7685 index++;
7686 }
7687 return stableRanges;
7688 }
7689
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007690 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7691 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7692 for (int i = 0; i < ranges.length; i++) {
7693 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7694 }
7695 return stableRanges;
7696 }
7697
Ken Chen5e65a852020-12-24 12:59:10 +08007698 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7699 int[] exemptUids) {
7700 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7701 try {
7702 mNetd.socketDestroy(ranges, exemptUids);
7703 } catch (Exception e) {
7704 loge("Exception in socket destroy: ", e);
7705 }
7706 }
7707 }
7708
paulhuaa0743d2021-05-26 21:56:03 +08007709 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08007710 int[] exemptUids = new int[2];
7711 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7712 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7713 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7714 exemptUids[0] = VPN_UID;
7715 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7716 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7717
7718 maybeCloseSockets(nai, ranges, exemptUids);
7719 try {
7720 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08007721 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007722 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08007723 } else {
paulhu0e79d952021-06-09 16:11:35 +08007724 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08007725 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08007726 }
7727 } catch (Exception e) {
7728 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7729 " on netId " + nai.network.netId + ". " + e);
7730 }
7731 maybeCloseSockets(nai, ranges, exemptUids);
7732 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007733
lucaslin53e8a262021-06-08 01:43:59 +08007734 private boolean isProxySetOnAnyDefaultNetwork() {
7735 ensureRunningOnConnectivityServiceThread();
7736 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7737 final NetworkAgentInfo nai = nri.getSatisfier();
7738 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
7739 return true;
7740 }
7741 }
7742 return false;
7743 }
7744
7745 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7746 NetworkCapabilities newNc) {
7747 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
7748 // the proxy might be changed since the default network satisfied by the apps might also
7749 // changed.
7750 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
7751 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09007752 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
7753 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
7754 if (nai.isVPN() && nai.everConnected && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08007755 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
7756 mProxyTracker.sendProxyBroadcast();
7757 }
7758 }
7759
Chalard Jeanb2a49912018-01-16 18:43:05 +09007760 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7761 NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007762 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7763 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007764 if (null == prevRanges) prevRanges = new ArraySet<>();
7765 if (null == newRanges) newRanges = new ArraySet<>();
7766 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
7767
7768 prevRanges.removeAll(newRanges);
7769 newRanges.removeAll(prevRangesCopy);
7770
7771 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007772 // When updating the VPN uid routing rules, add the new range first then remove the old
7773 // range. If old range were removed first, there would be a window between the old
7774 // range being removed and the new range being added, during which UIDs contained
7775 // in both ranges are not subject to any VPN routing rules. Adding new range before
7776 // removing old range works because, unlike the filtering rules below, it's possible to
7777 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08007778 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
7779 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
7780 // [1-5] & [1-2],[4-5] == [3]
7781 // Then we can do:
7782 // maybeCloseSockets([3])
7783 // mNetd.networkAddUidRanges([1-2],[4-5])
7784 // mNetd.networkRemoveUidRanges([1-5])
7785 // maybeCloseSockets([3])
7786 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
7787 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09007788 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08007789 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007790 }
7791 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08007792 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007793 }
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007794 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
7795 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
7796 final String iface = nai.linkProperties.getInterfaceName();
7797 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09007798 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007799 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
7800 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
7801 // were added first and then newRanges got removed later, there would be only one uid
7802 // 10013 left. A consequence of removing old ranges before adding new ranges is that
7803 // there is now a window of opportunity when the UIDs are not subject to any filtering.
7804 // Note that this is in contrast with the (more robust) update of VPN routing rules
7805 // above, where the addition of new ranges happens before the removal of old ranges.
7806 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
7807 // to be removed will never overlap with the new range to be added.
7808 if (wasFiltering && !prevRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08007809 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007810 }
7811 if (shouldFilter && !newRanges.isEmpty()) {
Qingxi Libb8da982020-01-17 17:54:27 -08007812 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007813 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09007814 } catch (Exception e) {
7815 // Never crash!
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007816 loge("Exception in updateUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09007817 }
7818 }
7819
Hugo Benichi9d35b752017-09-01 01:23:32 +00007820 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09007821 ensureRunningOnConnectivityServiceThread();
7822
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007823 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00007824 // Ignore updates for disconnected networks
7825 return;
7826 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007827 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09007828 log("Update of LinkProperties for " + nai.toShortString()
7829 + "; created=" + nai.created
7830 + "; everConnected=" + nai.everConnected);
Hugo Benichi9d35b752017-09-01 01:23:32 +00007831 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007832 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
7833 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08007834 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00007835 }
7836
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007837 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
7838 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007839 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007840 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08007841 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08007842 // If apps could file multi-layer requests with PendingIntents, they'd need to know
7843 // which of the layer is satisfied alongside with some ID for the request. Hence, if
7844 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09007845 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
7846 // need to be sent as a separate extra.
7847 final NetworkRequest req = nri.isMultilayerRequest()
7848 ? nri.getActiveRequest()
7849 // Non-multilayer listen requests do not have an active request
7850 : nri.mRequests.get(0);
7851 if (req == null) {
7852 Log.wtf(TAG, "No request in NRI " + nri);
7853 }
7854 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007855 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007856 sendIntent(nri.mPendingIntent, intent);
7857 }
7858 // else not handled
7859 }
7860
7861 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
7862 mPendingIntentWakeLock.acquire();
7863 try {
7864 if (DBG) log("Sending " + pendingIntent);
7865 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
7866 } catch (PendingIntent.CanceledException e) {
7867 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
7868 mPendingIntentWakeLock.release();
7869 releasePendingNetworkRequest(pendingIntent);
7870 }
7871 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
7872 }
7873
7874 @Override
7875 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
7876 String resultData, Bundle resultExtras) {
7877 if (DBG) log("Finished sending " + pendingIntent);
7878 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007879 // Release with a delay so the receiving client has an opportunity to put in its
7880 // own request.
7881 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007882 }
7883
James Mattis212df9e2020-12-03 19:57:41 -08007884 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
7885 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
7886 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08007887 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08007888 // Default request has no msgr. Also prevents callbacks from being invoked for
7889 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
7890 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
7891 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007892 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007893 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08007894 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007895 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007896 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08007897 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007898 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007899 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
7900 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007901 }
Roshan Pius951c0032020-12-22 15:10:42 -08007902 final boolean includeLocationSensitiveInfo =
7903 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007904 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09007905 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08007906 final NetworkCapabilities nc =
7907 networkCapabilitiesRestrictedForCallerPermissions(
7908 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7909 putParcelable(
7910 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08007911 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08007912 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08007913 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08007914 nri.mCallingAttributionTag));
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09007915 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7916 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08007917 // For this notification, arg1 contains the blocked status.
7918 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09007919 break;
7920 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007921 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09007922 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007923 break;
7924 }
7925 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09007926 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08007927 final NetworkCapabilities netCap =
7928 networkCapabilitiesRestrictedForCallerPermissions(
7929 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7930 putParcelable(
7931 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08007932 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08007933 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08007934 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08007935 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007936 break;
7937 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007938 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09007939 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7940 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007941 break;
7942 }
junyulaif2c67e42018-08-07 19:50:45 +08007943 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09007944 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08007945 msg.arg1 = arg1;
7946 break;
7947 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007948 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007949 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007950 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007951 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007952 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09007953 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08007954 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007955 }
James Mattis45d81842021-01-10 14:24:24 -08007956 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007957 } catch (RemoteException e) {
7958 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08007959 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007960 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007961 }
7962
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09007963 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
7964 bundle.putParcelable(t.getClass().getSimpleName(), t);
7965 }
7966
Chalard Jean0702f982021-09-16 21:50:07 +09007967 /**
7968 * Returns whether reassigning a request from an NAI to another can be done gracefully.
7969 *
7970 * When a request should be assigned to a new network, it is normally lingered to give
7971 * time for apps to gracefully migrate their connections. When both networks are on the same
7972 * radio, but that radio can't do time-sharing efficiently, this may end up being
7973 * counter-productive because any traffic on the old network may drastically reduce the
7974 * performance of the new network.
7975 * The stack supports a configuration to let modem vendors state that their radio can't
7976 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
7977 * from one cell network to another can't be done gracefully.
7978 *
7979 * @param oldNai the old network serving the request
7980 * @param newNai the new network serving the request
7981 * @return whether the switch can be graceful
7982 */
7983 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
7984 @NonNull final NetworkAgentInfo newSatisfier) {
7985 if (mCellularRadioTimesharingCapable) return true;
7986 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
7987 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
7988 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
7989 }
7990
Paul Jensenaf94b982014-09-30 15:37:41 -04007991 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09007992 if (nai.numRequestNetworkRequests() != 0) {
7993 for (int i = 0; i < nai.numNetworkRequests(); i++) {
7994 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007995 // Ignore listening and track default requests.
7996 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09007997 loge("Dead network still had at least " + nr);
7998 break;
7999 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008000 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008001 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008002 }
8003
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008004 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8005 if (oldNetwork == null) {
8006 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8007 return;
8008 }
Chalard Jean49707572019-12-10 21:07:02 +09008009 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008010
8011 // If we get here it means that the last linger timeout for this network expired. So there
8012 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008013 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008014
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008015 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008016 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008017 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008018 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008019 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008020 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008021 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008022 }
8023
James Mattise3ef1912020-12-20 11:09:58 -08008024 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8025 boolean isDefaultChanged = false;
8026 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8027 final NetworkReassignment.RequestReassignment reassignment =
8028 changes.getReassignment(defaultRequestInfo);
8029 if (null == reassignment) {
8030 continue;
8031 }
8032 // reassignment only contains those instances where the satisfying network changed.
8033 isDefaultChanged = true;
8034 // Notify system services of the new default.
8035 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8036 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008037
James Mattise3ef1912020-12-20 11:09:58 -08008038 if (isDefaultChanged) {
8039 // Hold a wakelock for a short time to help apps in migrating to a new default.
8040 scheduleReleaseNetworkTransitionWakelock();
8041 }
8042 }
8043
8044 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8045 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8046 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8047 if (DBG) {
8048 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8049 }
Chalard Jean8e382112019-12-03 20:45:30 +09008050
James Mattisd31bdfa2020-12-23 16:37:26 -08008051 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8052 if (newDefaultNetwork != null) {
8053 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008054 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008055
James Mattisd31bdfa2020-12-23 16:37:26 -08008056 // Set an app level managed default and return since further processing only applies to the
8057 // default network.
8058 if (mDefaultRequest != nri) {
8059 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8060 return;
8061 }
8062
8063 makeDefaultNetwork(newDefaultNetwork);
8064
James Mattise3ef1912020-12-20 11:09:58 -08008065 if (oldDefaultNetwork != null) {
8066 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8067 }
8068 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008069 handleApplyDefaultProxy(null != newDefaultNetwork
8070 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8071 updateTcpBufferSizes(null != newDefaultNetwork
8072 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008073 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008074 }
8075
James Mattisd31bdfa2020-12-23 16:37:26 -08008076 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8077 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8078 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8079 try {
8080 if (VDBG) {
8081 log("Setting default network for " + nri
8082 + " using UIDs " + nri.getUids()
8083 + " with old network " + (oldDefaultNetwork != null
8084 ? oldDefaultNetwork.network().getNetId() : "null")
8085 + " and new network " + (newDefaultNetwork != null
8086 ? newDefaultNetwork.network().getNetId() : "null"));
8087 }
8088 if (nri.getUids().isEmpty()) {
8089 throw new IllegalStateException("makeDefaultForApps called without specifying"
8090 + " any applications to set as the default." + nri);
8091 }
8092 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008093 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008094 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008095 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008096 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008097 }
8098 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008099 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008100 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008101 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008102 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008103 }
8104 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008105 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008106 }
8107 }
8108
8109 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8110 try {
8111 if (null != newDefaultNetwork) {
8112 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8113 } else {
8114 mNetd.networkClearDefault();
8115 }
8116 } catch (RemoteException | ServiceSpecificException e) {
8117 loge("Exception setting default network :" + e);
8118 }
8119 }
8120
Chalard Jean05cbe972019-12-09 11:50:38 +09008121 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008122 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09008123 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09008124 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09008125 processNewlySatisfiedListenRequests(nai);
8126 }
8127
8128 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008129 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8130 if (nri.isMultilayerRequest()) {
8131 continue;
8132 }
8133 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008134 if (!nr.isListen()) continue;
8135 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08008136 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008137 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
8138 }
8139 }
Chalard Jeancd397a22019-11-22 22:33:33 +09008140 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008141
Chalard Jeancd397a22019-11-22 22:33:33 +09008142 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008143 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8144 if (nri.isMultilayerRequest()) {
8145 continue;
8146 }
8147 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008148 if (!nr.isListen()) continue;
8149 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
8150 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09008151 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008152 }
8153 }
8154 }
8155
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008156 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008157 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008158 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08008159 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09008160 @Nullable public final NetworkRequest mOldNetworkRequest;
8161 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008162 @Nullable public final NetworkAgentInfo mOldNetwork;
8163 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08008164 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008165 @Nullable final NetworkRequest oldNetworkRequest,
8166 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008167 @Nullable final NetworkAgentInfo oldNetwork,
8168 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008169 mNetworkRequestInfo = networkRequestInfo;
8170 mOldNetworkRequest = oldNetworkRequest;
8171 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008172 mOldNetwork = oldNetwork;
8173 mNewNetwork = newNetwork;
8174 }
Chalard Jean49707572019-12-10 21:07:02 +09008175
8176 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09008177 final NetworkRequest requestToShow = null != mNewNetworkRequest
8178 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
8179 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08008180 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
8181 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09008182 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008183 }
8184
Chalard Jean46a62372019-12-10 21:25:24 +09008185 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008186
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008187 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09008188 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008189 }
8190
8191 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09008192 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09008193 // The code is never supposed to add two reassignments of the same request. Make
8194 // sure this stays true, but without imposing this expensive check on all
8195 // reassignments on all user devices.
8196 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08008197 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09008198 throw new IllegalStateException("Trying to reassign ["
8199 + reassignment + "] but already have ["
8200 + existing + "]");
8201 }
8202 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09008203 }
Chalard Jean46a62372019-12-10 21:25:24 +09008204 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008205 }
8206
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008207 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09008208 // the passed request.
8209 @Nullable
8210 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008211 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008212 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008213 }
8214 return null;
8215 }
Chalard Jean49707572019-12-10 21:07:02 +09008216
8217 public String toString() {
8218 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8219 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09008220 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008221 for (final RequestReassignment rr : getRequestReassignments()) {
8222 sj.add(rr.toString());
8223 }
8224 return sj.toString();
8225 }
8226
8227 public String debugString() {
8228 final StringBuilder sb = new StringBuilder();
8229 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09008230 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008231 for (final RequestReassignment rr : getRequestReassignments()) {
8232 sb.append("\n ").append(rr);
8233 }
8234 return sb.append("\n").toString();
8235 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008236 }
8237
Chalard Jean24344d72019-12-04 13:32:31 +09008238 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008239 @Nullable final NetworkRequest previousRequest,
8240 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09008241 @Nullable final NetworkAgentInfo previousSatisfier,
8242 @Nullable final NetworkAgentInfo newSatisfier,
8243 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08008244 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09008245 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09008246 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008247 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008248 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09008249 }
James Mattisa076c532020-12-02 14:12:41 -08008250 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean0702f982021-09-16 21:50:07 +09008251 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)) {
8252 // If this network switch can't be supported gracefully, the request is not
8253 // lingered. This allows letting go of the network sooner to reclaim some
8254 // performance on the new network, since the radio can't do both at the same
8255 // time while preserving good performance.
8256 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8257 }
Chalard Jean24344d72019-12-04 13:32:31 +09008258 } else {
8259 if (VDBG || DDBG) log(" accepting network in place of null");
8260 }
junyulai0ac374f2020-12-14 18:41:52 +08008261
8262 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8263 // and immediately satisfies a request then remove the timer. This will happen for
8264 // all networks except in the case of an underlying network for a VCN.
8265 if (newSatisfier.isNascent()) {
8266 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08008267 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008268 }
8269
Chalard Jean5d6e23b2021-03-01 22:00:20 +09008270 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08008271 newSatisfier.unlingerRequest(newRequest.requestId);
8272 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008273 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08008274 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008275 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09008276 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008277 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008278 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08008279 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008280 }
James Mattisa076c532020-12-02 14:12:41 -08008281 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008282 }
James Mattisa076c532020-12-02 14:12:41 -08008283 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008284 }
8285
James Mattisa076c532020-12-02 14:12:41 -08008286 /**
8287 * This function is triggered when something can affect what network should satisfy what
8288 * request, and it computes the network reassignment from the passed collection of requests to
8289 * network match to the one that the system should now have. That data is encoded in an
8290 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8291 * satisfier.
8292 *
8293 * After the reassignment is computed, it is applied to the state objects.
8294 *
8295 * @param networkRequests the nri objects to evaluate for possible network reassignment
8296 * @return NetworkReassignment listing of proposed network assignment changes
8297 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008298 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08008299 private NetworkReassignment computeNetworkReassignment(
8300 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09008301 final NetworkReassignment changes = new NetworkReassignment();
8302
Chalard Jeanc81d4c32021-04-07 17:06:19 +09008303 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09008304 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008305 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattisa076c532020-12-02 14:12:41 -08008306 if (!nai.everConnected) {
8307 continue;
8308 }
Chalard Jean857a1712019-12-10 21:08:07 +09008309 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09008310 }
Chalard Jean857a1712019-12-10 21:08:07 +09008311
James Mattisa076c532020-12-02 14:12:41 -08008312 for (final NetworkRequestInfo nri : networkRequests) {
8313 // Non-multilayer listen requests can be ignored.
8314 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8315 continue;
8316 }
8317 NetworkAgentInfo bestNetwork = null;
8318 NetworkRequest bestRequest = null;
8319 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09008320 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08008321 // Stop evaluating as the highest possible priority request is satisfied.
8322 if (null != bestNetwork) {
8323 bestRequest = req;
8324 break;
8325 }
8326 }
James Mattisd31bdfa2020-12-23 16:37:26 -08008327 if (null == bestNetwork && isDefaultBlocked(nri)) {
8328 // Remove default networking if disallowed for managed default requests.
8329 bestNetwork = mNoServiceNetwork;
8330 }
8331 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09008332 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09008333 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08008334 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09008335 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008336 }
8337 return changes;
8338 }
8339
James Mattisa076c532020-12-02 14:12:41 -08008340 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8341 return new HashSet<>(mNetworkRequests.values());
8342 }
8343
Paul Jensenc88b39b2015-06-16 14:27:36 -04008344 /**
James Mattisa076c532020-12-02 14:12:41 -08008345 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04008346 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04008347 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008348 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08008349 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8350 }
8351
8352 /**
8353 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8354 * being disconnected.
8355 */
8356 private void rematchNetworksAndRequests(
8357 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8358 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09008359 // TODO: This may be slow, and should be optimized.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008360 final long now = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08008361 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jean49707572019-12-10 21:07:02 +09008362 if (VDBG || DDBG) {
8363 log(changes.debugString());
8364 } else if (DBG) {
8365 log(changes.toString()); // Shorter form, only one line of log
8366 }
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008367 applyNetworkReassignment(changes, now);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008368 issueNetworkNeeds();
Chalard Jeand7f762d2019-12-10 19:01:29 +09008369 }
Chalard Jean64520dc2019-12-04 19:55:32 +09008370
Chalard Jeand7f762d2019-12-10 19:01:29 +09008371 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008372 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008373 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09008374
8375 // Since most of the time there are only 0 or 1 background networks, it would probably
8376 // be more efficient to just use an ArrayList here. TODO : measure performance
8377 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8378 for (final NetworkAgentInfo nai : nais) {
8379 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8380 }
8381
Chalard Jeand7f762d2019-12-10 19:01:29 +09008382 // First, update the lists of satisfied requests in the network agents. This is necessary
8383 // because some code later depends on this state to be correct, most prominently computing
8384 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09008385 for (final NetworkReassignment.RequestReassignment event :
8386 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008387 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8388 event.mOldNetworkRequest, event.mNewNetworkRequest,
8389 event.mOldNetwork, event.mNewNetwork,
8390 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09008391 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008392
James Mattise3ef1912020-12-20 11:09:58 -08008393 // Process default network changes if applicable.
8394 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008395
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008396 // Notify requested networks are available after the default net is switched, but
8397 // before LegacyTypeTracker sends legacy broadcasts
8398 for (final NetworkReassignment.RequestReassignment event :
8399 changes.getRequestReassignments()) {
8400 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008401 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008402 } else {
James Mattisa076c532020-12-02 14:12:41 -08008403 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008404 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008405 }
8406 }
8407
junyulai0ac374f2020-12-14 18:41:52 +08008408 // Update the inactivity state before processing listen callbacks, because the background
8409 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008410 // just yet though, because they have to be sent after the listens are processed to keep
8411 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08008412 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09008413 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08008414 // Rematching may have altered the inactivity state of some networks, so update all
8415 // inactivity timers. updateInactivityState reads the state from the network agent
8416 // and does nothing if the state has not changed : the source of truth is controlled
8417 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8418 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08008419 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08008420 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008421 }
8422 }
8423
Chalard Jeanb10ab412019-12-11 14:12:30 +09008424 for (final NetworkAgentInfo nai : nais) {
8425 if (!nai.everConnected) continue;
8426 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008427 // Process listen requests and update capabilities if the background state has
8428 // changed for this network. For consistency with previous behavior, send onLost
8429 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09008430 processNewlyLostListenRequests(nai);
8431 if (oldBackground != nai.isBackgroundNetwork()) {
8432 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008433 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09008434 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008435 }
8436
junyulai0ac374f2020-12-14 18:41:52 +08008437 for (final NetworkAgentInfo nai : inactiveNetworks) {
8438 // For nascent networks, if connecting with no foreground request, skip broadcasting
8439 // LOSING for backward compatibility. This is typical when mobile data connected while
8440 // wifi connected with mobile data always-on enabled.
8441 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008442 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008443 }
8444
James Mattise3ef1912020-12-20 11:09:58 -08008445 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09008446
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008447 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008448 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008449 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08008450 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008451 // This network has active linger timers and no requests, but is not
8452 // lingering. Linger it.
8453 //
8454 // One way (the only way?) this can happen if this network is unvalidated
8455 // and became unneeded due to another network improving its score to the
8456 // point where this network will no longer be able to satisfy any requests
8457 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08008458 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008459 notifyNetworkLosing(nai, now);
8460 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09008461 } else {
Chalard Jean49707572019-12-10 21:07:02 +09008462 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09008463 teardownUnneededNetwork(nai);
8464 }
8465 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04008466 }
8467 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008468
Chalard Jean62edfd82019-12-02 18:39:29 +09008469 /**
8470 * Apply a change in background state resulting from rematching networks with requests.
8471 *
8472 * During rematch, a network may change background states by starting to satisfy or stopping
8473 * to satisfy a foreground request. Listens don't count for this. When a network changes
8474 * background states, its capabilities need to be updated and callbacks fired for the
8475 * capability change.
8476 *
8477 * @param nai The network that changed background states
8478 */
8479 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8480 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8481 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8482 updateNetworkPermissions(nai, newNc);
8483 nai.getAndSetNetworkCapabilities(newNc);
8484 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8485 }
8486
Chalard Jeanf0344532019-11-19 19:23:38 +09008487 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08008488 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008489 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09008490 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8491 changes.getReassignment(mDefaultRequest);
8492 final NetworkAgentInfo oldDefaultNetwork =
8493 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8494 final NetworkAgentInfo newDefaultNetwork =
8495 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08008496
Chalard Jean5b409c72021-02-04 13:12:59 +09008497 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008498 // Maintain the illusion : since the legacy API only understands one network at a time,
8499 // if the default network changed, apps should see a disconnected broadcast for the
8500 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09008501 if (oldDefaultNetwork != null) {
8502 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8503 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008504 }
Chalard Jean5b409c72021-02-04 13:12:59 +09008505 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008506 // The new default network can be newly null if and only if the old default
8507 // network doesn't satisfy the default request any more because it lost a
8508 // capability.
Chalard Jean5b409c72021-02-04 13:12:59 +09008509 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08008510 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09008511 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008512 }
8513 }
8514
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008515 // Now that all the callbacks have been sent, send the legacy network broadcasts
8516 // as needed. This is necessary so that legacy requests correctly bind dns
8517 // requests to this network. The legacy users are listening for this broadcast
8518 // and will generally do a dns request so they can ensureRouteToHost and if
8519 // they do that before the callbacks happen they'll use the default network.
8520 //
8521 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8522 // callbacks, but if apps can receive the broadcast before the callback, they still might
8523 // have an inconsistent view of networking.
8524 //
8525 // This *does* introduce a race where if the user uses the new api
8526 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8527 // they may get old info. Reverse this after the old startUsing api is removed.
8528 // This is on top of the multiple intent sequencing referenced in the todo above.
8529 for (NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008530 if (nai.everConnected) {
8531 addNetworkToLegacyTypeTracker(nai);
8532 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08008533 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008534 }
8535
Chalard Jean0354d8c2021-01-12 10:58:56 +09008536 private void issueNetworkNeeds() {
8537 ensureRunningOnConnectivityServiceThread();
8538 for (final NetworkOfferInfo noi : mNetworkOffers) {
8539 issueNetworkNeeds(noi);
8540 }
8541 }
8542
8543 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8544 ensureRunningOnConnectivityServiceThread();
8545 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8546 informOffer(nri, noi.offer, mNetworkRanker);
8547 }
8548 }
8549
8550 /**
8551 * Inform a NetworkOffer about any new situation of a request.
8552 *
8553 * This function handles updates to offers. A number of events may happen that require
8554 * updating the registrant for this offer about the situation :
8555 * • The offer itself was updated. This may lead the offer to no longer being able
8556 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8557 * or conversely being strengthened enough to beat the satisfier (and therefore
8558 * start being needed)
8559 * • The network satisfying a request changed (including cases where the request
8560 * starts or stops being satisfied). The new network may be a stronger or weaker
8561 * match than the old one, possibly affecting whether the offer is needed.
8562 * • The network satisfying a request updated their score. This may lead the offer
8563 * to no longer be able to beat it if the current satisfier got better, or
8564 * conversely start being a good choice if the current satisfier got weaker.
8565 *
8566 * @param nri The request
8567 * @param offer The offer. This may be an updated offer.
8568 */
8569 private static void informOffer(@NonNull NetworkRequestInfo nri,
8570 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
8571 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
8572 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09008573
8574 // Multi-layer requests have a currently active request, the one being satisfied.
8575 // Since the system will try to bring up a better network than is currently satisfying
8576 // the request, NetworkProviders need to be told the offers matching the requests *above*
8577 // the currently satisfied one are needed, that the ones *below* the satisfied one are
8578 // not needed, and the offer is needed for the active request iff the offer can beat
8579 // the satisfier.
8580 // For non-multilayer requests, the logic above gracefully degenerates to only the
8581 // last case.
8582 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
8583 // providers that the offer is needed for this request, until the active request is found.
8584 // In a second phase, deal with the currently active request. In a third phase, inform
8585 // the providers that offer is unneeded for the remaining requests.
8586
8587 // First phase : inform providers of all requests above the active request.
8588 int i;
8589 for (i = 0; nri.mRequests.size() > i; ++i) {
8590 final NetworkRequest request = nri.mRequests.get(i);
8591 if (activeRequest == request) break; // Found the active request : go to phase 2
8592 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8593 // Since this request is higher-priority than the one currently satisfied, if the
8594 // offer can satisfy it, the provider should try and bring up the network for sure ;
8595 // no need to even ask the ranker – an offer that can satisfy is always better than
8596 // no network. Hence tell the provider so unless it already knew.
8597 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
8598 offer.onNetworkNeeded(request);
8599 }
8600 }
8601
8602 // Second phase : deal with the active request (if any)
8603 if (null != activeRequest && activeRequest.isRequest()) {
8604 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00008605 // If an offer can satisfy the request, it is considered needed if it is currently
8606 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09008607 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00008608 && satisfier.factorySerialNumber == offer.providerId
8609 && activeRequest.canBeSatisfiedBy(offer.caps);
8610 final boolean newNeeded = currentlyServing
8611 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008612 if (newNeeded != oldNeeded) {
8613 if (newNeeded) {
8614 offer.onNetworkNeeded(activeRequest);
8615 } else {
8616 // The offer used to be able to beat the satisfier. Now it can't.
8617 offer.onNetworkUnneeded(activeRequest);
8618 }
8619 }
8620 }
8621
8622 // Third phase : inform the providers that the offer isn't needed for any request
8623 // below the active one.
8624 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
8625 final NetworkRequest request = nri.mRequests.get(i);
8626 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8627 // Since this request is lower-priority than the one currently satisfied, if the
8628 // offer can satisfy it, the provider should not try and bring up the network.
8629 // Hence tell the provider so unless it already knew.
8630 if (offer.neededFor(request)) {
8631 offer.onNetworkUnneeded(request);
8632 }
8633 }
8634 }
8635
Chalard Jean61c79252019-11-07 23:07:32 +09008636 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8637 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8638 NetworkRequest nr = nai.requestAt(i);
8639 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8640 // legacy type tracker filters out repeat adds
8641 mLegacyTypeTracker.add(nr.legacyType, nai);
8642 }
8643 }
8644
8645 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09008646 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09008647 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8648 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8649 if (nai.isVPN()) {
8650 mLegacyTypeTracker.add(TYPE_VPN, nai);
8651 }
8652 }
8653
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008654 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04008655 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittia8de5ca2014-12-17 11:14:42 +09008656 if (!nai.everValidated) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09008657 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04008658 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09008659 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008660
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09008661 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04008662 // Don't repeat publish.
8663 if (newInetCondition == mDefaultInetConditionPublished) return;
8664
8665 mDefaultInetConditionPublished = newInetCondition;
8666 sendInetConditionBroadcast(nai.networkInfo);
8667 }
8668
Chalard Jeand61375d2020-01-14 22:46:36 +09008669 @NonNull
8670 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8671 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008672 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09008673 final boolean suspended =
8674 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8675 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8676 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8677 // state. This is because the network could have been suspended before connecting,
8678 // or it could be disconnecting while being suspended, and in both these cases
8679 // the state should not be overridden. Note that the only detailed state that
8680 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8681 // worry about multiple different substates of CONNECTED.
8682 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8683 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08008684 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8685 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8686 // network agent is created, then goes to suspended, then goes out of suspended without
8687 // ever setting connected. Check if network agent is ever connected to update the state.
8688 newInfo.setDetailedState(nai.everConnected
8689 ? NetworkInfo.DetailedState.CONNECTED
8690 : NetworkInfo.DetailedState.CONNECTING,
8691 info.getReason(),
8692 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09008693 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008694 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09008695 return newInfo;
8696 }
8697
8698 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8699 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8700
Erik Kline99f301b2017-02-15 19:59:17 +09008701 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008702 NetworkInfo oldInfo = null;
8703 synchronized (networkAgent) {
8704 oldInfo = networkAgent.networkInfo;
8705 networkAgent.networkInfo = newInfo;
8706 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008707
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008708 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008709 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8710 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008711 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07008712
Robin Leea8c0b6e2016-05-01 23:00:00 +01008713 if (!networkAgent.created
8714 && (state == NetworkInfo.State.CONNECTED
8715 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008716
8717 // A network that has just connected has zero requests and is thus a foreground network.
8718 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8719
Luke Huangfdd11f82019-04-09 18:41:49 +08008720 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09008721 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008722 // Initialize the network's capabilities to their starting values according to the
8723 // underlying networks. This ensures that the capabilities are correct before
8724 // anything happens to the network.
8725 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09008726 }
Paul Jensen74940202014-08-04 12:21:19 -04008727 networkAgent.created = true;
Chiachang Wang3f6cc072021-03-24 18:39:17 +08008728 networkAgent.onNetworkCreated();
Robin Leea8c0b6e2016-05-01 23:00:00 +01008729 }
8730
8731 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
8732 networkAgent.everConnected = true;
8733
lucaslin45e639b2019-04-03 17:09:28 +08008734 // NetworkCapabilities need to be set before sending the private DNS config to
8735 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09008736 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
8737
Erik Kline9a62f012018-03-21 07:18:33 -07008738 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08008739 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
8740 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008741
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008742 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
8743 // command must be sent after updating LinkProperties to maximize chances of
8744 // NetworkMonitor seeing the correct LinkProperties when starting.
8745 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008746 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09008747 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008748 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09008749 networkAgent.networkMonitor().notifyNetworkConnected(
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008750 new LinkProperties(networkAgent.linkProperties,
8751 true /* parcelSensitiveFields */),
8752 networkAgent.networkCapabilities);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09008753 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008754
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008755 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
8756 // be communicated to a particular NetworkAgent depends only on the network's immutable,
8757 // capabilities, so it only needs to be done once on initial connect, not every time the
8758 // network's capabilities change. Note that we do this before rematching the network,
8759 // so we could decide to tear it down immediately afterwards. That's fine though - on
8760 // disconnection NetworkAgents should stop any signal strength monitoring they have been
8761 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09008762 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09008763
junyulai0ac374f2020-12-14 18:41:52 +08008764 // Before first rematching networks, put an inactivity timer without any request, this
8765 // allows {@code updateInactivityState} to update the state accordingly and prevent
8766 // tearing down for any {@code unneeded} evaluation in this period.
8767 // Note that the timer will not be rescheduled since the expiry time is
8768 // fixed after connection regardless of the network satisfying other requests or not.
8769 // But it will be removed as soon as the network satisfies a request for the first time.
8770 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
8771 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08008772 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008773
Paul Jensen05e85ee2014-09-11 11:00:39 -04008774 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008775 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09008776
8777 // This has to happen after matching the requests, because callbacks are just requests.
8778 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008779 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008780 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04008781 if (networkAgent.isVPN()) {
Chalard Jeanb2a49912018-01-16 18:43:05 +09008782 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04008783 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09008784 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00008785 if (networkAgent.isVPN()) {
8786 // As the active or bound network changes for apps, broadcast the default proxy, as
8787 // apps may need to update their proxy data. This is called after disconnecting from
8788 // VPN to make sure we do not broadcast the old proxy data.
8789 // TODO(b/122649188): send the broadcast only to VPN users.
8790 mProxyTracker.sendProxyBroadcast();
8791 }
Yintang Gu5014b522019-06-18 14:24:32 +08008792 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
8793 state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008794 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008795 }
8796 }
8797
Chalard Jean28018572020-12-21 18:36:52 +09008798 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09008799 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
8800 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008801 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07008802 }
8803
Erik Kline99f301b2017-02-15 19:59:17 +09008804 // Notify only this one new request of the current state. Transfer all the
8805 // current state by calling NetworkCapabilities and LinkProperties callbacks
8806 // so that callers can be guaranteed to have as close to atomicity in state
8807 // transfer as can be supported by this current API.
8808 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07008809 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09008810 if (nri.mPendingIntent != null) {
8811 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
8812 // Attempt no subsequent state pushes where intents are involved.
8813 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008814 }
Erik Kline99f301b2017-02-15 19:59:17 +09008815
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008816 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08008817 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008818 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
8819 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
8820 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08008821 }
8822
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008823 // Notify the requests on this NAI that the network is now lingered.
8824 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08008825 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008826 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
8827 }
8828
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008829 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
8830 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
8831 return vpnBlocked
8832 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
8833 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
8834 }
8835
8836 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
8837 if (blockedReasons == BLOCKED_REASON_NONE) {
8838 mUidBlockedReasons.delete(uid);
8839 } else {
8840 mUidBlockedReasons.put(uid, blockedReasons);
8841 }
8842 }
8843
junyulaif2c67e42018-08-07 19:50:45 +08008844 /**
8845 * Notify of the blocked state apps with a registered callback matching a given NAI.
8846 *
8847 * Unlike other callbacks, blocked status is different between each individual uid. So for
8848 * any given nai, all requests need to be considered according to the uid who filed it.
8849 *
8850 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008851 * @param oldMetered True if the previous network capabilities were metered.
8852 * @param newMetered True if the current network capabilities are metered.
8853 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
8854 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08008855 */
8856 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00008857 boolean newMetered, List<UidRange> oldBlockedUidRanges,
8858 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08008859
8860 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8861 NetworkRequest nr = nai.requestAt(i);
8862 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008863
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008864 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8865 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
8866 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008867 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008868 : oldVpnBlocked;
8869
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008870 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
8871 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
8872 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08008873 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008874 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08008875 }
8876 }
8877 }
8878
8879 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00008880 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08008881 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00008882 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08008883 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008884 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008885 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08008886 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008887 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00008888
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008889 final int oldBlockedState = getBlockedState(
8890 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
8891 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
8892 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08008893 continue;
junyulaif2c67e42018-08-07 19:50:45 +08008894 }
junyulaif2c67e42018-08-07 19:50:45 +08008895 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8896 NetworkRequest nr = nai.requestAt(i);
8897 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008898 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09008899 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8900 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08008901 }
8902 }
8903 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008904 }
8905
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008906 @VisibleForTesting
8907 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09008908 // The NetworkInfo we actually send out has no bearing on the real
8909 // state of affairs. For example, if the default connection is mobile,
8910 // and a request for HIPRI has just gone away, we need to pretend that
8911 // HIPRI has just disconnected. So we need to set the type to HIPRI and
8912 // the state to DISCONNECTED, even though the network is of type MOBILE
8913 // and is still connected.
8914 NetworkInfo info = new NetworkInfo(nai.networkInfo);
8915 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09008916 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008917 if (state != DetailedState.DISCONNECTED) {
8918 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09008919 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008920 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07008921 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07008922 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
8923 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
8924 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
8925 if (info.isFailover()) {
8926 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
8927 nai.networkInfo.setFailover(false);
8928 }
8929 if (info.getReason() != null) {
8930 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
8931 }
8932 if (info.getExtraInfo() != null) {
8933 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
8934 }
8935 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09008936 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08008937 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07008938 if (newDefaultAgent != null) {
8939 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
8940 newDefaultAgent.networkInfo);
8941 } else {
8942 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
8943 }
8944 }
8945 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
8946 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09008947 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008948 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09008949 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07008950 }
8951 }
8952 }
8953
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008954 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008955 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008956 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09008957 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09008958 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008959 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
8960 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008961 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8962 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008963 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008964 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008965 } else {
8966 sendPendingIntentForRequest(nri, networkAgent, notifyType);
8967 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008968 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008969 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07008970
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008971 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
8972 notifyNetworkCallbacks(networkAgent, notifyType, 0);
8973 }
8974
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08008975 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09008976 * Returns the list of all interfaces that could be used by network traffic that does not
8977 * explicitly specify a network. This includes the default network, but also all VPNs that are
8978 * currently connected.
8979 *
8980 * Must be called on the handler thread.
8981 */
junyulaie7c7d2a2021-01-26 15:29:15 +08008982 @NonNull
8983 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08008984 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08008985 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08008986 final Set<Integer> activeNetIds = new ArraySet<>();
8987 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8988 if (nri.isBeingSatisfied()) {
8989 activeNetIds.add(nri.getSatisfier().network().netId);
8990 }
8991 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008992 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
James Mattis2516da32021-01-31 17:06:19 -08008993 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09008994 defaultNetworks.add(nai.network);
8995 }
8996 }
junyulaie7c7d2a2021-01-26 15:29:15 +08008997 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09008998 }
8999
9000 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09009001 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
9002 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009003 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08009004 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009005 ensureRunningOnConnectivityServiceThread();
9006 String activeIface = null;
9007 LinkProperties activeLinkProperties = getActiveLinkProperties();
9008 if (activeLinkProperties != null) {
9009 activeIface = activeLinkProperties.getInterfaceName();
9010 }
Benedict Wong9308cd32019-06-12 17:46:31 +00009011
junyulai2050bed2021-01-23 09:46:34 +08009012 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009013 try {
junyulaide41fc22021-01-22 22:46:01 +08009014 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
junyulai69114da2021-03-05 14:46:25 +08009015 for (final NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaide41fc22021-01-22 22:46:01 +08009016 snapshots.add(snapshot);
9017 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009018 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
9019 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009020 } catch (Exception ignored) {
9021 }
9022 }
9023
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07009024 @Override
Udam Sainicd645462016-01-04 12:16:14 -08009025 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08009026 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009027 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009028 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009029
9030 if (!TextUtils.isEmpty(settingUrl)) {
9031 return settingUrl;
9032 }
9033
9034 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009035 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009036 if (!TextUtils.isEmpty(settingUrl)) {
9037 return settingUrl;
9038 }
9039
9040 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009041 }
9042
9043 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009044 public void startNattKeepalive(Network network, int intervalSeconds,
9045 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009046 enforceKeepalivePermission();
9047 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009048 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai070f9ff2019-01-16 20:23:34 +08009049 intervalSeconds, cb,
junyulai011b1f12019-01-03 18:50:15 +08009050 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009051 }
9052
9053 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009054 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009055 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulaid05a1922019-01-15 11:32:44 +08009056 String dstAddr) {
Josh Gao461a1222020-06-16 15:58:11 -07009057 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009058 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009059 mKeepaliveTracker.startNattKeepalive(
9060 getNetworkAgentInfoForNetwork(network), fd, resourceId,
9061 intervalSeconds, cb,
9062 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
9063 } finally {
9064 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9065 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009066 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9067 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009068 }
9069 }
junyulaid05a1922019-01-15 11:32:44 +08009070 }
9071
9072 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009073 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009074 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009075 try {
9076 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08009077 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009078 mKeepaliveTracker.startTcpKeepalive(
9079 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
9080 } finally {
9081 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9082 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009083 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9084 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009085 }
9086 }
junyulai0835a1e2019-01-08 20:04:33 +08009087 }
9088
9089 @Override
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009090 public void stopKeepalive(Network network, int slot) {
9091 mHandler.sendMessage(mHandler.obtainMessage(
junyulai011b1f12019-01-03 18:50:15 +08009092 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009093 }
9094
9095 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07009096 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08009097 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07009098
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009099 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08009100 final long token = Binder.clearCallingIdentity();
9101 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009102 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
9103 UserHandle.getUserHandleForUid(uid))) {
9104 return;
9105 }
9106
Heemin Seogdb8489d2019-06-12 09:21:44 -07009107 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
9108 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009109
9110 // Turn airplane mode off
9111 setAirplaneMode(false);
9112
9113 // restore private DNS settings to default mode (opportunistic)
9114 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
9115 UserHandle.getUserHandleForUid(uid))) {
9116 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
9117 PRIVATE_DNS_MODE_OPPORTUNISTIC);
9118 }
9119
9120 Settings.Global.putString(mContext.getContentResolver(),
9121 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08009122 } finally {
9123 Binder.restoreCallingIdentity(token);
9124 }
Stuart Scottd5463642015-04-02 18:00:02 -07009125 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04009126
Ricky Wai7097cc92018-01-23 04:09:45 +00009127 @Override
9128 public byte[] getNetworkWatchlistConfigHash() {
9129 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
9130 if (nwm == null) {
9131 loge("Unable to get NetworkWatchlistManager");
9132 return null;
9133 }
9134 // Redirect it to network watchlist service to access watchlist file and calculate hash.
9135 return nwm.getWatchlistConfigHash();
9136 }
9137
Hugo Benichibe0c7652016-05-31 16:28:06 +09009138 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09009139 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08009140 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09009141 }
Hugo Benichif4210292017-04-21 15:07:12 +09009142
9143 private static boolean toBool(int encodedBoolean) {
9144 return encodedBoolean != 0; // Only 0 means false.
9145 }
9146
9147 private static int encodeBool(boolean b) {
9148 return b ? 1 : 0;
9149 }
mswest4632928412018-03-12 10:34:34 -07009150
9151 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009152 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
9153 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
9154 @NonNull String[] args) {
9155 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
9156 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07009157 }
9158
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009159 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07009160 @Override
9161 public int onCommand(String cmd) {
9162 if (cmd == null) {
9163 return handleDefaultCommands(cmd);
9164 }
9165 final PrintWriter pw = getOutPrintWriter();
9166 try {
9167 switch (cmd) {
9168 case "airplane-mode":
9169 final String action = getNextArg();
9170 if ("enable".equals(action)) {
9171 setAirplaneMode(true);
9172 return 0;
9173 } else if ("disable".equals(action)) {
9174 setAirplaneMode(false);
9175 return 0;
9176 } else if (action == null) {
9177 final ContentResolver cr = mContext.getContentResolver();
9178 final int enabled = Settings.Global.getInt(cr,
9179 Settings.Global.AIRPLANE_MODE_ON);
9180 pw.println(enabled == 0 ? "disabled" : "enabled");
9181 return 0;
9182 } else {
9183 onHelp();
9184 return -1;
9185 }
9186 default:
9187 return handleDefaultCommands(cmd);
9188 }
9189 } catch (Exception e) {
9190 pw.println(e);
9191 }
9192 return -1;
9193 }
9194
9195 @Override
9196 public void onHelp() {
9197 PrintWriter pw = getOutPrintWriter();
9198 pw.println("Connectivity service commands:");
9199 pw.println(" help");
9200 pw.println(" Print this help text.");
9201 pw.println(" airplane-mode [enable|disable]");
9202 pw.println(" Turn airplane mode on or off.");
9203 pw.println(" airplane-mode");
9204 pw.println(" Get airplane mode.");
9205 }
9206 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009207
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09009208 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009209 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
9210 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
9211 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +08009212 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009213 }
9214
9215 /**
9216 * @param connectionInfo the connection to resolve.
9217 * @return {@code uid} if the connection is found and the app has permission to observe it
9218 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
9219 * connection is not found.
9220 */
9221 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009222 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
9223 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
9224 }
9225
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09009226 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009227 connectionInfo.local, connectionInfo.remote);
9228
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009229 if (uid == INVALID_UID) return uid; // Not found.
9230
9231 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
9232 // VPN, if any, that applies to the UID that owns the connection.
9233 if (checkNetworkStackPermission()) return uid;
9234
9235 final NetworkAgentInfo vpn = getVpnForUid(uid);
9236 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09009237 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009238 return INVALID_UID;
9239 }
9240
9241 return uid;
9242 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +00009243
Benedict Wong493e04b2018-11-09 14:45:34 -08009244 /**
9245 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
9246 *
9247 * <p>The TestNetworkService must be run in the system server due to TUN creation.
9248 */
9249 @Override
9250 public IBinder startOrGetTestNetworkService() {
9251 synchronized (mTNSLock) {
9252 TestNetworkService.enforceTestNetworkPermissions(mContext);
9253
9254 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +08009255 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -08009256 }
9257
9258 return mTNS;
9259 }
9260 }
Cody Kestingd199a9d2019-12-17 12:55:28 -08009261
Cody Kesting73708bf2019-12-18 10:57:50 -08009262 /**
9263 * Handler used for managing all Connectivity Diagnostics related functions.
9264 *
9265 * @see android.net.ConnectivityDiagnosticsManager
9266 *
9267 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9268 */
9269 @VisibleForTesting
9270 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009271 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9272
Cody Kesting73708bf2019-12-18 10:57:50 -08009273 /**
9274 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9275 * android.net.ConnectivityDiagnosticsManager}.
9276 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9277 * NetworkRequestInfo to be registered
9278 */
9279 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9280
9281 /**
9282 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9283 * android.net.ConnectivityDiagnosticsManager}.
9284 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9285 * arg1 = the uid of the caller
9286 */
9287 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9288
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009289 /**
9290 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
9291 * after processing {@link #EVENT_NETWORK_TESTED} events.
9292 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9293 * NetworkMonitor.
9294 * data = PersistableBundle of extras passed from NetworkMonitor.
9295 *
9296 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
9297 */
9298 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
9299
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009300 /**
9301 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9302 * been detected on the network.
9303 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9304 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9305 * arg2 = NetID.
9306 * data = PersistableBundle of extras passed from NetworkMonitor.
9307 */
9308 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9309
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009310 /**
9311 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9312 * the platform. This event will invoke {@link
9313 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9314 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -07009315 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009316 */
9317 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9318
Cody Kesting73708bf2019-12-18 10:57:50 -08009319 private ConnectivityDiagnosticsHandler(Looper looper) {
9320 super(looper);
9321 }
9322
9323 @Override
9324 public void handleMessage(Message msg) {
9325 switch (msg.what) {
9326 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9327 handleRegisterConnectivityDiagnosticsCallback(
9328 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9329 break;
9330 }
9331 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9332 handleUnregisterConnectivityDiagnosticsCallback(
9333 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9334 break;
9335 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009336 case EVENT_NETWORK_TESTED: {
9337 final ConnectivityReportEvent reportEvent =
9338 (ConnectivityReportEvent) msg.obj;
9339
Aaron Huang959d3642021-01-21 15:47:41 +08009340 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009341 break;
9342 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009343 case EVENT_DATA_STALL_SUSPECTED: {
9344 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +08009345 final Pair<Long, PersistableBundle> arg =
9346 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009347 if (nai == null) break;
9348
Aaron Huang959d3642021-01-21 15:47:41 +08009349 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009350 break;
9351 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009352 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -07009353 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009354 break;
9355 }
9356 default: {
9357 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9358 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009359 }
9360 }
9361 }
9362
9363 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9364 @VisibleForTesting
9365 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9366 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9367 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009368 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009369
9370 @VisibleForTesting
9371 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009372 @NonNull IConnectivityDiagnosticsCallback cb,
9373 @NonNull NetworkRequestInfo nri,
9374 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009375 mCb = cb;
9376 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009377 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009378 }
9379
9380 @Override
9381 public void binderDied() {
9382 log("ConnectivityDiagnosticsCallback IBinder died.");
9383 unregisterConnectivityDiagnosticsCallback(mCb);
9384 }
9385 }
9386
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009387 /**
9388 * Class used for sending information from {@link
9389 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9390 */
9391 private static class NetworkTestedResults {
9392 private final int mNetId;
9393 private final int mTestResult;
9394 private final long mTimestampMillis;
9395 @Nullable private final String mRedirectUrl;
9396
9397 private NetworkTestedResults(
9398 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9399 mNetId = netId;
9400 mTestResult = testResult;
9401 mTimestampMillis = timestampMillis;
9402 mRedirectUrl = redirectUrl;
9403 }
9404 }
9405
9406 /**
9407 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9408 * ConnectivityDiagnosticsHandler}.
9409 */
9410 private static class ConnectivityReportEvent {
9411 private final long mTimestampMillis;
9412 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +08009413 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009414
Aaron Huang959d3642021-01-21 15:47:41 +08009415 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9416 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009417 mTimestampMillis = timestampMillis;
9418 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +08009419 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009420 }
9421 }
9422
Cody Kestingf1120be2020-08-03 18:01:40 -07009423 /**
9424 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
9425 * ConnectivityDiagnosticsHandler}.
9426 */
9427 private static class ReportedNetworkConnectivityInfo {
9428 public final boolean hasConnectivity;
9429 public final boolean isNetworkRevalidating;
9430 public final int reporterUid;
9431 @NonNull public final NetworkAgentInfo nai;
9432
9433 private ReportedNetworkConnectivityInfo(
9434 boolean hasConnectivity,
9435 boolean isNetworkRevalidating,
9436 int reporterUid,
9437 @NonNull NetworkAgentInfo nai) {
9438 this.hasConnectivity = hasConnectivity;
9439 this.isNetworkRevalidating = isNetworkRevalidating;
9440 this.reporterUid = reporterUid;
9441 this.nai = nai;
9442 }
9443 }
9444
Cody Kesting73708bf2019-12-18 10:57:50 -08009445 private void handleRegisterConnectivityDiagnosticsCallback(
9446 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9447 ensureRunningOnConnectivityServiceThread();
9448
9449 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -08009450 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009451 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9452
James Mattis64b8b0f2020-11-24 17:40:49 -08009453 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9454 // confusing for these networks to change when an NRI is satisfied in another layer.
9455 if (nri.isMultilayerRequest()) {
9456 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9457 + "network requests.");
9458 }
9459
Cody Kesting73708bf2019-12-18 10:57:50 -08009460 // This means that the client registered the same callback multiple times. Do
9461 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -08009462 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009463 if (VDBG) log("Diagnostics callback is already registered");
9464
9465 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9466 // incremented when the NetworkRequestInfo is created as part of
9467 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009468 nri.decrementRequestCount();
Cody Kesting73708bf2019-12-18 10:57:50 -08009469 return;
9470 }
9471
Cody Kesting31f1ff62020-03-05 10:46:02 -08009472 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -08009473
9474 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -08009475 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009476 } catch (RemoteException e) {
9477 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -08009478 return;
9479 }
9480
9481 // Once registered, provide ConnectivityReports for matching Networks
9482 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9483 synchronized (mNetworkForNetId) {
9484 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9485 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -08009486 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9487 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -08009488 matchingNetworks.add(nai);
9489 }
9490 }
9491 }
9492 for (final NetworkAgentInfo nai : matchingNetworks) {
9493 final ConnectivityReport report = nai.getConnectivityReport();
9494 if (report == null) {
9495 continue;
9496 }
9497 if (!checkConnectivityDiagnosticsPermissions(
9498 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9499 continue;
9500 }
9501
9502 try {
9503 cb.onConnectivityReportAvailable(report);
9504 } catch (RemoteException e) {
9505 // Exception while sending the ConnectivityReport. Move on to the next network.
9506 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009507 }
9508 }
9509
9510 private void handleUnregisterConnectivityDiagnosticsCallback(
9511 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9512 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009513 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009514
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009515 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9516 mConnectivityDiagnosticsCallbacks.remove(iCb);
9517 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009518 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9519 return;
9520 }
9521
Cody Kesting2b1a61c2020-03-30 12:43:49 -07009522 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -08009523
Cody Kesting70fa2b22020-12-02 12:16:56 -08009524 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9525 // (if the Binder died)
9526 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9527 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -08009528 return;
9529 }
9530
Cody Kesting46cb1672020-03-04 13:35:20 -08009531 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9532 // incremented when the NetworkRequestInfo is created as part of
9533 // enforceRequestCountLimit().
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09009534 nri.decrementRequestCount();
Cody Kesting46cb1672020-03-04 13:35:20 -08009535
Cody Kesting31f1ff62020-03-05 10:46:02 -08009536 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009537 }
9538
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009539 private void handleNetworkTestedWithExtras(
9540 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9541 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -08009542 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009543 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009544 final ConnectivityReport report =
9545 new ConnectivityReport(
9546 reportEvent.mNai.network,
9547 reportEvent.mTimestampMillis,
9548 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009549 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009550 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -08009551 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -07009552
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009553 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009554 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009555 for (final IConnectivityDiagnosticsCallback cb : results) {
9556 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -08009557 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009558 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -07009559 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009560 }
9561 }
9562 }
9563
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009564 private void handleDataStallSuspected(
9565 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9566 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -08009567 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009568 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009569 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -08009570 new DataStallReport(
9571 nai.network,
9572 timestampMillis,
9573 detectionMethod,
9574 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -08009575 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -08009576 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009577 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009578 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009579 for (final IConnectivityDiagnosticsCallback cb : results) {
9580 try {
9581 cb.onDataStallSuspected(report);
9582 } catch (RemoteException ex) {
9583 loge("Error invoking onDataStallSuspected", ex);
9584 }
9585 }
9586 }
9587
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009588 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -07009589 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
9590 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
9591 final ConnectivityReport cachedReport = nai.getConnectivityReport();
9592
9593 // If the Network is being re-validated as a result of this call to
9594 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
9595 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009596 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -07009597 getMatchingPermissionedCallbacks(
9598 nai,
9599 reportedNetworkConnectivityInfo.isNetworkRevalidating
9600 ? Process.INVALID_UID
9601 : reportedNetworkConnectivityInfo.reporterUid);
9602
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009603 for (final IConnectivityDiagnosticsCallback cb : results) {
9604 try {
Cody Kestingf1120be2020-08-03 18:01:40 -07009605 cb.onNetworkConnectivityReported(
9606 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009607 } catch (RemoteException ex) {
9608 loge("Error invoking onNetworkConnectivityReported", ex);
9609 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009610
9611 // If the Network isn't re-validating, also provide the cached report. If there is no
9612 // cached report, the Network is still being validated and a report will be sent once
9613 // validation is complete. Note that networks which never undergo validation will still
9614 // have a cached ConnectivityReport with RESULT_SKIPPED.
9615 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
9616 try {
9617 cb.onConnectivityReportAvailable(cachedReport);
9618 } catch (RemoteException ex) {
9619 loge("Error invoking onConnectivityReportAvailable", ex);
9620 }
9621 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009622 }
9623 }
9624
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009625 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +09009626 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9627 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -08009628 sanitized.setUids(null);
9629 sanitized.setAdministratorUids(new int[0]);
9630 sanitized.setOwnerUid(Process.INVALID_UID);
9631 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -08009632 }
9633
Cody Kestingf1120be2020-08-03 18:01:40 -07009634 /**
9635 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
9636 *
9637 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
9638 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009639 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -07009640 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009641 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -08009642 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009643 mConnectivityDiagnosticsCallbacks.entrySet()) {
9644 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9645 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -07009646
James Mattis64b8b0f2020-11-24 17:40:49 -08009647 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -07009648 if (!nai.satisfies(nri.mRequests.get(0))) {
9649 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009650 }
Cody Kestingf1120be2020-08-03 18:01:40 -07009651
9652 // UID for this callback must either be:
9653 // - INVALID_UID (which sends callbacks to all UIDs), or
9654 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
9655 // notified as a result)
9656 if (uid != Process.INVALID_UID && uid != nri.mUid) {
9657 continue;
9658 }
9659
9660 if (!checkConnectivityDiagnosticsPermissions(
9661 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9662 continue;
9663 }
9664
9665 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009666 }
9667 return results;
9668 }
9669
Cody Kesting7474f672021-05-11 14:22:40 -07009670 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
9671 @NonNull NetworkAgentInfo nai) {
9672 // TODO(b/188483916): replace with a transport-agnostic location-aware check
9673 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
9674 }
9675
Cody Kesting160ef392021-05-05 13:17:22 -07009676 private boolean hasLocationPermission(String packageName, int uid) {
9677 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9678 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9679 // call in a try-catch.
9680 try {
9681 if (!mLocationPermissionChecker.checkLocationPermission(
9682 packageName, null /* featureId */, uid, null /* message */)) {
9683 return false;
9684 }
9685 } catch (SecurityException e) {
9686 return false;
9687 }
9688
9689 return true;
9690 }
9691
9692 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
9693 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +09009694 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -07009695 && virtual.networkCapabilities.getOwnerUid() == uid
9696 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
9697 return true;
9698 }
9699 }
9700
9701 return false;
9702 }
9703
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009704 @VisibleForTesting
9705 boolean checkConnectivityDiagnosticsPermissions(
9706 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9707 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9708 return true;
9709 }
9710
Cody Kesting160ef392021-05-05 13:17:22 -07009711 // Administrator UIDs also contains the Owner UID
9712 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
9713 if (!CollectionUtils.contains(administratorUids, callbackUid)
9714 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009715 return false;
9716 }
9717
Cody Kesting7474f672021-05-11 14:22:40 -07009718 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
9719 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009720 }
9721
Cody Kestingd199a9d2019-12-17 12:55:28 -08009722 @Override
9723 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009724 @NonNull IConnectivityDiagnosticsCallback callback,
9725 @NonNull NetworkRequest request,
9726 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -07009727 Objects.requireNonNull(callback, "callback must not be null");
9728 Objects.requireNonNull(request, "request must not be null");
9729 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
9730
Cody Kesting73708bf2019-12-18 10:57:50 -08009731 if (request.legacyType != TYPE_NONE) {
9732 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
9733 + " Please use NetworkCapabilities instead.");
9734 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009735 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -08009736 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009737
9738 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
9739 // and administrator uids to be safe.
9740 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08009741 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009742
9743 final NetworkRequest requestWithId =
9744 new NetworkRequest(
9745 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
9746
9747 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
9748 //
9749 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
9750 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
9751 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009752 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -08009753 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009754 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -08009755
9756 mConnectivityDiagnosticsHandler.sendMessage(
9757 mConnectivityDiagnosticsHandler.obtainMessage(
9758 ConnectivityDiagnosticsHandler
9759 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9760 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -08009761 }
9762
9763 @Override
9764 public void unregisterConnectivityDiagnosticsCallback(
9765 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +08009766 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -08009767 mConnectivityDiagnosticsHandler.sendMessage(
9768 mConnectivityDiagnosticsHandler.obtainMessage(
9769 ConnectivityDiagnosticsHandler
9770 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009771 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -08009772 0,
9773 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -08009774 }
Cody Kestingf53a0752020-04-15 12:33:28 -07009775
9776 @Override
9777 public void simulateDataStall(int detectionMethod, long timestampMillis,
9778 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -07009779 Objects.requireNonNull(network, "network must not be null");
9780 Objects.requireNonNull(extras, "extras must not be null");
9781
Cody Kestingf53a0752020-04-15 12:33:28 -07009782 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
9783 android.Manifest.permission.NETWORK_STACK);
9784 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
9785 if (!nc.hasTransport(TRANSPORT_TEST)) {
9786 throw new SecurityException("Data Stall simluation is only possible for test networks");
9787 }
9788
9789 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +09009790 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -07009791 throw new SecurityException("Data Stall simulation is only possible for network "
9792 + "creators");
9793 }
9794
Cody Kesting652e3ec2020-05-21 12:08:21 -07009795 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
9796 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
9797 // Data Stall information as a DataStallReportParcelable and passing to
9798 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
9799 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -07009800 final DataStallReportParcelable p = new DataStallReportParcelable();
9801 p.timestampMillis = timestampMillis;
9802 p.detectionMethod = detectionMethod;
9803
9804 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
9805 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
9806 }
9807 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
9808 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
9809 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
9810 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
9811 }
9812
Serik Beketayevec8ad212020-12-07 22:43:07 -08009813 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -07009814 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009815
lucaslin66f44212021-02-23 01:12:55 +08009816 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
9817 @Override
lucaslin87b58aa2021-02-25 15:10:29 +08009818 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +08009819 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +08009820 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +08009821 }
lucaslin37a16d92021-01-21 19:48:09 +08009822
9823 @Override
9824 public void onInterfaceLinkStateChanged(String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +08009825 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +08009826 nai.clatd.interfaceLinkStateChanged(iface, up);
9827 }
9828 }
9829
9830 @Override
9831 public void onInterfaceRemoved(String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +08009832 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +08009833 nai.clatd.interfaceRemoved(iface);
9834 }
lucaslin66f44212021-02-23 01:12:55 +08009835 }
9836 }
9837
lucaslin1a8b4c62021-01-21 02:02:55 +08009838 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
9839
9840 /**
9841 * Class used for updating network activity tracking with netd and notify network activity
9842 * changes.
9843 */
9844 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +08009845 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +08009846 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +08009847 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +08009848 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
9849 new RemoteCallbackList<>();
9850 // Indicate the current system default network activity is active or not.
9851 @GuardedBy("mActiveIdleTimers")
9852 private boolean mNetworkActive;
9853 @GuardedBy("mActiveIdleTimers")
9854 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
9855 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +08009856
lucaslin1193a5d2021-01-21 02:04:15 +08009857 private class IdleTimerParams {
9858 public final int timeout;
9859 public final int transportType;
9860
9861 IdleTimerParams(int timeout, int transport) {
9862 this.timeout = timeout;
9863 this.transportType = transport;
9864 }
9865 }
9866
9867 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +08009868 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +08009869 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +08009870 mNetd = netd;
9871 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +08009872 }
9873
lucaslin66f44212021-02-23 01:12:55 +08009874 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
9875 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
9876 synchronized (mActiveIdleTimers) {
9877 mNetworkActive = active;
9878 // If there are no idle timers, it means that system is not monitoring
9879 // activity, so the system default network for those default network
9880 // unspecified apps is always considered active.
9881 //
9882 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
9883 // any network activity change event. Whenever this event is received,
9884 // the mActiveIdleTimers should be always not empty. The legacy behavior
9885 // is no-op. Remove to refer to mNetworkActive only.
9886 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
9887 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
9888 }
9889 }
9890 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009891
lucaslin1193a5d2021-01-21 02:04:15 +08009892 // The network activity should only be updated from ConnectivityService handler thread
9893 // when mActiveIdleTimers lock is held.
9894 @GuardedBy("mActiveIdleTimers")
9895 private void reportNetworkActive() {
9896 final int length = mNetworkActivityListeners.beginBroadcast();
9897 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
9898 try {
9899 for (int i = 0; i < length; i++) {
9900 try {
9901 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
9902 } catch (RemoteException | RuntimeException e) {
9903 loge("Fail to send network activie to listener " + e);
9904 }
9905 }
9906 } finally {
9907 mNetworkActivityListeners.finishBroadcast();
9908 }
9909 }
9910
9911 @GuardedBy("mActiveIdleTimers")
9912 public void handleReportNetworkActivity() {
9913 synchronized (mActiveIdleTimers) {
9914 reportNetworkActive();
9915 }
9916 }
9917
lucaslin1a8b4c62021-01-21 02:02:55 +08009918 // This is deprecated and only to support legacy use cases.
9919 private int transportTypeToLegacyType(int type) {
9920 switch (type) {
9921 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009922 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +08009923 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009924 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +08009925 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009926 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +08009927 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09009928 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +08009929 default:
9930 loge("Unexpected transport in transportTypeToLegacyType: " + type);
9931 }
9932 return ConnectivityManager.TYPE_NONE;
9933 }
9934
9935 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
9936 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
9937 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
9938 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
9939 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
9940 final long ident = Binder.clearCallingIdentity();
9941 try {
9942 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
9943 RECEIVE_DATA_ACTIVITY_CHANGE,
9944 null /* resultReceiver */,
9945 null /* scheduler */,
9946 0 /* initialCode */,
9947 null /* initialData */,
9948 null /* initialExtra */);
9949 } finally {
9950 Binder.restoreCallingIdentity(ident);
9951 }
9952 }
9953
9954 /**
9955 * Setup data activity tracking for the given network.
9956 *
9957 * Every {@code setupDataActivityTracking} should be paired with a
9958 * {@link #removeDataActivityTracking} for cleanup.
9959 */
9960 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
9961 final String iface = networkAgent.linkProperties.getInterfaceName();
9962
9963 final int timeout;
9964 final int type;
9965
9966 if (networkAgent.networkCapabilities.hasTransport(
9967 NetworkCapabilities.TRANSPORT_CELLULAR)) {
9968 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009969 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +08009970 10);
9971 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9972 } else if (networkAgent.networkCapabilities.hasTransport(
9973 NetworkCapabilities.TRANSPORT_WIFI)) {
9974 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009975 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +08009976 15);
9977 type = NetworkCapabilities.TRANSPORT_WIFI;
9978 } else {
9979 return; // do not track any other networks
9980 }
9981
lucaslinb961efc2021-01-21 02:03:17 +08009982 updateRadioPowerState(true /* isActive */, type);
9983
lucaslin1a8b4c62021-01-21 02:02:55 +08009984 if (timeout > 0 && iface != null) {
9985 try {
lucaslin1193a5d2021-01-21 02:04:15 +08009986 synchronized (mActiveIdleTimers) {
9987 // Networks start up.
9988 mNetworkActive = true;
9989 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
9990 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
9991 reportNetworkActive();
9992 }
lucaslin1a8b4c62021-01-21 02:02:55 +08009993 } catch (Exception e) {
9994 // You shall not crash!
9995 loge("Exception in setupDataActivityTracking " + e);
9996 }
9997 }
9998 }
9999
10000 /**
10001 * Remove data activity tracking when network disconnects.
10002 */
10003 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
10004 final String iface = networkAgent.linkProperties.getInterfaceName();
10005 final NetworkCapabilities caps = networkAgent.networkCapabilities;
10006
lucaslinb961efc2021-01-21 02:03:17 +080010007 if (iface == null) return;
10008
10009 final int type;
10010 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
10011 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10012 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
10013 type = NetworkCapabilities.TRANSPORT_WIFI;
10014 } else {
10015 return; // do not track any other networks
10016 }
10017
10018 try {
10019 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080010020 synchronized (mActiveIdleTimers) {
10021 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
10022 // The call fails silently if no idle timer setup for this interface
10023 mNetd.idletimerRemoveInterface(iface, params.timeout,
10024 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080010025 }
lucaslinb961efc2021-01-21 02:03:17 +080010026 } catch (Exception e) {
10027 // You shall not crash!
10028 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080010029 }
10030 }
10031
10032 /**
10033 * Update data activity tracking when network state is updated.
10034 */
10035 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
10036 NetworkAgentInfo oldNetwork) {
10037 if (newNetwork != null) {
10038 setupDataActivityTracking(newNetwork);
10039 }
10040 if (oldNetwork != null) {
10041 removeDataActivityTracking(oldNetwork);
10042 }
10043 }
lucaslinb961efc2021-01-21 02:03:17 +080010044
10045 private void updateRadioPowerState(boolean isActive, int transportType) {
10046 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
10047 switch (transportType) {
10048 case NetworkCapabilities.TRANSPORT_CELLULAR:
10049 bs.reportMobileRadioPowerState(isActive, NO_UID);
10050 break;
10051 case NetworkCapabilities.TRANSPORT_WIFI:
10052 bs.reportWifiRadioPowerState(isActive, NO_UID);
10053 break;
10054 default:
10055 logw("Untracked transport type:" + transportType);
10056 }
10057 }
lucaslin1193a5d2021-01-21 02:04:15 +080010058
10059 public boolean isDefaultNetworkActive() {
10060 synchronized (mActiveIdleTimers) {
10061 // If there are no idle timers, it means that system is not monitoring activity,
10062 // so the default network is always considered active.
10063 //
10064 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
10065 // tracking is disabled (negative idle timer value configured), or no active default
10066 // network. In the latter case, this reports active but it should report inactive.
10067 return mNetworkActive || mActiveIdleTimers.isEmpty();
10068 }
10069 }
10070
10071 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
10072 mNetworkActivityListeners.register(l);
10073 }
10074
10075 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
10076 mNetworkActivityListeners.unregister(l);
10077 }
lucaslin012f7a12021-01-21 02:04:35 +080010078
10079 public void dump(IndentingPrintWriter pw) {
10080 synchronized (mActiveIdleTimers) {
10081 pw.print("mNetworkActive="); pw.println(mNetworkActive);
10082 pw.println("Idle timers:");
10083 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
10084 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
10085 final IdleTimerParams params = ent.getValue();
10086 pw.print(" timeout="); pw.print(params.timeout);
10087 pw.print(" type="); pw.println(params.transportType);
10088 }
10089 }
10090 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010091 }
James Mattis47db0582021-01-01 14:13:35 -080010092
Daniel Brightf9e945b2020-06-15 16:10:01 -070010093 /**
10094 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
10095 *
10096 * @param socketInfo the socket information
10097 * @param callback the callback to register
10098 */
10099 @Override
10100 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
10101 @NonNull final IQosCallback callback) {
10102 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
10103 if (nai == null || nai.networkCapabilities == null) {
10104 try {
10105 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
10106 } catch (final RemoteException ex) {
10107 loge("registerQosCallbackInternal: RemoteException", ex);
10108 }
10109 return;
10110 }
10111 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
10112 }
10113
10114 /**
10115 * Register a {@link IQosCallback} with base {@link QosFilter}.
10116 *
10117 * @param filter the filter to register
10118 * @param callback the callback to register
10119 * @param nai the agent information related to the filter's network
10120 */
10121 @VisibleForTesting
10122 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
10123 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
10124 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
10125 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
10126
10127 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
10128 enforceConnectivityRestrictedNetworksPermission();
10129 }
10130 mQosCallbackTracker.registerCallback(callback, filter, nai);
10131 }
10132
10133 /**
10134 * Unregisters the given callback.
10135 *
10136 * @param callback the callback to unregister
10137 */
10138 @Override
10139 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010140 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010141 mQosCallbackTracker.unregisterCallback(callback);
10142 }
James Mattis47db0582021-01-01 14:13:35 -080010143
James Mattis45d81842021-01-10 14:24:24 -080010144 /**
Chalard Jeanfa45a682021-02-25 17:23:40 +090010145 * Request that a user profile is put by default on a network matching a given preference.
10146 *
10147 * See the documentation for the individual preferences for a description of the supported
10148 * behaviors.
10149 *
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010150 * @param profile the user profile for whih the preference is being set.
10151 * @param preferences the list of profile network preferences for the
10152 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010153 * @param listener an optional listener to listen for completion of the operation.
10154 */
10155 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010156 public void setProfileNetworkPreferences(
10157 @NonNull final UserHandle profile,
10158 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090010159 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010160 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010161 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010162
10163 if (preferences.size() == 0) {
10164 preferences.add((new ProfileNetworkPreference.Builder()).build());
10165 }
10166
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010167 PermissionUtils.enforceNetworkStackPermission(mContext);
10168 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010169 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010170 }
10171 if (profile.getIdentifier() < 0) {
10172 throw new IllegalArgumentException("Must explicitly specify a user handle ("
10173 + "UserHandle.CURRENT not supported)");
10174 }
Chalard Jeana21ef9b2021-04-02 19:24:44 +090010175 final UserManager um = mContext.getSystemService(UserManager.class);
10176 if (!um.isManagedProfile(profile.getIdentifier())) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010177 throw new IllegalArgumentException("Profile must be a managed profile");
10178 }
paulhuaa0743d2021-05-26 21:56:03 +080010179
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010180 final List<ProfileNetworkPreferenceList.Preference> preferenceList =
10181 new ArrayList<ProfileNetworkPreferenceList.Preference>();
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010182 boolean allowFallback = true;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010183 for (final ProfileNetworkPreference preference : preferences) {
10184 final NetworkCapabilities nc;
10185 switch (preference.getPreference()) {
10186 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
10187 nc = null;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010188 if (preference.getPreferenceEnterpriseId() != 0) {
10189 throw new IllegalArgumentException(
10190 "Invalid enterprise identifier in setProfileNetworkPreferences");
10191 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010192 break;
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010193 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
10194 allowFallback = false;
10195 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010196 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010197 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
10198 throw new IllegalArgumentException(
10199 "Invalid enterprise identifier in setProfileNetworkPreferences");
10200 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010201 final Set<UidRange> uidRangeSet =
10202 getUidListToBeAppliedForNetworkPreference(profile, preference);
10203 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
10204 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
10205 } else {
10206 throw new IllegalArgumentException(
10207 "Overlapping uid range in setProfileNetworkPreferences");
10208 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010209 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010210 nc.addEnterpriseId(
10211 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010212 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10213 break;
10214 default:
10215 throw new IllegalArgumentException(
10216 "Invalid preference in setProfileNetworkPreferences");
10217 }
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010218 preferenceList.add(new ProfileNetworkPreferenceList.Preference(
10219 profile, nc, allowFallback));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010220 }
10221 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010222 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010223 }
10224
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010225 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
10226 @NonNull final UserHandle profile,
10227 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
10228 final UidRange profileUids = UidRange.createForUser(profile);
10229 Set<UidRange> uidRangeSet = UidRangeUtils.convertListToUidRange(
10230 profileNetworkPreference.getIncludedUids());
10231 if (uidRangeSet.size() > 0) {
10232 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
10233 throw new IllegalArgumentException(
10234 "Allow uid range is outside the uid range of profile.");
10235 }
10236 } else {
10237 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertListToUidRange(
10238 profileNetworkPreference.getExcludedUids());
10239 if (disallowUidRangeSet.size() > 0) {
10240 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
10241 throw new IllegalArgumentException(
10242 "disallow uid range is outside the uid range of profile.");
10243 }
10244 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
10245 disallowUidRangeSet);
10246 } else {
10247 uidRangeSet = new ArraySet<UidRange>();
10248 uidRangeSet.add(profileUids);
10249 }
10250 }
10251 return uidRangeSet;
10252 }
10253
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010254 private boolean isEnterpriseIdentifierValid(
10255 @NetworkCapabilities.EnterpriseId int identifier) {
10256 if ((identifier >= NET_ENTERPRISE_ID_1)
10257 && (identifier <= NET_ENTERPRISE_ID_5)) {
10258 return true;
10259 }
10260 return false;
10261 }
10262
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010263 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
10264 @Nullable final NetworkCapabilities nc) {
10265 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
10266 ensureRequestableCapabilities(nc);
10267 }
10268
10269 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010270 @NonNull final ProfileNetworkPreferenceList prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010271 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010272 for (final ProfileNetworkPreferenceList.Preference pref : prefs.preferences) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010273 // The NRI for a user should contain the request for capabilities.
10274 // If fallback to default network is needed then NRI should include
10275 // the request for the default network. Create an image of it to
10276 // have the correct UIDs in it (also a request can only be part of one NRI, because
10277 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010278 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
10279 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010280 if (pref.allowFallback) {
10281 nrs.add(createDefaultInternetRequestForTransport(
10282 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10283 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010284 if (VDBG) {
10285 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
10286 pref.capabilities.getUids()));
10287 }
10288
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010289 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080010290 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080010291 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010292 result.add(nri);
10293 }
10294 return result;
10295 }
10296
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010297 /**
10298 * Compare if the given UID range sets have the same UIDs.
10299 *
10300 */
10301 private boolean isRangeAlreadyInPreferenceList(
10302 @NonNull List<ProfileNetworkPreferenceList.Preference> preferenceList,
10303 @NonNull Set<UidRange> uidRangeSet) {
10304 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
10305 return false;
10306 }
10307 for (ProfileNetworkPreferenceList.Preference pref : preferenceList) {
10308 if (UidRangeUtils.doesRangeSetOverlap(
10309 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
10310 return true;
10311 }
10312 }
10313 return false;
10314 }
10315
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010316 private void handleSetProfileNetworkPreference(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010317 @NonNull final List<ProfileNetworkPreferenceList.Preference> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010318 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010319 for (final ProfileNetworkPreferenceList.Preference preference : preferenceList) {
10320 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
10321 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
10322 }
paulhu74128522021-09-28 02:29:03 +000010323 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
10324 addPerAppDefaultNetworkRequests(
10325 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010326 // Finally, rematch.
10327 rematchAllNetworksAndRequests();
10328
10329 if (null != listener) {
10330 try {
10331 listener.onComplete();
10332 } catch (RemoteException e) {
10333 loge("Listener for setProfileNetworkPreference has died");
10334 }
10335 }
10336 }
10337
paulhu51f77dc2021-06-07 02:34:20 +000010338 @VisibleForTesting
10339 @NonNull
10340 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
10341 @NonNull final Set<Integer> uids) {
10342 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10343 if (uids.size() == 0) {
10344 // Should not create NetworkRequestInfo if no preferences. Without uid range in
10345 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
10346 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
10347 return nris;
10348 }
10349
10350 final List<NetworkRequest> requests = new ArrayList<>();
10351 // The NRI should be comprised of two layers:
10352 // - The request for the mobile network preferred.
10353 // - The request for the default network, for fallback.
10354 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090010355 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000010356 requests.add(createDefaultInternetRequestForTransport(
10357 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10358 final Set<UidRange> ranges = new ArraySet<>();
10359 for (final int uid : uids) {
10360 ranges.add(new UidRange(uid, uid));
10361 }
10362 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080010363 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080010364 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000010365 return nris;
10366 }
10367
10368 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000010369 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000010370 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
10371 addPerAppDefaultNetworkRequests(
10372 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000010373 // Finally, rematch.
10374 rematchAllNetworksAndRequests();
10375 }
10376
James Mattis45d81842021-01-10 14:24:24 -080010377 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080010378 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
10379 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080010380 }
10381
10382 /**
10383 * Used by automotive devices to set the network preferences used to direct traffic at an
10384 * application level as per the given OemNetworkPreferences. An example use-case would be an
10385 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
10386 * vehicle via a particular network.
10387 *
10388 * Calling this will overwrite the existing preference.
10389 *
James Mattisda32cfe2021-01-26 16:23:52 -080010390 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090010391 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080010392 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080010393 */
James Mattis47db0582021-01-01 14:13:35 -080010394 @Override
James Mattis45d81842021-01-10 14:24:24 -080010395 public void setOemNetworkPreference(
10396 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010397 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080010398
James Mattisfa270db2021-05-31 17:11:10 -070010399 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10400 // Only bypass the permission/device checks if this is a valid test request.
10401 if (isValidTestOemNetworkPreference(preference)) {
10402 enforceManageTestNetworksPermission();
10403 } else {
10404 enforceAutomotiveDevice();
10405 enforceOemNetworkPreferencesPermission();
10406 validateOemNetworkPreferences(preference);
10407 }
James Mattis45d81842021-01-10 14:24:24 -080010408
James Mattis45d81842021-01-10 14:24:24 -080010409 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
10410 new Pair<>(preference, listener)));
10411 }
10412
James Mattisfa270db2021-05-31 17:11:10 -070010413 /**
10414 * Check the validity of an OEM network preference to be used for testing purposes.
10415 * @param preference the preference to validate
10416 * @return true if this is a valid OEM network preference test request.
10417 */
10418 private boolean isValidTestOemNetworkPreference(
10419 @NonNull final OemNetworkPreferences preference) {
10420 // Allow for clearing of an existing OemNetworkPreference used for testing.
10421 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
10422 // changes after this check is complete. This is an unlikely scenario as calling of this API
10423 // is controlled by the OEM therefore the added complexity is not worth adding given those
10424 // circumstances. That said, it is an edge case to be aware of hence this comment.
10425 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
10426 && isTestOemNetworkPreference(mOemNetworkPreferences);
10427 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
10428 }
10429
10430 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
10431 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
10432 return prefMap.size() == 1
10433 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
10434 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
10435 }
10436
James Mattis45d81842021-01-10 14:24:24 -080010437 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
10438 for (@OemNetworkPreferences.OemNetworkPreference final int pref
10439 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070010440 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
10441 throw new IllegalArgumentException(
10442 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
10443 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080010444 }
10445 }
10446 }
10447
10448 private void handleSetOemNetworkPreference(
10449 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010450 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080010451 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10452 if (DBG) {
10453 log("set OEM network preferences :" + preference.toString());
10454 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010455
James Mattiscb1e0362021-04-06 17:07:42 -070010456 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000010457 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
10458 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
10459 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080010460 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080010461
10462 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010463 try {
10464 listener.onComplete();
10465 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080010466 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010467 }
James Mattis45d81842021-01-10 14:24:24 -080010468 }
10469 }
10470
paulhu74128522021-09-28 02:29:03 +000010471 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080010472 // Skip the requests which are set by other network preference. Because the uid range rules
10473 // should stay in netd.
10474 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080010475 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080010476 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080010477 }
10478
James Mattis3ce3d3c2021-02-09 18:18:28 -080010479 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
10480 ensureRunningOnConnectivityServiceThread();
10481 mDefaultNetworkRequests.addAll(nris);
10482 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
10483 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080010484 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000010485 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
10486 nrisToRegister.addAll(
10487 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
10488 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010489 }
10490
10491 /**
10492 * All current requests that are tracking the default network need to be assessed as to whether
10493 * or not the current set of per-application default requests will be changing their default
10494 * network. If so, those requests will need to be updated so that they will send callbacks for
10495 * default network changes at the appropriate time. Additionally, those requests tracking the
10496 * default that were previously updated by this flow will need to be reassessed.
10497 * @return the nris which will need to be updated.
10498 */
10499 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
10500 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
10501 // Get the distinct nris to check since for multilayer requests, it is possible to have the
10502 // same nri in the map's values for each of its NetworkRequest objects.
10503 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080010504 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010505 // Include this nri if it is currently being tracked.
10506 if (isPerAppTrackedNri(nri)) {
10507 defaultCallbackRequests.add(nri);
10508 continue;
10509 }
10510 // We only track callbacks for requests tracking the default.
10511 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
10512 continue;
10513 }
10514 // Include this nri if it will be tracked by the new per-app default requests.
10515 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010516 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080010517 if (isNriGoingToBeTracked) {
10518 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080010519 }
10520 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080010521 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080010522 }
10523
James Mattis3ce3d3c2021-02-09 18:18:28 -080010524 /**
10525 * Create nris for those network requests that are currently tracking the default network that
10526 * are being controlled by a per-application default.
10527 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
10528 * foundation when creating the nri. Important items include the calling uid's original
10529 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
10530 * requests are assumed to have already been validated as needing to be updated.
10531 * @return the Set of nris to use when registering network requests.
10532 */
10533 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
10534 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
10535 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
10536 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
10537 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010538 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010539
Chalard Jean9473c982021-07-29 20:03:04 +090010540 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080010541 if (trackingNri == mDefaultRequest) {
10542 callbackRequestsToRegister.add(new NetworkRequestInfo(
10543 callbackRequest,
10544 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
10545 continue;
10546 }
10547
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010548 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080010549 callbackRequestsToRegister.add(new NetworkRequestInfo(
10550 callbackRequest,
10551 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010552 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090010553 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080010554 }
10555 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080010556 }
10557
Chalard Jean17215832021-03-01 14:06:28 +090010558 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
10559 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090010560 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010561 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090010562 }
10563 }
10564
James Mattis45d81842021-01-10 14:24:24 -080010565 /**
10566 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
10567 */
10568 @VisibleForTesting
10569 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010570 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080010571 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080010572 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080010573 final SparseArray<Set<Integer>> uids =
10574 createUidsFromOemNetworkPreferences(preference);
10575 for (int i = 0; i < uids.size(); i++) {
10576 final int key = uids.keyAt(i);
10577 final Set<Integer> value = uids.valueAt(i);
10578 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
10579 // No need to add an nri without any requests.
10580 if (0 == nri.mRequests.size()) {
10581 continue;
10582 }
10583 nris.add(nri);
10584 }
10585
10586 return nris;
10587 }
10588
10589 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
10590 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070010591 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080010592 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080010593 final List<UserHandle> users =
10594 mContext.getSystemService(UserManager.class).getUserHandles(true);
10595 if (null == users || users.size() == 0) {
10596 if (VDBG || DDBG) {
10597 log("No users currently available for setting the OEM network preference.");
10598 }
James Mattisb6b6a432021-06-01 22:30:36 -070010599 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080010600 }
James Mattis45d81842021-01-10 14:24:24 -080010601 for (final Map.Entry<String, Integer> entry :
10602 preference.getNetworkPreferences().entrySet()) {
10603 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070010604 // Add the rules for all users as this policy is device wide.
10605 for (final UserHandle user : users) {
10606 try {
10607 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
10608 if (!prefToUids.contains(pref)) {
10609 prefToUids.put(pref, new ArraySet<>());
10610 }
10611 prefToUids.get(pref).add(uid);
10612 } catch (PackageManager.NameNotFoundException e) {
10613 // Although this may seem like an error scenario, it is ok that uninstalled
10614 // packages are sent on a network preference as the system will watch for
10615 // package installations associated with this network preference and update
10616 // accordingly. This is done to minimize race conditions on app install.
10617 continue;
James Mattis45d81842021-01-10 14:24:24 -080010618 }
James Mattis45d81842021-01-10 14:24:24 -080010619 }
10620 }
James Mattisb6b6a432021-06-01 22:30:36 -070010621 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080010622 }
10623
10624 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10625 @OemNetworkPreferences.OemNetworkPreference final int preference,
10626 @NonNull final Set<Integer> uids) {
10627 final List<NetworkRequest> requests = new ArrayList<>();
10628 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10629 switch (preference) {
10630 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10631 requests.add(createUnmeteredNetworkRequest());
10632 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070010633 requests.add(createDefaultInternetRequestForTransport(
10634 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080010635 break;
10636 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10637 requests.add(createUnmeteredNetworkRequest());
10638 requests.add(createOemPaidNetworkRequest());
10639 break;
10640 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10641 requests.add(createOemPaidNetworkRequest());
10642 break;
10643 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10644 requests.add(createOemPrivateNetworkRequest());
10645 break;
James Mattisfa270db2021-05-31 17:11:10 -070010646 case OEM_NETWORK_PREFERENCE_TEST:
10647 requests.add(createUnmeteredNetworkRequest());
10648 requests.add(createTestNetworkRequest());
10649 requests.add(createDefaultRequest());
10650 break;
10651 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
10652 requests.add(createTestNetworkRequest());
10653 break;
James Mattis45d81842021-01-10 14:24:24 -080010654 default:
10655 // This should never happen.
10656 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10657 + " called with invalid preference of " + preference);
10658 }
10659
James Mattisfa270db2021-05-31 17:11:10 -070010660 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090010661 for (final int uid : uids) {
10662 ranges.add(new UidRange(uid, uid));
10663 }
10664 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080010665 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080010666 }
10667
10668 private NetworkRequest createUnmeteredNetworkRequest() {
10669 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10670 .addCapability(NET_CAPABILITY_NOT_METERED)
10671 .addCapability(NET_CAPABILITY_VALIDATED);
10672 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10673 }
10674
10675 private NetworkRequest createOemPaidNetworkRequest() {
10676 // NET_CAPABILITY_OEM_PAID is a restricted capability.
10677 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10678 .addCapability(NET_CAPABILITY_OEM_PAID)
10679 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10680 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10681 }
10682
10683 private NetworkRequest createOemPrivateNetworkRequest() {
10684 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
10685 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10686 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
10687 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10688 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10689 }
10690
10691 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070010692 final NetworkCapabilities netcap = new NetworkCapabilities();
10693 netcap.addCapability(NET_CAPABILITY_INTERNET);
10694 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
10695 return netcap;
10696 }
10697
10698 private NetworkRequest createTestNetworkRequest() {
10699 final NetworkCapabilities netcap = new NetworkCapabilities();
10700 netcap.clearAll();
10701 netcap.addTransportType(TRANSPORT_TEST);
10702 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080010703 }
James Mattis47db0582021-01-01 14:13:35 -080010704 }
markchien738ad912021-12-09 18:15:45 +080010705
10706 @Override
10707 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
10708 enforceNetworkStackOrSettingsPermission();
10709
10710 try {
10711 if (add) {
10712 mNetd.bandwidthAddNiceApp(uid);
10713 } else {
10714 mNetd.bandwidthRemoveNiceApp(uid);
10715 }
10716 } catch (RemoteException | ServiceSpecificException e) {
10717 throw new IllegalStateException(e);
10718 }
10719 }
10720
10721 @Override
10722 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
10723 enforceNetworkStackOrSettingsPermission();
10724
10725 try {
10726 if (add) {
10727 mNetd.bandwidthAddNaughtyApp(uid);
10728 } else {
10729 mNetd.bandwidthRemoveNaughtyApp(uid);
10730 }
10731 } catch (RemoteException | ServiceSpecificException e) {
10732 throw new IllegalStateException(e);
10733 }
10734 }
markchiene1561fa2021-12-09 22:00:56 +080010735
10736 @Override
10737 public void updateFirewallRule(final int chain, final int uid, final boolean allow) {
10738 enforceNetworkStackOrSettingsPermission();
10739
10740 try {
10741 mNetd.firewallSetUidRule(chain, uid,
10742 allow ? INetd.FIREWALL_RULE_ALLOW : INetd.FIREWALL_RULE_DENY);
10743 } catch (RemoteException | ServiceSpecificException e) {
10744 throw new IllegalStateException(e);
10745 }
10746 }
markchien98a6f952022-01-13 23:43:53 +080010747
10748 @Override
10749 public void setFirewallChainEnabled(final int chain, final boolean enable) {
10750 enforceNetworkStackOrSettingsPermission();
10751
10752 try {
10753 mNetd.firewallEnableChildChain(chain, enable);
10754 } catch (RemoteException | ServiceSpecificException e) {
10755 throw new IllegalStateException(e);
10756 }
10757 }
10758
markchien00a0bed2022-01-13 23:46:13 +080010759 @Override
10760 public void replaceFirewallChain(final int chain, final int[] uids) {
10761 enforceNetworkStackOrSettingsPermission();
10762
10763 try {
10764 switch (chain) {
10765 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
10766 mNetd.firewallReplaceUidChain("fw_dozable", true /* isAllowList */, uids);
10767 break;
10768 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
10769 mNetd.firewallReplaceUidChain("fw_standby", false /* isAllowList */, uids);
10770 break;
10771 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
10772 mNetd.firewallReplaceUidChain("fw_powersave", true /* isAllowList */, uids);
10773 break;
10774 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
10775 mNetd.firewallReplaceUidChain("fw_restricted", true /* isAllowList */, uids);
10776 break;
10777 default:
10778 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
10779 + chain);
10780 }
10781 } catch (RemoteException | ServiceSpecificException e) {
10782 throw new IllegalStateException(e);
10783 }
10784 }
markchien9c806112022-01-11 23:28:23 +080010785
10786 @Override
10787 public void swapActiveStatsMap() {
10788 enforceNetworkStackOrSettingsPermission();
10789 try {
10790 mNetd.trafficSwapActiveStatsMap();
10791 } catch (RemoteException | ServiceSpecificException e) {
10792 throw new IllegalStateException(e);
10793 }
10794 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070010795}