blob: c95295cb875c1e18cf31ba2aaa3da801d345ddf6 [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;
Mark Fasheh7c999d82023-05-04 20:23:11 +000020import static android.app.ActivityManager.UidFrozenStateChangedCallback.UID_FROZEN_STATE_FROZEN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090021import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
22import static android.content.pm.PackageManager.FEATURE_WATCH;
23import static android.content.pm.PackageManager.FEATURE_WIFI;
24import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
Chalard Jean9a396cc2018-02-21 18:43:54 +090025import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +090026import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
27import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
28import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
29import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
33import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090034import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
35import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka98215562021-03-23 08:12:28 +000036import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
Jeff Sharkey971cd162011-08-29 16:02:57 -070037import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
markchien3c04e662022-03-22 16:29:56 +080038import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
39import static android.net.ConnectivityManager.FIREWALL_RULE_DEFAULT;
40import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090041import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090042import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090043import static android.net.ConnectivityManager.TYPE_MOBILE;
44import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
45import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
46import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
47import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
48import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
49import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
50import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
51import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
52import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070053import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090054import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070055import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090056import static android.net.ConnectivityManager.TYPE_WIFI;
57import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070058import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070059import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080060import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080061import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080062import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070063import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080064import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen53f08952015-06-16 14:27:36 -040065import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090066import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090067import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090068import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090069import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090070import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
71import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060072import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090073import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080074import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090075import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080076import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
77import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080078import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090079import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080080import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
81import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080082import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
83import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
84import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090085import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090086import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060087import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070088import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080089import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090090import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070091import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
92import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070093import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080094import static android.os.Process.VPN_UID;
Motomu Utsumi278db582023-04-21 12:35:22 +090095import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
Patrick Rohr2857ac42022-01-21 14:58:16 +010096import static android.system.OsConstants.ETH_P_ALL;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070097import static android.system.OsConstants.IPPROTO_TCP;
98import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey07e19362017-10-27 17:22:59 -060099
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900100import static com.android.net.module.util.DeviceConfigUtils.TETHERING_MODULE_NAME;
Xiao Ma60142372022-07-16 17:30:20 +0900101import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Junyu Lai4c6fe232023-04-11 11:33:46 +0800102import static com.android.net.module.util.PermissionUtils.checkAnyPermissionOf;
paulhu3ffffe72021-09-16 10:15:22 +0800103import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
104import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
105import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900106
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800107import static java.util.Map.Entry;
108
Chalard Jean5b639762020-03-09 21:25:37 +0900109import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000110import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800111import android.annotation.Nullable;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800112import android.annotation.TargetApi;
Mark Fasheh7c999d82023-05-04 20:23:11 +0000113import android.app.ActivityManager;
114import android.app.ActivityManager.UidFrozenStateChangedCallback;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800115import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800116import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700117import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700118import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900119import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800120import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700121import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800122import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800123import android.content.ContentResolver;
124import android.content.Context;
125import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700126import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800127import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900128import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700129import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900130import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900131import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700132import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800133import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800134import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800135import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900136import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800137import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900138import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800139import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900140import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800141import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700142import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900143import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800144import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800145import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800146import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800147import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800148import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900149import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900150import android.net.INetworkMonitor;
151import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900152import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900153import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700154import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800155import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900156import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900157import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900158import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800159import android.net.LinkProperties;
Charles He9369e612017-05-15 17:07:18 +0100160import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800161import android.net.NativeNetworkConfig;
162import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800163import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700164import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700165import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900166import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700167import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800168import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700169import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900170import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900171import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000172import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900173import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700174import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900175import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700176import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900177import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700178import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800179import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900180import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700181import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000182import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800183import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900184import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800185import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400186import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700187import android.net.QosCallbackException;
188import android.net.QosFilter;
189import android.net.QosSocketFilter;
190import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700191import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800192import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800193import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800194import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900195import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400196import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800197import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800198import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400199import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800200import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900201import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900202import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900203import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900204import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800205import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900206import android.net.networkstack.ModuleNetworkStackClient;
207import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900208import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800209import android.net.resolv.aidl.DnsHealthEventParcel;
210import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
211import android.net.resolv.aidl.Nat64PrefixEventParcel;
212import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900213import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900214import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800215import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800216import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800217import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700218import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000219import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800220import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700221import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700222import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800223import android.os.Looper;
224import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700225import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700226import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900227import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800228import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700229import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700230import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800231import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700232import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900233import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900234import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700235import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700236import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400237import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800238import android.provider.Settings;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900239import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700240import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700241import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700242import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800243import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900244import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000245import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600246import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900247import android.util.Pair;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900248import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700249import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700250import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800251
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800252import androidx.annotation.RequiresApi;
253
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900254import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400255import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400256import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700257import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900258import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800259import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900260import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800261import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000262import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900263import com.android.net.module.util.BitUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900264import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900265import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100266import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900267import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
268import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900269import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800270import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800271import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100272import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000273import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800274import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
275import com.android.networkstack.apishim.ConstantsShim;
276import com.android.networkstack.apishim.common.BroadcastOptionsShim;
277import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900278import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900279import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000280import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900281import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800282import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800283import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900284import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900285import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900286import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500287import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700288import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900289import com.android.server.connectivity.FullScore;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900290import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900291import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000292import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100293import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700294import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900295import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700296import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600297import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900298import com.android.server.connectivity.NetworkNotificationManager;
299import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900300import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900301import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900302import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700303import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900304import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900305import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700306import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800307import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000308import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800309import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600310
Josh Gao461a1222020-06-16 15:58:11 -0700311import libcore.io.IoUtils;
312
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900313import org.xmlpull.v1.XmlPullParserException;
314
The Android Open Source Project28527d22009-03-03 19:31:44 -0800315import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100316import java.io.IOException;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900317import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800318import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900319import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700320import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700321import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900322import java.net.InetSocketAddress;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900323import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700324import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700325import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700326import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700327import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800328import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900329import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800330import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700331import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700332import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700333import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700334import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900335import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700336import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900337import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600338import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900339import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600340import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900341import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800342
343/**
344 * @hide
345 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800346public class ConnectivityService extends IConnectivityManager.Stub
347 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900348 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800349
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900350 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900351 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900352 private static final String NETWORK_ARG = "networks";
353 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800354 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900355
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900356 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900357 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
358 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800359
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900360 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700361
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100362 /**
363 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
364 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800365 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100366 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
367 * (preferably via runtime resource overlays).
368 */
369 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
370 "http://connectivitycheck.gstatic.com/generate_204";
371
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700372 // TODO: create better separation between radio types and network types
373
Robert Greenwalt2034b912009-08-12 16:08:25 -0700374 // how long to wait before switching back to a radio's default network
375 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
376 // system property that can override the above value
377 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
378 "android.telephony.apn-restore";
379
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900380 // How long to wait before putting up a "This network doesn't have an Internet connection,
381 // connect anyway?" dialog after the user selects a network that doesn't validate.
382 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
383
Chalard Jean5fb43c72022-09-08 19:03:14 +0900384 // How long to wait before considering that a network is bad in the absence of any form
385 // of connectivity (valid, partial, captive portal). If none has been detected after this
386 // delay, the stack considers this network bad, which may affect how it's handled in ranking
387 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900388 // Timeout in case the "actively prefer bad wifi" feature is on
389 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
390 // Timeout in case the "actively prefer bad wifi" feature is off
391 private static final int DONT_ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900392
junyulai0ac374f2020-12-14 18:41:52 +0800393 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900394 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
395 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800396 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700397
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800398 // Delimiter used when creating the broadcast delivery group for sending
399 // CONNECTIVITY_ACTION broadcast.
400 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
401
he_won.hwang881307a2022-03-15 21:23:52 +0900402 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900403 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900404
Daniel Brightf9e945b2020-06-15 16:10:01 -0700405 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900406 @VisibleForTesting
407 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700408
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900409 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700410 @VisibleForTesting
411 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900412
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900413 @VisibleForTesting
414 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800415 @VisibleForTesting
416 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900417 // True if the cell radio of the device is capable of time-sharing.
418 @VisibleForTesting
419 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900420
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800421 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800422 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800423 private final int mReleasePendingIntentDelayMs;
424
Chalard Jean46bfbf02022-02-02 00:56:25 +0900425 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900426
Motomu Utsumif360aa62023-01-30 17:52:20 +0900427 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700428
Chalard Jean9473c982021-07-29 20:03:04 +0900429 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800430 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700431 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800432 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700433
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900434 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700435
junyulaif2c67e42018-08-07 19:50:45 +0800436 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000437 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
438 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800439 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900440 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800441
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900442 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900443 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000444 // The Context is created for UserHandle.ALL.
445 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900446 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900447 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700448 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700449 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800450
Chenbo Feng15416292018-11-08 17:36:21 -0800451 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800452 protected IDnsResolver mDnsResolver;
453 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800454 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700455 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900456 private final NetworkStatsManager mStatsManager;
457 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800458 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700459
Benedict Wong493e04b2018-11-09 14:45:34 -0800460 /**
461 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
462 * instances.
463 */
464 @GuardedBy("mTNSLock")
465 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800466 private final CompanionDeviceManagerProxyService mCdmps;
Benedict Wong493e04b2018-11-09 14:45:34 -0800467
468 private final Object mTNSLock = new Object();
469
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700470 private String mCurrentTcpBufferSizes;
471
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900472 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000473 new Class[] {
474 ConnectivityService.class,
475 NetworkAgent.class,
476 NetworkAgentInfo.class,
477 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900478
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500479 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400480 // Tear down networks that have no chance (e.g. even if validated) of becoming
481 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500482 // all networks have been rematched against all NetworkRequests.
483 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400484 // Don't reap networks. This should be passed when some networks have not yet been
485 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500486 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900487 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500488
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900489 private enum UnneededFor {
490 LINGER, // Determine whether this network is unneeded and should be lingered.
491 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
492 }
493
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700494 /**
paulhuaa0743d2021-05-26 21:56:03 +0800495 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800496 * should have priority. The order is passed to netd which will use it together
497 * with UID ranges to generate the corresponding IP rule. This serves to
498 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800499 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800500 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000501 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800502 *
paulhu48291862021-07-14 14:53:57 +0800503 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
504 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800505 */
paulhu48291862021-07-14 14:53:57 +0800506 // Used when sending to netd to code for "no order".
507 static final int PREFERENCE_ORDER_NONE = 0;
508 // Order for requests that don't code for a per-app preference. As it is
509 // out of the valid range, the corresponding order should be
510 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800511 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800512 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800513 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800514 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
515 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800516 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800517 static final int PREFERENCE_ORDER_OEM = 10;
518 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800519 // See {@link #setProfileNetworkPreference}.
520 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800521 static final int PREFERENCE_ORDER_PROFILE = 20;
522 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800523 // better scores are connected.
524 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800525 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800526 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900527 // Preference order that signifies the network shouldn't be set as a default network for
528 // the UIDs, only give them access to it. TODO : replace this with a boolean
529 // in NativeUidRangeConfig
530 @VisibleForTesting
531 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
532 // Bound for the lowest valid preference order.
533 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800534
535 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700536 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700537 * from one net to another. Clear happens when we get a new
538 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
539 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700540 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700541 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700542
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700543 /**
544 * used internally to reload global proxy settings
545 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700546 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700547
Robert Greenwalt34848c02011-03-25 13:09:25 -0700548 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400549 * PAC manager has received new port.
550 */
551 private static final int EVENT_PROXY_HAS_CHANGED = 16;
552
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700553 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900554 * used internally when registering NetworkProviders
555 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700556 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900557 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700558
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700559 /**
560 * used internally when registering NetworkAgents
561 * obj = Messenger
562 */
563 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
564
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700565 /**
566 * used to add a network request
567 * includes a NetworkRequestInfo
568 */
569 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
570
571 /**
572 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900573 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700574 * cancel it.
575 * includes a NetworkRequestInfo
576 */
577 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
578
579 /**
580 * used to add a network listener - no request
581 * includes a NetworkRequestInfo
582 */
583 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
584
585 /**
586 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400587 * arg1 = UID of caller
588 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700589 */
590 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
591
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700592 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900593 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700594 * obj = Messenger
595 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900596 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700597
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700598 /**
599 * used internally to expire a wakelock when transitioning
600 * from one net to another. Expire happens when we fail to find
601 * a new network (typically after 1 minute) -
602 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
603 * a replacement network.
604 */
605 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
606
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700607 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800608 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400609 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800610 */
611 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
612
613 /**
614 * used to remove a pending intent and its associated network request.
615 * arg1 = UID of caller
616 * obj = PendingIntent
617 */
618 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
619
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900620 /**
621 * used to specify whether a network should be used even if unvalidated.
622 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
623 * arg2 = whether to remember this choice in the future (1 or 0)
624 * obj = network
625 */
626 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
627
628 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700629 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900630 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700631 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900632
Paul Jensenc8873fc2015-06-17 14:15:39 -0400633 /**
634 * used to add a network listener with a pending intent
635 * obj = NetworkRequestInfo
636 */
637 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
638
Hugo Benichid6b510a2017-04-06 17:22:18 +0900639 /**
640 * used to specify whether a network should not be penalized when it becomes unvalidated.
641 */
642 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
643
644 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700645 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900646 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700647 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900648
Erik Kline31b4a9e2018-01-11 21:07:29 +0900649 // Handle changes in Private DNS settings.
650 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
651
dalyk1720e542018-03-05 12:42:22 -0500652 // Handle private DNS validation status updates.
653 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
654
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900655 /**
656 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
657 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800658 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
659 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
660 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900661 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900662 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900663
664 /**
665 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
666 * config was resolved.
667 * obj = PrivateDnsConfig
668 * arg2 = netid
669 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900670 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900671
672 /**
673 * Request ConnectivityService display provisioning notification.
674 * arg1 = Whether to make the notification visible.
675 * arg2 = NetID.
676 * obj = Intent to be launched when notification selected by user, null if !arg1.
677 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900678 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900679
680 /**
lucaslin2240ef62019-03-12 13:08:03 +0800681 * Used to specify whether a network should be used even if connectivity is partial.
682 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
683 * false)
684 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
685 * obj = network
686 */
lucaslin444d43a2020-02-20 16:56:59 +0800687 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800688
689 /**
lucasline117e2e2019-10-22 18:27:33 +0800690 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
691 * Both of the arguments are bitmasks, and the value of bits come from
692 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900693 * arg1 = unused
694 * arg2 = netId
695 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800696 */
lucaslin444d43a2020-02-20 16:56:59 +0800697 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800698
699 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900700 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
701 * arg1 = unused
702 * arg2 = netId
703 * obj = captive portal data
704 */
lucaslin444d43a2020-02-20 16:56:59 +0800705 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900706
707 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900708 * Used by setRequireVpnForUids.
709 * arg1 = whether the specified UID ranges are required to use a VPN.
710 * obj = Array of UidRange objects.
711 */
712 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
713
714 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900715 * Used internally when setting the default networks for OemNetworkPreferences.
716 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800717 */
718 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
719
720 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800721 * Used to indicate the system default network becomes active.
722 */
723 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
724
725 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900726 * Used internally when setting a network preference for a user profile.
727 * obj = Pair<ProfileNetworkPreference, Listener>
728 */
729 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
730
731 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000732 * Event to specify that reasons for why an uid is blocked changed.
733 * arg1 = uid
734 * arg2 = blockedReasons
735 */
736 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
737
738 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900739 * Event to register a new network offer
740 * obj = NetworkOffer
741 */
742 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
743
744 /**
745 * Event to unregister an existing network offer
746 * obj = INetworkOfferCallback
747 */
748 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
749
750 /**
paulhu51f77dc2021-06-07 02:34:20 +0000751 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
752 */
753 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
754
755 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800756 * Event to set temporary allow bad wifi within a limited time to override
757 * {@code config_networkAvoidBadWifi}.
758 */
759 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
760
761 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100762 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
763 */
764 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
765
766 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900767 * The initial evaluation period is over for this network.
768 *
769 * If no form of connectivity has been found on this network (valid, partial, captive portal)
770 * then the stack will now consider it to have been determined bad.
771 */
772 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
773
774 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000775 * Used internally when the user does not want the network from captive portal app.
776 * obj = Network
777 */
778 private static final int EVENT_USER_DOES_NOT_WANT = 58;
779
780 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000781 * Event to set VPN as preferred network for specific apps.
782 * obj = VpnNetworkPreferenceInfo
783 */
784 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
785
786 /**
chiachangwange0192a72023-02-06 13:25:01 +0000787 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
788 */
789 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
790
791 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +0000792 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
793 */
794 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
795
796 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900797 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
798 * should be shown.
799 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900800 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900801
802 /**
803 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
804 * should be hidden.
805 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900806 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900807
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800808 /**
809 * The maximum alive time to allow bad wifi configuration for testing.
810 */
811 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
812
Patrick Rohr2857ac42022-01-21 14:58:16 +0100813 /**
chiachangwange0192a72023-02-06 13:25:01 +0000814 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
815 * testing.
816 */
817 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
818
819 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100820 * The priority of the tc police rate limiter -- smaller value is higher priority.
821 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
822 */
823 private static final short TC_PRIO_POLICE = 1;
824
825 /**
826 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
827 */
828 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700829 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100830
Hugo Benichi47011212017-03-30 10:46:05 +0900831 private static String eventName(int what) {
832 return sMagicDecoderRing.get(what, Integer.toString(what));
833 }
834
paulhua10d8212020-11-10 15:32:56 +0800835 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900836 final DnsResolverServiceManager dsm = context.getSystemService(
837 DnsResolverServiceManager.class);
838 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800839 }
840
Cody Kesting73708bf2019-12-18 10:57:50 -0800841 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900842 @VisibleForTesting
843 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700844 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700845 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700846 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700847 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800848 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
849 @VisibleForTesting
850 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
851
Erik Kline32120082017-12-13 19:40:49 +0900852 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900853 @VisibleForTesting
854 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700855
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400856 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800857 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400858
Chalard Jean46bfbf02022-02-02 00:56:25 +0900859 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800860 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700861
Chalard Jean5d70ba42018-06-07 16:44:04 +0900862 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
863 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +0800864 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400865
Erik Kline05f2b402015-04-30 12:58:40 +0900866 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700867
Chalard Jean46bfbf02022-02-02 00:56:25 +0900868 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400869
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700870 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900871 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700872
Valentin Iftime9fa35092019-09-24 13:32:13 +0200873 private Set<String> mWolSupportedInterfaces;
874
Roshan Pius08c94fb2020-01-16 12:17:17 -0800875 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800876 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800877 private final AppOpsManager mAppOpsManager;
878
879 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400880
chiachangwang3d60bac2023-01-17 14:38:08 +0000881 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900882 private final QosCallbackTracker mQosCallbackTracker;
883 private final NetworkNotificationManager mNotifier;
884 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900885
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700886 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800887 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700888
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900889 // Sequence number for NetworkProvider IDs.
890 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
891 NetworkProvider.FIRST_PROVIDER_ID);
892
Erik Klineedf878b2015-07-09 18:24:03 +0900893 // NetworkRequest activity String log entries.
894 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
895 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
896
Hugo Benichid159fdd2016-07-11 11:05:12 +0900897 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900898 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900899 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
900
Hugo Benichi47011212017-03-30 10:46:05 +0900901 private static final int MAX_WAKELOCK_LOGS = 20;
902 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900903 private int mTotalWakelockAcquisitions = 0;
904 private int mTotalWakelockReleases = 0;
905 private long mTotalWakelockDurationMs = 0;
906 private long mMaxWakelockDurationMs = 0;
907 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900908
Hugo Benichi208c0102016-07-28 17:53:06 +0900909 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900910
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700911 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900912 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700913
Erik Kline95ecfee2016-10-02 18:02:14 +0900914 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900915 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900916
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900917 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800918 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
919 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800920
Patrick Rohr2857ac42022-01-21 14:58:16 +0100921 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
922 // configured via {@link
923 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
924 // Only the handler thread is allowed to access this field.
925 private long mIngressRateLimit = -1;
926
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900927 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
928 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900929 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900930 @GuardedBy("mSelfCertifiedCapabilityCache")
931 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
932 mSelfCertifiedCapabilityCache = new HashMap<>();
933
Robert Greenwalt802c1102014-06-02 15:32:02 -0700934 /**
935 * Implements support for the legacy "one network per network type" model.
936 *
937 * We used to have a static array of NetworkStateTrackers, one for each
938 * network type, but that doesn't work any more now that we can have,
939 * for example, more that one wifi network. This class stores all the
940 * NetworkAgentInfo objects that support a given type, but the legacy
941 * API will only see the first one.
942 *
943 * It serves two main purposes:
944 *
945 * 1. Provide information about "the network for a given type" (since this
946 * API only supports one).
947 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
948 * the first network for a given type changes, or if the default network
949 * changes.
950 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900951 @VisibleForTesting
952 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900953
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900954 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900955 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900956
Robert Greenwalt802c1102014-06-02 15:32:02 -0700957 /**
958 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
959 * Each list holds references to all NetworkAgentInfos that are used to
960 * satisfy requests for that network type.
961 *
962 * This array is built out at startup such that an unsupported network
963 * doesn't get an ArrayList instance, making this a tristate:
964 * unsupported, supported but not active and active.
965 *
966 * The actual lists are populated when we scan the network types that
967 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900968 *
969 * Threading model:
970 * - addSupportedType() is only called in the constructor
971 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
972 * They are therefore not thread-safe with respect to each other.
973 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
974 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900975 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900976 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700977 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900978 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900979 @NonNull
980 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700981
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900982 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
983 // an entry have no timer (equivalent to -1). Lazily loaded.
984 @NonNull
985 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
986
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900987 LegacyTypeTracker(@NonNull ConnectivityService service) {
988 mService = service;
989 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700990 }
991
Chiachang Wang3bc52762021-11-25 14:17:57 +0800992 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
993 // addressed.
994 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900995 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
996 final PackageManager pm = ctx.getPackageManager();
997 if (pm.hasSystemFeature(FEATURE_WIFI)) {
998 addSupportedType(TYPE_WIFI);
999 }
1000 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1001 addSupportedType(TYPE_WIFI_P2P);
1002 }
1003 if (tm.isDataCapable()) {
1004 // Telephony does not have granular support for these types: they are either all
1005 // supported, or none is supported
1006 addSupportedType(TYPE_MOBILE);
1007 addSupportedType(TYPE_MOBILE_MMS);
1008 addSupportedType(TYPE_MOBILE_SUPL);
1009 addSupportedType(TYPE_MOBILE_DUN);
1010 addSupportedType(TYPE_MOBILE_HIPRI);
1011 addSupportedType(TYPE_MOBILE_FOTA);
1012 addSupportedType(TYPE_MOBILE_IMS);
1013 addSupportedType(TYPE_MOBILE_CBS);
1014 addSupportedType(TYPE_MOBILE_IA);
1015 addSupportedType(TYPE_MOBILE_EMERGENCY);
1016 }
1017 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1018 addSupportedType(TYPE_BLUETOOTH);
1019 }
1020 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1021 // TYPE_PROXY is only used on Wear
1022 addSupportedType(TYPE_PROXY);
1023 }
1024 // Ethernet is often not specified in the configs, although many devices can use it via
1025 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001026 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001027 addSupportedType(TYPE_ETHERNET);
1028 }
1029
1030 // Always add TYPE_VPN as a supported type
1031 addSupportedType(TYPE_VPN);
1032 }
1033
1034 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001035 if (mTypeLists[type] != null) {
1036 throw new IllegalStateException(
1037 "legacy list for type " + type + "already initialized");
1038 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001039 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001040 }
1041
Robert Greenwalt802c1102014-06-02 15:32:02 -07001042 public boolean isTypeSupported(int type) {
1043 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1044 }
1045
1046 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001047 synchronized (mTypeLists) {
1048 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1049 return mTypeLists[type].get(0);
1050 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001051 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001052 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001053 }
1054
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001055 public int getRestoreTimerForType(int type) {
1056 synchronized (mTypeLists) {
1057 if (mRestoreTimers == null) {
1058 mRestoreTimers = loadRestoreTimers();
1059 }
1060 return mRestoreTimers.getOrDefault(type, -1);
1061 }
1062 }
1063
1064 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1065 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001066 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001067 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1068 for (final String config : configs) {
1069 final String[] splits = TextUtils.split(config, ",");
1070 if (splits.length != 2) {
1071 logwtf("Invalid restore timer token count: " + config);
1072 continue;
1073 }
1074 try {
1075 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1076 } catch (NumberFormatException e) {
1077 logwtf("Invalid restore timer number format: " + config, e);
1078 }
1079 }
1080 return ret;
1081 }
1082
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001083 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001084 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001085 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001086 log("Sending " + state
1087 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001088 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001089 }
1090 }
1091
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001092 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1093 // network type, to preserve previous behaviour.
1094 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1095 if (vpnNai != mService.getLegacyLockdownNai()) return;
1096
1097 if (vpnNai.declaredUnderlyingNetworks == null
1098 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1099 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1100 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1101 return;
1102 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001103 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001104 vpnNai.declaredUnderlyingNetworks[0]);
1105 if (underlyingNai == null) return;
1106
1107 final int type = underlyingNai.networkInfo.getType();
1108 final DetailedState state = DetailedState.CONNECTED;
1109 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1110 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1111 }
1112
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001113 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001114 public void add(int type, NetworkAgentInfo nai) {
1115 if (!isTypeSupported(type)) {
1116 return; // Invalid network type.
1117 }
1118 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1119
1120 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1121 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001122 return;
1123 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001124 synchronized (mTypeLists) {
1125 list.add(nai);
1126 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001127
Chalard Jean5b409c72021-02-04 13:12:59 +09001128 // Send a broadcast if this is the first network of its type or if it's the default.
1129 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001130
1131 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1132 // to preserve previous behaviour.
1133 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001134 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001135 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1136 mService.sendLegacyNetworkBroadcast(nai, state, type);
1137 }
1138
1139 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1140 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001141 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001142 }
1143
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001144 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001145 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001146 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1147 if (list == null || list.isEmpty()) {
1148 return;
1149 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001150 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001151
Hugo Benichi389633f2016-06-21 09:48:07 +09001152 synchronized (mTypeLists) {
1153 if (!list.remove(nai)) {
1154 return;
1155 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001156 }
1157
Lorenzo Colitti49767722015-05-01 00:30:10 +09001158 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001159 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1160 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001161 }
1162
1163 if (!list.isEmpty() && wasFirstNetwork) {
1164 if (DBG) log("Other network available for type " + type +
1165 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001166 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001167 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001168 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001169 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001170 }
1171 }
1172
1173 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001174 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1175 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001176 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001177 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001178 }
1179 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001180
Chalard Jean46bfbf02022-02-02 00:56:25 +09001181 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001182 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001183 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001184 final DetailedState state = nai.networkInfo.getDetailedState();
1185 for (int type = 0; type < mTypeLists.length; type++) {
1186 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001187 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001188 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001189 if (isFirst || contains && isDefault) {
1190 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001191 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001192 }
1193 }
1194 }
1195
Robert Greenwalt94e22142014-07-30 16:31:24 -07001196 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001197 pw.println("mLegacyTypeTracker:");
1198 pw.increaseIndent();
1199 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001200 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001201 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001202 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001203 pw.println();
1204 pw.println("Current state:");
1205 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001206 synchronized (mTypeLists) {
1207 for (int type = 0; type < mTypeLists.length; type++) {
1208 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1209 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001210 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001211 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001212 }
1213 }
1214 pw.decreaseIndent();
1215 pw.decreaseIndent();
1216 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001217 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001218 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001219 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001220
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001221 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001222 /**
1223 * Helper class which parses out priority arguments and dumps sections according to their
1224 * priority. If priority arguments are omitted, function calls the legacy dump command.
1225 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001226 private class LocalPriorityDump {
1227 private static final String PRIORITY_ARG = "--dump-priority";
1228 private static final String PRIORITY_ARG_HIGH = "HIGH";
1229 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1230
1231 LocalPriorityDump() {}
1232
1233 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1234 doDump(fd, pw, new String[] {DIAG_ARG});
1235 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001236 }
1237
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001238 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1239 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001240 }
1241
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001242 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1243 if (args == null) {
1244 dumpNormal(fd, pw, args);
1245 return;
1246 }
1247
1248 String priority = null;
1249 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1250 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1251 argIndex++;
1252 priority = args[argIndex];
1253 }
1254 }
1255
1256 if (PRIORITY_ARG_HIGH.equals(priority)) {
1257 dumpHigh(fd, pw);
1258 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1259 dumpNormal(fd, pw, args);
1260 } else {
1261 // ConnectivityService publishes binder service using publishBinderService() with
1262 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001263 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1264 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001265 // TODO: Integrate into signal dump.
1266 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001267 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001268 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001269 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001270
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001271 /**
1272 * Dependencies of ConnectivityService, for injection in tests.
1273 */
1274 @VisibleForTesting
1275 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001276 public int getCallingUid() {
1277 return Binder.getCallingUid();
1278 }
1279
Chalard Jeandf29a852023-05-29 17:02:43 +09001280 public boolean isAtLeastS() {
1281 return SdkLevel.isAtLeastS();
1282 }
1283
1284 public boolean isAtLeastT() {
1285 return SdkLevel.isAtLeastT();
1286 }
1287
1288 public boolean isAtLeastU() {
1289 return SdkLevel.isAtLeastU();
1290 }
1291
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001292 /**
1293 * Get system properties to use in ConnectivityService.
1294 */
1295 public MockableSystemProperties getSystemProperties() {
1296 return new MockableSystemProperties();
1297 }
1298
1299 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001300 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1301 */
1302 public ConnectivityResources getResources(@NonNull Context ctx) {
1303 return new ConnectivityResources(ctx);
1304 }
1305
1306 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001307 * Create a HandlerThread to use in ConnectivityService.
1308 */
1309 public HandlerThread makeHandlerThread() {
1310 return new HandlerThread("ConnectivityServiceThread");
1311 }
1312
1313 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001314 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001315 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001316 public NetworkStackClientBase getNetworkStack() {
1317 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001318 }
1319
1320 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001321 * @see ProxyTracker
1322 */
1323 public ProxyTracker makeProxyTracker(@NonNull Context context,
1324 @NonNull Handler connServiceHandler) {
1325 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1326 }
1327
1328 /**
1329 * @see NetIdManager
1330 */
1331 public NetIdManager makeNetIdManager() {
1332 return new NetIdManager();
1333 }
1334
1335 /**
1336 * @see NetworkUtils#queryUserAccess(int, int)
1337 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001338 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1339 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001340 }
1341
1342 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001343 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1344 * requires CAP_NET_ADMIN, which the unit tests do not have.
1345 */
1346 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1347 InetSocketAddress remote) {
1348 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1349 }
1350
1351 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001352 * @see MultinetworkPolicyTracker
1353 */
1354 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1355 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1356 return new MultinetworkPolicyTracker(c, h, r);
1357 }
1358
Aaron Huang330a4c02020-10-27 03:36:19 +08001359 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001360 * @see AutomaticOnOffKeepaliveTracker
1361 */
1362 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1363 @NonNull Context c, @NonNull Handler h) {
1364 return new AutomaticOnOffKeepaliveTracker(c, h);
1365 }
1366
1367 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001368 * @see BatteryStatsManager
1369 */
1370 public void reportNetworkInterfaceForTransports(Context context, String iface,
1371 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001372 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001373 context.getSystemService(BatteryStatsManager.class);
1374 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1375 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001376
1377 public boolean getCellular464XlatEnabled() {
1378 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1379 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001380
1381 /**
1382 * @see PendingIntent#intentFilterEquals
1383 */
1384 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1385 return a.intentFilterEquals(b);
1386 }
1387
1388 /**
1389 * @see LocationPermissionChecker
1390 */
1391 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1392 return new LocationPermissionChecker(context);
1393 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001394
1395 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001396 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001397 *
1398 * This method returns null in versions before T, where carrier privilege
1399 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001400 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001401 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001402 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1403 @NonNull final Context context, @NonNull final TelephonyManager tm) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001404 if (isAtLeastT()) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09001405 return new CarrierPrivilegeAuthenticator(context, tm);
1406 } else {
1407 return null;
1408 }
1409 }
1410
1411 /**
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001412 * @see DeviceConfigUtils#isFeatureEnabled
1413 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001414 public boolean isFeatureEnabled(Context context, String name) {
1415 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING, name,
1416 TETHERING_MODULE_NAME, false /* defaultValue */);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001417 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001418
1419 /**
1420 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001421 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001422 * @return BpfNetMaps implementation.
1423 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001424 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1425 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001426 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001427
1428 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001429 * @see ClatCoordinator
1430 */
1431 public ClatCoordinator getClatCoordinator(INetd netd) {
1432 return new ClatCoordinator(
1433 new ClatCoordinator.Dependencies() {
1434 @NonNull
1435 public INetd getNetd() {
1436 return netd;
1437 }
1438 });
1439 }
1440
1441 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001442 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1443 */
1444 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1445 final InterfaceParams params = InterfaceParams.getByName(iface);
1446 if (params == null) {
1447 // the interface might have disappeared.
1448 logw("Failed to get interface params for interface " + iface);
1449 return;
1450 }
1451 try {
1452 // converting rateInBytesPerSecond from long to int is safe here because the
1453 // setting's range is limited to INT_MAX.
1454 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001455 Log.i(TAG,
1456 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001457 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1458 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1459 } catch (IOException e) {
1460 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1461 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1462 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1463 + ") failure: ", e);
1464 }
1465 }
1466
1467 /**
1468 * Wraps {@link TcUtils#tcFilterDelDev}
1469 */
1470 public void disableIngressRateLimit(String iface) {
1471 final InterfaceParams params = InterfaceParams.getByName(iface);
1472 if (params == null) {
1473 // the interface might have disappeared.
1474 logw("Failed to get interface params for interface " + iface);
1475 return;
1476 }
1477 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001478 Log.i(TAG,
1479 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001480 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1481 } catch (IOException e) {
1482 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1483 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1484 }
1485 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001486
1487 /**
1488 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1489 */
1490 // TODO: when available in all active branches:
1491 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1492 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1493 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1494 return BroadcastOptionsShimImpl.newInstance(options);
1495 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001496
1497 /**
1498 * Wrapper method for
1499 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1500 *
1501 * @param changeId The ID of the compatibility change in question.
1502 * @param packageName The package name of the app in question.
1503 * @param user The user that the operation is done for.
1504 * @return {@code true} if the change is enabled for the specified package.
1505 */
1506 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1507 @NonNull final UserHandle user) {
1508 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1509 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001510
1511 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001512 * As above but with a UID.
1513 * @see CompatChanges#isChangeEnabled(long, int)
1514 */
1515 public boolean isChangeEnabled(final long changeId, final int uid) {
1516 return CompatChanges.isChangeEnabled(changeId, uid);
1517 }
1518
1519 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001520 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1521 *
1522 * @param ranges target uid ranges
1523 * @param exemptUids uids to skip close socket
1524 */
1525 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1526 @NonNull final Set<Integer> exemptUids)
1527 throws SocketException, InterruptedIOException, ErrnoException {
1528 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1529 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001530
1531 /**
1532 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1533 *
1534 * @param ownerUids target uids to close sockets
1535 */
1536 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1537 throws SocketException, InterruptedIOException, ErrnoException {
1538 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1539 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001540
1541 /**
1542 * Schedule the evaluation timeout.
1543 *
1544 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1545 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1546 * of these events happen, this time will run out, after which the network is considered
1547 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1548 * on this network and considers it won't provide connectivity. In particular, that means
1549 * it's when the system prefers it to cell if it's wifi and configuration says it should
1550 * prefer bad wifi to cell.
1551 */
1552 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1553 @NonNull final Network network, final long delayMs) {
1554 handler.sendMessageDelayed(
1555 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1556 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001557 }
1558
junyulaie7c7d2a2021-01-26 15:29:15 +08001559 public ConnectivityService(Context context) {
1560 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001561 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1562 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001563 }
1564
1565 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001566 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1567 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001568 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001569
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001570 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001571 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001572 mSystemProperties = mDeps.getSystemProperties();
1573 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001574 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001575 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001576 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1577 // Pass limit - 1 to maintain backward compatibility.
1578 // TODO: Remove the workaround.
1579 mNetworkRequestCounter =
1580 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1581 mSystemNetworkRequestCounter =
1582 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001583
Hugo Benichi208c0102016-07-28 17:53:06 +09001584 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001585 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1586 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001587 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001588 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001589 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001590 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1591 mDefaultNetworkRequests.add(mDefaultRequest);
1592 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001593
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001594 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001595 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001596
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001597 // The default WiFi request is a background request so that apps using WiFi are
1598 // migrated to a better network (typically ethernet) when one comes up, instead
1599 // of staying on WiFi forever.
1600 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1601 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1602
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001603 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1604 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1605 NetworkRequest.Type.BACKGROUND_REQUEST);
1606
Chalard Jean0702f982021-09-16 21:50:07 +09001607 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1608 // TODO: Consider making the timer customizable.
1609 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1610 mCellularRadioTimesharingCapable =
1611 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1612
Paul Hu51f816b2022-08-11 14:43:47 +00001613 mNetd = netd;
1614 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001615 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001616 mPermissionMonitor =
1617 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001618 mHandlerThread.start();
1619 mHandler = new InternalHandler(mHandlerThread.getLooper());
1620 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001621 mConnectivityDiagnosticsHandler =
1622 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001623
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001624 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001625 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001626
junyulaie7c7d2a2021-01-26 15:29:15 +08001627 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001628 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001629 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001630 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001631
Wink Saville32506bc2013-06-29 21:10:57 -07001632 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001633 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001634 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001635 mCarrierPrivilegeAuthenticator =
1636 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001637
Sudheer Shanka9967d462021-03-18 19:09:25 +00001638 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001639 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1640 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001641 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001642
1643 final PowerManager powerManager = (PowerManager) context.getSystemService(
1644 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001645 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001646 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001647
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001648 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1649 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001650 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001651 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001652 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001653 mProtectedNetworks.add(p);
1654 } else {
1655 if (DBG) loge("Ignoring protectedNetwork " + p);
1656 }
1657 }
1658
soma, kawata29444ae2019-05-23 09:30:40 +09001659 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1660
James Mattis02220e22021-03-13 19:27:21 -08001661 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001662 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001663 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001664 final IntentFilter userIntentFilter = new IntentFilter();
1665 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1666 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1667 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1668 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001669
James Mattis02220e22021-03-13 19:27:21 -08001670 // Listen to package add/removes for netd
1671 final IntentFilter packageIntentFilter = new IntentFilter();
1672 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1673 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1674 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1675 packageIntentFilter.addDataScheme("package");
1676 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001677 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001678
lucaslind5c2d072021-02-20 18:59:47 +08001679 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001680
Chalard Jean46bfbf02022-02-02 00:56:25 +09001681 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001682 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001683 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001684 } catch (RemoteException | ServiceSpecificException e) {
1685 loge("Error registering event listener :" + e);
1686 }
1687
Erik Kline05f2b402015-04-30 12:58:40 +09001688 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1689 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001690
chiachangwang7c17c282023-02-02 05:58:59 +00001691 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001692 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001693 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001694
1695 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001696 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001697 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1698 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001699 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001700 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1701 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001702
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001703 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001704 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001705 mNetworkRanker =
1706 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1707
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001708 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001709
Chiachang Wangc1215d32020-10-20 15:38:58 +08001710 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001711 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001712
Chalard Jean28018572020-12-21 18:36:52 +09001713 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1714 // request that doesn't allow fallback to the default network. It should never be visible
1715 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1716 // arguments like the handler or the DnsResolver.
1717 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001718 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001719 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001720 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001721 new LinkProperties(), new NetworkCapabilities(),
1722 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001723 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1724 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001725
1726 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001727 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1728 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1729 // Even if it could, running on S would at least require mocking out the BPF map,
1730 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1731 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001732 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001733 mDscpPolicyTracker = new DscpPolicyTracker();
1734 }
Tyler Wear72388212021-09-09 14:49:02 -07001735 } catch (ErrnoException e) {
1736 loge("Unable to create DscpPolicyTracker");
1737 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001738
1739 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1740 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001741
Chalard Jeandf29a852023-05-29 17:02:43 +09001742 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001743 mCdmps = new CompanionDeviceManagerProxyService(context);
1744 } else {
1745 mCdmps = null;
1746 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001747
Chalard Jeandf29a852023-05-29 17:02:43 +09001748 if (mDeps.isAtLeastU()
Mark Fasheh7c999d82023-05-04 20:23:11 +00001749 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION)) {
1750 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1751 new UidFrozenStateChangedCallback() {
1752 @Override
1753 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1754 if (uids.length != frozenStates.length) {
1755 Log.wtf(TAG, "uids has length " + uids.length
1756 + " but frozenStates has length " + frozenStates.length);
1757 return;
1758 }
1759
1760 final UidFrozenStateChangedArgs args =
1761 new UidFrozenStateChangedArgs(uids, frozenStates);
1762
1763 mHandler.sendMessage(
1764 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1765 }
1766 };
1767
1768 final ActivityManager activityManager =
1769 mContext.getSystemService(ActivityManager.class);
1770 activityManager.registerUidFrozenStateChangedCallback(
1771 (Runnable r) -> r.run(), frozenStateChangedCallback);
1772 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001773 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001774
Xiao Ma0a171c02022-01-23 16:14:51 +00001775 /**
1776 * Check whether or not the device supports Ethernet transport.
1777 */
1778 public static boolean deviceSupportsEthernet(final Context context) {
1779 final PackageManager pm = context.getPackageManager();
1780 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1781 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1782 }
1783
Chalard Jean46adcf32018-04-18 20:18:38 +09001784 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001785 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1786 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001787 }
1788
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001789 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1790 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001791 final NetworkCapabilities netCap = new NetworkCapabilities();
1792 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001793 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001794 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001795 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001796 return netCap;
1797 }
1798
James Mattis45d81842021-01-10 14:24:24 -08001799 private NetworkRequest createDefaultRequest() {
1800 return createDefaultInternetRequestForTransport(
1801 TYPE_NONE, NetworkRequest.Type.REQUEST);
1802 }
1803
lucaslin3ba7cc22022-12-19 02:35:33 +00001804 private NetworkRequest createVpnRequest() {
1805 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1806 .withoutDefaultCapabilities()
1807 .addTransportType(TRANSPORT_VPN)
1808 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1809 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1810 .build();
1811 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1812 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1813 }
1814
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001815 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001816 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001817 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001818 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001819 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001820 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001821 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001822 netCap.addTransportType(transportType);
1823 }
James Mattis45d81842021-01-10 14:24:24 -08001824 return createNetworkRequest(type, netCap);
1825 }
1826
1827 private NetworkRequest createNetworkRequest(
1828 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001829 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001830 }
1831
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001832 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1833 NetworkRequest.Type type) {
1834 final NetworkCapabilities netCap = new NetworkCapabilities();
1835 netCap.clearAll();
1836 netCap.addCapability(capability);
1837 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1838 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1839 }
1840
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001841 // Used only for testing.
1842 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001843 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001844 // changing ContentResolver to make registerContentObserver non-final).
1845 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1846 // by subclassing SettingsObserver.
1847 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001848 void updateAlwaysOnNetworks() {
1849 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001850 }
1851
Erik Kline9a62f012018-03-21 07:18:33 -07001852 // See FakeSettingsProvider comment above.
1853 @VisibleForTesting
1854 void updatePrivateDnsSettings() {
1855 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1856 }
1857
paulhu51f77dc2021-06-07 02:34:20 +00001858 @VisibleForTesting
1859 void updateMobileDataPreferredUids() {
1860 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1861 }
1862
Patrick Rohr2857ac42022-01-21 14:58:16 +01001863 @VisibleForTesting
1864 void updateIngressRateLimit() {
1865 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1866 }
1867
Aaron Huang40b52442021-06-08 04:34:24 +08001868 @VisibleForTesting
1869 void simulateUpdateProxyInfo(@Nullable final Network network,
1870 @NonNull final ProxyInfo proxyInfo) {
1871 Message.obtain(mHandler, EVENT_PROXY_HAS_CHANGED,
1872 new Pair<>(network, proxyInfo)).sendToTarget();
1873 }
1874
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001875 private void handleAlwaysOnNetworkRequest(
1876 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001877 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001878 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001879 handleAlwaysOnNetworkRequest(networkRequest, enable);
1880 }
1881
1882 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001883 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001884 if (enable == isEnabled) {
1885 return; // Nothing to do.
1886 }
1887
1888 if (enable) {
1889 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001890 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001891 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001892 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001893 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001894 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1895 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001896 }
1897 }
1898
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001899 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001900 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1901 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1902 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1903 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001904 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1905 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001906 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001907 }
1908
paulhu51f77dc2021-06-07 02:34:20 +00001909 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001910 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001911 private void registerSettingsCallbacks() {
1912 // Watch for global HTTP proxy changes.
1913 mSettingsObserver.observe(
1914 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1915 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1916
Chalard Jean46bfbf02022-02-02 00:56:25 +09001917 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09001918 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001919 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001920 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1921
Chalard Jean46bfbf02022-02-02 00:56:25 +09001922 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001923 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001924 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001925 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001926
1927 // Watch for mobile data preferred uids changes.
1928 mSettingsObserver.observe(
1929 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1930 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001931
1932 // Watch for ingress rate limit changes.
1933 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01001934 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01001935 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
1936 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001937 }
1938
Erik Kline31b4a9e2018-01-11 21:07:29 +09001939 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001940 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1941 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001942 }
1943 }
1944
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001945 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001946 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1947 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001948 return mNextNetworkRequestId++;
1949 }
1950
junyulai74f9a8b2018-06-13 15:00:37 +08001951 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09001952 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08001953 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001954 if (network == null) {
1955 return null;
1956 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001957 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001958 }
1959
1960 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001961 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001962 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001963 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001964 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001965
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001966 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001967 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001968 private NetworkAgentInfo getVpnForUid(int uid) {
1969 synchronized (mNetworkForNetId) {
1970 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1971 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09001972 if (nai.isVPN() && nai.everConnected()
1973 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001974 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001975 }
1976 }
1977 }
1978 return null;
1979 }
1980
Chalard Jean46bfbf02022-02-02 00:56:25 +09001981 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001982 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001983 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001984 final NetworkAgentInfo nai = getVpnForUid(uid);
1985 if (nai != null) return nai.declaredUnderlyingNetworks;
1986 return null;
1987 }
1988
Lorenzo Colittia7574052021-01-19 01:33:05 +09001989 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001990 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001991
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001992 final Network[] networks = getVpnUnderlyingNetworks(uid);
1993 if (networks != null) {
1994 // getUnderlyingNetworks() returns:
1995 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1996 // empty array => the VPN explicitly said "no default network".
1997 // non-empty array => the VPN specified one or more default networks; we use the
1998 // first one.
1999 if (networks.length > 0) {
2000 nai = getNetworkAgentInfoForNetwork(networks[0]);
2001 } else {
2002 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002003 }
2004 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002005 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002006 }
2007
2008 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002009 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002010 */
paulhu7aeba372020-12-30 00:42:19 +08002011 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2012 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002013 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002014 if (ignoreBlocked) {
2015 return false;
2016 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002017 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002018 final long ident = Binder.clearCallingIdentity();
2019 try {
2020 final boolean metered = nc == null ? true : nc.isMetered();
2021 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2022 } finally {
2023 Binder.restoreCallingIdentity(ident);
2024 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002025 }
2026
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002027 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002028 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2029 return;
2030 }
Hugo Benichi47011212017-03-30 10:46:05 +09002031 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002032 synchronized (mBlockedAppUids) {
2033 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002034 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002035 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002036 blocked = false;
2037 } else {
2038 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002039 }
2040 }
Hugo Benichi47011212017-03-30 10:46:05 +09002041 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2042 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2043 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002044 }
2045
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002046 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002047 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2048 return;
2049 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002050 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002051 final int requestId = nri.getActiveRequest() != null
2052 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002053 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002054 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002055 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002056 }
2057
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002058 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002059 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002060 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002061 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002062 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002063 @NonNull
2064 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2065 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002066 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2067 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2068 // but only exists if an app asks about them or requests them. Ensure the requesting app
2069 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002070 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002071 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2072 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2073 null /* extraInfo */);
2074 }
2075 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002076 return filtered;
2077 }
2078
2079 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2080 boolean ignoreBlocked) {
2081 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2082 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002083 }
2084
2085 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002086 * Return NetworkInfo for the active (i.e., connected) network interface.
2087 * It is assumed that at most one network is active at a time. If more
2088 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002089 * @return the info for the active network, or {@code null} if none is
2090 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002091 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002092 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002093 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002094 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002095 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002096 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002097 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2098 if (nai == null) return null;
2099 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2100 maybeLogBlockedNetworkInfo(networkInfo, uid);
2101 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002102 }
2103
Paul Jensen1f567382015-02-13 14:18:39 -05002104 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002105 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002106 public Network getActiveNetwork() {
2107 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002108 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002109 }
2110
2111 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002112 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002113 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002114 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002115 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002116 }
2117
Chalard Jean46bfbf02022-02-02 00:56:25 +09002118 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002119 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002120 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2121 if (vpnNai != null) {
2122 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2123 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2124 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002125 }
Paul Jensen1f567382015-02-13 14:18:39 -05002126 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002127
James Mattis2516da32021-01-31 17:06:19 -08002128 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002129 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2130 ignoreBlocked)) {
2131 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002132 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002133 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002134 }
2135
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002136 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002137 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002138 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002139 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002140 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2141 if (nai == null) return null;
2142 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002143 }
2144
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002145 /** Returns a NetworkInfo object for a network that doesn't exist. */
2146 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2147 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2148 getNetworkTypeName(networkType), "" /* subtypeName */);
2149 info.setIsAvailable(true);
2150 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2151 // background data is restricted.
2152 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2153 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2154 ? DetailedState.BLOCKED
2155 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002156 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2157 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002158 return info;
2159 }
2160
Lorenzo Colittia7574052021-01-19 01:33:05 +09002161 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002162 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2163 return null;
2164 }
2165 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002166 if (nai == null) {
2167 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002168 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002169 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2170 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002171 }
2172
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002173 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002174 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002175 public NetworkInfo getNetworkInfo(int networkType) {
2176 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002177 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002178 if (getVpnUnderlyingNetworks(uid) != null) {
2179 // A VPN is active, so we may need to return one of its underlying networks. This
2180 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002181 // getNetworkAgentInfoForUid.
2182 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2183 if (nai == null) return null;
2184 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2185 if (networkInfo.getType() == networkType) {
2186 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002187 }
2188 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002189 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002190 }
2191
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002192 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002193 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002194 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002195 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002196 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002197 if (nai == null) return null;
2198 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002199 }
2200
2201 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002202 public NetworkInfo[] getAllNetworkInfo() {
2203 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002204 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002205 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2206 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002207 NetworkInfo info = getNetworkInfo(networkType);
2208 if (info != null) {
2209 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002210 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002211 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002212 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002213 }
2214
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002215 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002216 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002217 public Network getNetworkForType(int networkType) {
2218 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002219 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2220 return null;
2221 }
2222 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2223 if (nai == null) {
2224 return null;
2225 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002226 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002227 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2228 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002229 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002230 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002231 }
2232
2233 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002234 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002235 public Network[] getAllNetworks() {
2236 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002237 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002238 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002239 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002240 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002241 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002242 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002243 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002244 }
2245
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002246 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002247 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002248 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002249 // The basic principle is: if an app's traffic could possibly go over a
2250 // network, without the app doing anything multinetwork-specific,
2251 // (hence, by "default"), then include that network's capabilities in
2252 // the array.
2253 //
2254 // In the normal case, app traffic only goes over the system's default
2255 // network connection, so that's the only network returned.
2256 //
2257 // With a VPN in force, some app traffic may go into the VPN, and thus
2258 // over whatever underlying networks the VPN specifies, while other app
2259 // traffic may go over the system default network (e.g.: a split-tunnel
2260 // VPN, or an app disallowed by the VPN), so the set of networks
2261 // returned includes the VPN's underlying networks and the system
2262 // default.
2263 enforceAccessPermission();
2264
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002265 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002266
James Mattis2516da32021-01-31 17:06:19 -08002267 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2268 if (!nri.isBeingSatisfied()) {
2269 continue;
2270 }
2271 final NetworkAgentInfo nai = nri.getSatisfier();
2272 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2273 if (null != nc
2274 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2275 && !result.containsKey(nai.network)) {
2276 result.put(
2277 nai.network,
2278 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002279 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002280 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2281 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002282 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002283 }
2284
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002285 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002286 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002287 if (null != networks) {
2288 for (final Network network : networks) {
2289 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2290 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002291 result.put(
2292 network,
2293 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002294 nc,
2295 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002296 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002297 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002298 }
2299 }
2300 }
2301
2302 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2303 out = result.values().toArray(out);
2304 return out;
2305 }
2306
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002307 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002308 public boolean isNetworkSupported(int networkType) {
2309 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002310 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002311 }
2312
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002313 /**
2314 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002315 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002316 * @return the ip properties for the active network, or {@code null} if
2317 * none is active
2318 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002319 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002320 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002321 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002322 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002323 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2324 if (nai == null) return null;
2325 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002326 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002327 }
2328
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002329 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002330 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002331 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002332 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002333 final LinkProperties lp = getLinkProperties(nai);
2334 if (lp == null) return null;
2335 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002336 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002337 }
2338
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002339 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002340 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002341 public LinkProperties getLinkProperties(Network network) {
2342 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002343 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2344 if (lp == null) return null;
2345 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002346 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002347 }
2348
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002349 @Nullable
2350 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002351 if (nai == null) {
2352 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002353 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002354 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002355 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002356 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002357 }
2358
lucaslinc582d502022-01-27 09:07:00 +08002359 @Override
2360 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002361 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002362 @NonNull String packageName, @Nullable String callingAttributionTag) {
2363 Objects.requireNonNull(packageName);
2364 Objects.requireNonNull(lp);
2365 enforceNetworkStackOrSettingsPermission();
2366 if (!checkAccessPermission(-1 /* pid */, uid)) {
2367 return null;
2368 }
2369 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2370 }
2371
Qingxi Lib2748102020-01-08 12:51:49 -08002372 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2373 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2374 }
2375
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002376 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002377 if (nai == null) return null;
2378 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002379 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002380 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002381 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002382 }
2383
2384 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002385 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2386 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002387 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002388 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002389 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002390 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002391 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002392 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002393 }
2394
lucaslinc582d502022-01-27 09:07:00 +08002395 @Override
lucaslind2b06132022-03-02 10:56:57 +08002396 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2397 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2398 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002399 Objects.requireNonNull(nc);
2400 Objects.requireNonNull(packageName);
2401 enforceNetworkStackOrSettingsPermission();
2402 if (!checkAccessPermission(-1 /* pid */, uid)) {
2403 return null;
2404 }
2405 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2406 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2407 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2408 callingAttributionTag);
2409 }
2410
lucaslin69e1aa92022-03-22 18:15:09 +08002411 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2412 if (nc.getUnderlyingNetworks() != null
2413 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2414 nc.setUnderlyingNetworks(null);
2415 }
2416 }
2417
Qingxi Libb8da982020-01-17 17:54:27 -08002418 @VisibleForTesting
2419 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002420 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002421 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2422 // this would be expensive (one more permission check every time any NC callback is
2423 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2424 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2425 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002426 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002427 if (!checkSettingsPermission(callerPid, callerUid)) {
2428 newNc.setUids(null);
2429 newNc.setSSID(null);
2430 }
Etan Cohen107ae952018-12-30 17:59:59 -08002431 if (newNc.getNetworkSpecifier() != null) {
2432 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2433 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002434 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2435 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002436 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2437 newNc.setAdministratorUids(new int[0]);
2438 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002439 if (!checkAnyPermissionOf(mContext,
Benedict Wong53de25f2021-03-24 14:01:51 -07002440 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002441 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002442 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002443 }
lucaslin69e1aa92022-03-22 18:15:09 +08002444 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002445
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002446 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002447 }
2448
Roshan Pius98f59ec2021-02-23 08:47:39 -08002449 /**
2450 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002451 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002452 * NetworkCapabilities.
2453 * Note: This wrapper does not support any sort of invalidation and thus must not be
2454 * persistent or long-lived. It may only be used for the time necessary to
2455 * compute the redactions required by one particular NetworkCallback or
2456 * synchronous call.
2457 */
2458 private class RedactionPermissionChecker {
2459 private final int mCallingPid;
2460 private final int mCallingUid;
2461 @NonNull private final String mCallingPackageName;
2462 @Nullable private final String mCallingAttributionTag;
2463
2464 private Boolean mHasLocationPermission = null;
2465 private Boolean mHasLocalMacAddressPermission = null;
2466 private Boolean mHasSettingsPermission = null;
2467
2468 RedactionPermissionChecker(int callingPid, int callingUid,
2469 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2470 mCallingPid = callingPid;
2471 mCallingUid = callingUid;
2472 mCallingPackageName = callingPackageName;
2473 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002474 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002475
2476 private boolean hasLocationPermissionInternal() {
2477 final long token = Binder.clearCallingIdentity();
2478 try {
2479 return mLocationPermissionChecker.checkLocationPermission(
2480 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2481 null /* message */);
2482 } finally {
2483 Binder.restoreCallingIdentity(token);
2484 }
2485 }
2486
2487 /**
2488 * Returns whether the app holds location permission or not (might return cached result
2489 * if the permission was already checked before).
2490 */
2491 public boolean hasLocationPermission() {
2492 if (mHasLocationPermission == null) {
2493 // If there is no cached result, perform the check now.
2494 mHasLocationPermission = hasLocationPermissionInternal();
2495 }
2496 return mHasLocationPermission;
2497 }
2498
2499 /**
2500 * Returns whether the app holds local mac address permission or not (might return cached
2501 * result if the permission was already checked before).
2502 */
2503 public boolean hasLocalMacAddressPermission() {
2504 if (mHasLocalMacAddressPermission == null) {
2505 // If there is no cached result, perform the check now.
2506 mHasLocalMacAddressPermission =
2507 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2508 }
2509 return mHasLocalMacAddressPermission;
2510 }
2511
2512 /**
2513 * Returns whether the app holds settings permission or not (might return cached
2514 * result if the permission was already checked before).
2515 */
2516 public boolean hasSettingsPermission() {
2517 if (mHasSettingsPermission == null) {
2518 // If there is no cached result, perform the check now.
2519 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2520 }
2521 return mHasSettingsPermission;
2522 }
2523 }
2524
2525 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2526 @NetworkCapabilities.NetCapability long redaction) {
2527 return (redactions & redaction) != 0;
2528 }
2529
2530 /**
2531 * Use the provided |applicableRedactions| to check the receiving app's
2532 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2533 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2534 * before being sent to the corresponding app.
2535 */
2536 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2537 @NetworkCapabilities.RedactionType long applicableRedactions,
2538 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2539 boolean includeLocationSensitiveInfo) {
2540 long redactions = applicableRedactions;
2541 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2542 if (includeLocationSensitiveInfo
2543 && redactionPermissionChecker.hasLocationPermission()) {
2544 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2545 }
2546 }
2547 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2548 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2549 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2550 }
2551 }
2552 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2553 if (redactionPermissionChecker.hasSettingsPermission()) {
2554 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2555 }
2556 }
2557 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002558 }
2559
Qingxi Lib2748102020-01-08 12:51:49 -08002560 @VisibleForTesting
2561 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002562 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002563 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002564 int callingPid, int callingUid, @NonNull String callingPkgName,
2565 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002566 if (nc == null) {
2567 return null;
2568 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002569 // Avoid doing location permission check if the transport info has no location sensitive
2570 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002571 final RedactionPermissionChecker redactionPermissionChecker =
2572 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2573 callingAttributionTag);
2574 final long redactions = retrieveRequiredRedactions(
2575 nc.getApplicableRedactions(), redactionPermissionChecker,
2576 includeLocationSensitiveInfo);
2577 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002578 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002579 // TODO : calling UID is redacted because apps should generally not know what UID is
2580 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002581 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002582 newNc.setOwnerUid(INVALID_UID);
2583 return newNc;
2584 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002585 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2586 if (nc.hasTransport(TRANSPORT_VPN)) {
2587 // Owner UIDs already checked above. No need to re-check.
2588 return newNc;
2589 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002590 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2591 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002592 // compatibility for older apps.
2593 if (!includeLocationSensitiveInfo
2594 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002595 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002596 newNc.setOwnerUid(INVALID_UID);
2597 return newNc;
2598 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002599 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002600 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002601 newNc.setOwnerUid(INVALID_UID);
2602 }
Qingxi Lib2748102020-01-08 12:51:49 -08002603 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002604 }
2605
lucaslinc582d502022-01-27 09:07:00 +08002606 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002607 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2608 LinkProperties lp, int callerPid, int callerUid) {
2609 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002610 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2611 // this would be expensive (one more permission check every time any LP callback is
2612 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2613 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2614 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002615
2616 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2617 final boolean needsSanitization =
2618 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2619 if (!needsSanitization) {
2620 return new LinkProperties(lp);
2621 }
2622
2623 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002624 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002625 }
2626
2627 final LinkProperties newLp = new LinkProperties(lp);
2628 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2629 // object gets parceled.
2630 newLp.setCaptivePortalApiUrl(null);
2631 newLp.setCaptivePortalData(null);
2632 return newLp;
2633 }
2634
Roshan Pius08c94fb2020-01-16 12:17:17 -08002635 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2636 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002637 // There is no need to track the effective UID of the request here. If the caller
2638 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002639 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002640 // Unprivileged apps can only pass in null or their own UID.
2641 if (nc.getUids() == null) {
2642 // If the caller passes in null, the callback will also match networks that do not
2643 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2644 // In this case, redact everything in the request immediately. This ensures that the
2645 // app is not able to get any redacted information by filing an unredacted request
2646 // and observing whether the request matches something.
2647 if (nc.getNetworkSpecifier() != null) {
2648 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2649 }
2650 } else {
2651 nc.setSingleUid(callerUid);
2652 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002653 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002654 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002655 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002656
2657 // Clear owner UID; this can never come from an app.
2658 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002659 }
2660
Chalard Jean38354d12018-03-20 19:13:57 +09002661 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002662 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002663 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2664 }
2665 }
2666
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002667 @Override
2668 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2669 enforceAccessPermission();
2670 final int callerUid = Binder.getCallingUid();
2671 final long token = Binder.clearCallingIdentity();
2672 try {
2673 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2674 } finally {
2675 Binder.restoreCallingIdentity(token);
2676 }
2677 }
2678
junyulaiebd15162021-03-03 12:09:05 +08002679 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002680 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002681 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002682 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002683 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002684
Serik Beketayev05130302021-01-15 16:47:25 -08002685 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002686 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002687 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2688 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002689 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002690 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002691 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002692 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2693 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002694 }
2695 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002696 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002697 }
2698
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002699 @Override
junyulaiebd15162021-03-03 12:09:05 +08002700 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002701 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002702 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002703 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002704
2705 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2706 for (Network network : getAllNetworks()) {
2707 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09002708 final boolean includeNetwork = (nai != null) && nai.isCreated();
2709 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08002710 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2711 // NetworkCapabilities, which may contain UIDs of apps to which the
2712 // network applies. Should the UIDs be cleared so as not to leak or
2713 // interfere ?
2714 result.add(nai.getNetworkStateSnapshot());
2715 }
2716 }
2717 return result;
2718 }
2719
2720 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002721 public boolean isActiveNetworkMetered() {
2722 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002723
Qingxi Lib2748102020-01-08 12:51:49 -08002724 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002725 if (caps != null) {
2726 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2727 } else {
2728 // Always return the most conservative value
2729 return true;
2730 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002731 }
2732
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002733 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002734 * Ensures that the system cannot call a particular method.
2735 */
2736 private boolean disallowedBecauseSystemCaller() {
2737 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002738 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2739 // for devices launched with Q and above. However, existing devices upgrading to Q and
2740 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002741 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002742 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002743 log("This method exists only for app backwards compatibility"
2744 + " and must not be called by system services.");
2745 return true;
2746 }
2747 return false;
2748 }
2749
paulhub2c28682021-08-18 18:35:54 +08002750 private int getAppUid(final String app, final UserHandle user) {
2751 final PackageManager pm =
2752 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2753 final long token = Binder.clearCallingIdentity();
2754 try {
2755 return pm.getPackageUid(app, 0 /* flags */);
2756 } catch (PackageManager.NameNotFoundException e) {
2757 return -1;
2758 } finally {
2759 Binder.restoreCallingIdentity(token);
2760 }
2761 }
2762
2763 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2764 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2765 if (getAppUid(packageName, user) != callingUid) {
2766 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2767 }
2768 }
2769
Lorenzo Colitti23862912018-09-28 11:31:55 +09002770 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002771 * Ensure that a network route exists to deliver traffic to the specified
2772 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002773 * @param networkType the type of the network over which traffic to the
2774 * specified host is to be routed
2775 * @param hostAddress the IP address of the host to which the route is
2776 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002777 * @return {@code true} on success, {@code false} on failure
2778 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002779 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002780 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2781 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002782 if (disallowedBecauseSystemCaller()) {
2783 return false;
2784 }
paulhub2c28682021-08-18 18:35:54 +08002785 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002786 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002787 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08002788 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002789 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002790
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002791 InetAddress addr;
2792 try {
2793 addr = InetAddress.getByAddress(hostAddress);
2794 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002795 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002796 return false;
2797 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002798
The Android Open Source Project28527d22009-03-03 19:31:44 -08002799 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002800 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002801 return false;
2802 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002803
2804 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2805 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002806 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002807 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2808 } else {
2809 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2810 }
2811 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002812 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002813
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002814 DetailedState netState;
2815 synchronized (nai) {
2816 netState = nai.networkInfo.getDetailedState();
2817 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002818
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002819 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002820 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002821 log("requestRouteToHostAddress on down network "
2822 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002823 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002824 }
2825 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002826 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002827
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002828 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002829 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002830 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002831 LinkProperties lp;
2832 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002833 synchronized (nai) {
2834 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002835 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002836 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002837 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002838 if (DBG) {
2839 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2840 }
Wink Saville32506bc2013-06-29 21:10:57 -07002841 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002842 } finally {
2843 Binder.restoreCallingIdentity(token);
2844 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002845 }
2846
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002847 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002848 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002849 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002850 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002851 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002852 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002853 if (bestRoute.getGateway().equals(addr)) {
2854 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002855 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002856 } else {
2857 // if we will connect to this through another route, add a direct route
2858 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002859 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002860 }
2861 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002862 if (DBG) log("Adding legacy route " + bestRoute +
2863 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002864
2865 final String dst = bestRoute.getDestinationLinkAddress().toString();
2866 final String nextHop = bestRoute.hasGateway()
2867 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002868 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002869 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2870 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002871 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002872 return false;
2873 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002874 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002875 }
2876
paulhu7c0a2e62021-01-08 00:51:49 +08002877 class DnsResolverUnsolicitedEventCallback extends
2878 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002879 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002880 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002881 try {
2882 mHandler.sendMessage(mHandler.obtainMessage(
2883 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002884 new PrivateDnsValidationUpdate(event.netId,
2885 InetAddresses.parseNumericAddress(event.ipAddress),
2886 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002887 } catch (IllegalArgumentException e) {
2888 loge("Error parsing ip address in validation event");
2889 }
2890 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002891
2892 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002893 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2894 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002895 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2896 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2897 // event callback for certain nai. e.g. cellular. Register here to pass to
2898 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002899 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002900 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2901 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002902 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002903 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002904 }
2905 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002906
2907 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002908 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2909 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2910 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002911 }
dalyk1720e542018-03-05 12:42:22 -05002912
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002913 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002914 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002915 return this.VERSION;
2916 }
2917
2918 @Override
2919 public String getInterfaceHash() {
2920 return this.HASH;
2921 }
paulhu7c0a2e62021-01-08 00:51:49 +08002922 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002923
2924 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002925 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2926 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002927
paulhu7c0a2e62021-01-08 00:51:49 +08002928 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002929 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002930 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002931 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002932 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002933 }
2934 }
2935
Sudheer Shanka9967d462021-03-18 19:09:25 +00002936 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002937 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002938 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002939 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2940 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002941 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002942 };
2943
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002944 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002945 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002946 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002947 }
2948
Mark Fasheh7c999d82023-05-04 20:23:11 +00002949 static final class UidFrozenStateChangedArgs {
2950 final int[] mUids;
2951 final int[] mFrozenStates;
2952
2953 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
2954 mUids = uids;
2955 mFrozenStates = frozenStates;
2956 }
2957 }
2958
2959 private void handleFrozenUids(int[] uids, int[] frozenStates) {
2960 final ArraySet<Range<Integer>> ranges = new ArraySet<>();
2961
2962 for (int i = 0; i < uids.length; i++) {
2963 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
2964 Integer uidAsInteger = Integer.valueOf(uids[i]);
2965 ranges.add(new Range(uidAsInteger, uidAsInteger));
2966 }
2967 }
2968
2969 if (!ranges.isEmpty()) {
2970 final Set<Integer> exemptUids = new ArraySet<>();
2971 try {
2972 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
2973 } catch (Exception e) {
2974 loge("Exception in socket destroy: " + e);
2975 }
2976 }
2977 }
2978
2979 @VisibleForTesting
2980 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
2981
Paul Jensen83f5d572014-08-29 09:54:01 -04002982 private void enforceInternetPermission() {
2983 mContext.enforceCallingOrSelfPermission(
2984 android.Manifest.permission.INTERNET,
2985 "ConnectivityService");
2986 }
2987
The Android Open Source Project28527d22009-03-03 19:31:44 -08002988 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002989 mContext.enforceCallingOrSelfPermission(
2990 android.Manifest.permission.ACCESS_NETWORK_STATE,
2991 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002992 }
2993
lucaslinc582d502022-01-27 09:07:00 +08002994 private boolean checkAccessPermission(int pid, int uid) {
2995 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
2996 == PERMISSION_GRANTED;
2997 }
2998
paulhua6ee2122021-02-22 15:40:43 +08002999 /**
3000 * Performs a strict and comprehensive check of whether a calling package is allowed to
3001 * change the state of network, as the condition differs for pre-M, M+, and
3002 * privileged/preinstalled apps. The caller is expected to have either the
3003 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3004 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3005 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3006 * permission and cannot be revoked. See http://b/23597341
3007 *
3008 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3009 * of this app will be updated to the current time.
3010 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003011 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003012 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3013 == PackageManager.PERMISSION_GRANTED) {
3014 return;
3015 }
3016
3017 if (callingPkg == null) {
3018 throw new SecurityException("Calling package name is null.");
3019 }
3020
3021 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3022 final int uid = mDeps.getCallingUid();
3023 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3024 callingPkg, callingAttributionTag, null /* message */);
3025
3026 if (mode == AppOpsManager.MODE_ALLOWED) {
3027 return;
3028 }
3029
3030 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3031 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3032 return;
3033 }
3034
3035 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3036 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3037 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003038 }
3039
Charles He9369e612017-05-15 17:07:18 +01003040 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003041 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003042 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003043 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003044 }
3045
Quang Luong98858d62023-02-11 00:25:24 +00003046 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003047 enforceAnyPermissionOf(mContext,
3048 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003049 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003050 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3051 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3052 }
3053
paulhu8e96a752019-08-12 16:25:11 +08003054 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003055 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003056 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003057 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003058 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003059 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003060 }
3061
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003062 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003063 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003064 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003065 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003066 android.Manifest.permission.NETWORK_SETTINGS,
3067 android.Manifest.permission.NETWORK_FACTORY,
3068 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3069 }
3070
3071 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003072 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003073 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003074 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003075 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3076 android.Manifest.permission.NETWORK_FACTORY,
3077 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3078 }
3079
lucaslin69e1aa92022-03-22 18:15:09 +08003080 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3081 return PERMISSION_GRANTED == mContext.checkPermission(
3082 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3083 || PERMISSION_GRANTED == mContext.checkPermission(
3084 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3085 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003086 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003087 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003088 }
3089
Chalard Jean9a396cc2018-02-21 18:43:54 +09003090 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003091 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003092 android.Manifest.permission.NETWORK_SETTINGS,
3093 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003094 }
3095
3096 private boolean checkSettingsPermission(int pid, int uid) {
3097 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003098 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3099 || PERMISSION_GRANTED == mContext.checkPermission(
3100 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003101 }
3102
paulhu8e96a752019-08-12 16:25:11 +08003103 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003104 enforceNetworkStackPermissionOr(mContext,
3105 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003106 }
3107
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003108 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003109 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003110 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003111 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003112 }
3113
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003114 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003115 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003116 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3117 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003118 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003119 }
3120
James Mattis8378aec2021-01-26 14:05:36 -08003121 private void enforceOemNetworkPreferencesPermission() {
3122 mContext.enforceCallingOrSelfPermission(
3123 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3124 "ConnectivityService");
3125 }
3126
James Mattisfa270db2021-05-31 17:11:10 -07003127 private void enforceManageTestNetworksPermission() {
3128 mContext.enforceCallingOrSelfPermission(
3129 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3130 "ConnectivityService");
3131 }
3132
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003133 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003134 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003135 android.Manifest.permission.NETWORK_STACK,
3136 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003137 }
3138
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003139 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003140 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003141 android.Manifest.permission.NETWORK_STACK,
3142 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3143 }
3144
paulhu1a407652019-03-22 16:35:06 +08003145 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003146 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003147 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003148 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3149 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003150 }
3151
Paul Hu8fc2a552022-05-04 18:44:42 +08003152 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3153 boolean checkUidsAllowedList) {
3154 if (PermissionUtils.checkAnyPermissionOf(mContext,
3155 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3156 return true;
3157 }
3158
3159 // fallback to ConnectivityInternalPermission
3160 // TODO: Remove this fallback check after all apps have declared
3161 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3162 if (PermissionUtils.checkAnyPermissionOf(mContext,
3163 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3164 return true;
3165 }
3166
3167 // Check whether uid is in allowed on restricted networks list.
3168 if (checkUidsAllowedList
3169 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3170 return true;
3171 }
3172 return false;
3173 }
3174
3175 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3176 final int callingUid = mDeps.getCallingUid();
3177 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3178 throw new SecurityException("ConnectivityService: user " + callingUid
3179 + " has no permission to access restricted network.");
3180 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003181 }
3182
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003183 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003184 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003185 }
3186
Roshan Pius98f59ec2021-02-23 08:47:39 -08003187 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3188 return PERMISSION_GRANTED == mContext.checkPermission(
3189 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3190 }
3191
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003192 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003193 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003194 }
3195
3196 private void sendInetConditionBroadcast(NetworkInfo info) {
3197 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3198 }
3199
Wink Saville4f0de1e2011-08-04 15:01:58 -07003200 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003201 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003202 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003203 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003204 if (info.isFailover()) {
3205 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3206 info.setFailover(false);
3207 }
3208 if (info.getReason() != null) {
3209 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3210 }
3211 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003212 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3213 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003214 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003215 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003216 return intent;
3217 }
3218
3219 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3220 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3221 }
3222
Chiachang Wang3bc52762021-11-25 14:17:57 +08003223 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3224 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003225 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003226 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003227 if (!mSystemReady
3228 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003229 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003230 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003231 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003232 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003233 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003234 }
3235
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003236 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003237 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003238 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003239 final NetworkInfo ni = intent.getParcelableExtra(
3240 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003241 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3242 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003243 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003244 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003245 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003246 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003247 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003248 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003249 } finally {
3250 Binder.restoreCallingIdentity(ident);
3251 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003252 }
3253 }
3254
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003255 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3256 NetworkInfo info) {
3257 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003258 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003259
3260 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3261 try {
3262 // This allows us to discard older broadcasts still waiting to be delivered
3263 // which have the same namespace and key.
3264 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3265 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3266 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003267 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003268 } catch (UnsupportedApiLevelException e) {
3269 Log.wtf(TAG, "Using unsupported API" + e);
3270 }
3271 }
3272
3273 @VisibleForTesting
3274 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3275 final StringBuilder sb = new StringBuilder();
3276 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3277 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3278 sb.append(info.getExtraInfo());
3279 return sb.toString();
3280 }
3281
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003282 /**
Aaron Huang96011892020-06-27 07:18:23 +08003283 * Called by SystemServer through ConnectivityManager when the system is ready.
3284 */
3285 @Override
3286 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003287 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003288 throw new SecurityException("Calling Uid is not system uid.");
3289 }
3290 systemReadyInternal();
3291 }
3292
3293 /**
3294 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003295 */
3296 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003297 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003298 // Load flags after PackageManager is ready to query module version
3299 mFlags.loadFlags(mDeps, mContext);
3300
Aaron Huang9a57acf2020-12-08 10:03:29 +08003301 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3302 // listening network request which is sent by MultipathPolicyTracker won't be added
3303 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3304 // be called after PermissionMonitor#startMonitoring().
3305 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3306 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3307 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003308 final ConditionVariable startMonitoringDone = new ConditionVariable();
3309 mHandler.post(() -> {
3310 mPermissionMonitor.startMonitoring();
3311 startMonitoringDone.open();
3312 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003313 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003314 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003315
Hugo Benichie5220992017-04-26 14:53:28 +09003316 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003317 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003318 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003319 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003320 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003321 }
3322 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003323
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003324 // Create network requests for always-on networks.
3325 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003326
3327 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003328 // Note that updating can be skipped here if the list is empty only because no uid
3329 // rules are applied before system ready. Normally, the empty uid list means to clear
3330 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003331 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3332 updateMobileDataPreferredUids();
3333 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003334
3335 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003336 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003337 mBpfNetMaps.setPullAtomCallback(mContext);
3338 }
Paul Hu3c8c8102022-08-25 07:06:16 +00003339 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3340 // have permission problem. While CV#block() is unbounded in time and can in principle block
3341 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3342 // could have blocked forever too.
3343 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003344 }
3345
The Android Open Source Project28527d22009-03-03 19:31:44 -08003346 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003347 * Start listening for default data network activity state changes.
3348 */
3349 @Override
3350 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003351 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003352 }
3353
3354 /**
3355 * Stop listening for default data network activity state changes.
3356 */
3357 @Override
3358 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003359 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003360 }
3361
3362 /**
3363 * Check whether the default network radio is currently active.
3364 */
3365 @Override
3366 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003367 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003368 }
3369
3370 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003371 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003372 * and set it on it's iface.
3373 */
Junyu Lai970963e2022-10-25 15:46:47 +08003374 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003375 final String iface = newLp.getInterfaceName();
3376 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003377 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003378 // Silently ignore unset MTU value.
3379 return;
3380 }
Hansen Kurli04252032022-12-07 11:21:49 +00003381 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3382 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3383 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003384 return;
3385 }
Hansen Kurli04252032022-12-07 11:21:49 +00003386 // Cannot set MTU without interface name
3387 if (TextUtils.isEmpty(iface)) {
3388 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003389 return;
3390 }
sy.yun4aa73922013-09-02 05:24:09 +09003391
Hansen Kurli04252032022-12-07 11:21:49 +00003392 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3393 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003394 return;
3395 }
3396
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003397 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003398 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003399 mNetd.interfaceSetMtu(iface, mtu);
3400 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003401 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003402 }
3403 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003404
Chenbo Feng15416292018-11-08 17:36:21 -08003405 @VisibleForTesting
3406 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003407
Junyu Lai970963e2022-10-25 15:46:47 +08003408 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003409 String[] values = null;
3410 if (tcpBufferSizes != null) {
3411 values = tcpBufferSizes.split(",");
3412 }
3413
3414 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003415 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003416 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3417 values = tcpBufferSizes.split(",");
3418 }
3419
3420 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3421
3422 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003423 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003424
Chenbo Feng15416292018-11-08 17:36:21 -08003425 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3426 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3427 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003428 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003429 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003430 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003431 }
3432 }
3433
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003434 @Override
3435 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003436 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003437 NETWORK_RESTORE_DELAY_PROP_NAME);
3438 if(restoreDefaultNetworkDelayStr != null &&
3439 restoreDefaultNetworkDelayStr.length() != 0) {
3440 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003441 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003442 } catch (NumberFormatException e) {
3443 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003444 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003445 // if the system property isn't set, use the value for the apn type
3446 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3447
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003448 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3449 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003450 }
3451 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003452 }
3453
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003454 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003455 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003456 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003457 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003458 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003459 // Start gathering diagnostic information.
3460 netDiags.add(new NetworkDiagnostics(
3461 nai.network,
3462 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003463 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003464 DIAG_TIME_MS));
3465 }
3466
3467 for (NetworkDiagnostics netDiag : netDiags) {
3468 pw.println();
3469 netDiag.waitForMeasurements();
3470 netDiag.dump(pw);
3471 }
3472 }
3473
The Android Open Source Project28527d22009-03-03 19:31:44 -08003474 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003475 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3476 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003477 if (!checkDumpPermission(mContext, TAG, writer)) return;
3478
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003479 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003480 }
3481
lucaslin99473f62020-12-10 15:10:54 +08003482 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3483 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3484 != PackageManager.PERMISSION_GRANTED) {
3485 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003486 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003487 + " due to missing android.permission.DUMP permission");
3488 return false;
3489 } else {
3490 return true;
3491 }
3492 }
3493
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003494 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003495 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003496
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003497 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003498 dumpNetworkDiagnostics(pw);
3499 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003500 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003501 dumpNetworks(pw);
3502 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003503 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003504 dumpNetworkRequests(pw);
3505 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003506 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3507 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3508 dumpTrafficController(pw, fd, verbose);
3509 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003510 }
Erik Kline9647f382015-06-05 17:47:34 +09003511
Junyu Lai0da479b2022-04-20 15:06:29 +08003512 pw.println("NetworkProviders for:");
3513 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003514 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003515 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003516 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003517 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003518 pw.println();
3519
Chalard Jean5b409c72021-02-04 13:12:59 +09003520 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003521 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003522 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003523 pw.println("none");
3524 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003525 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003526 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003527 pw.println();
3528
James Mattis8b298a02021-06-01 22:34:04 -07003529 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003530 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003531 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003532 pw.decreaseIndent();
3533 pw.println();
3534
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003535 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003536 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003537 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003538 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003539 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003540
junyulaif2c67e42018-08-07 19:50:45 +08003541 pw.println("Status for known UIDs:");
3542 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003543 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003544 for (int i = 0; i < size; i++) {
3545 // Don't crash if the array is modified while dumping in bugreports.
3546 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003547 final int uid = mUidBlockedReasons.keyAt(i);
3548 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3549 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003550 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003551 } catch (ArrayIndexOutOfBoundsException e) {
3552 pw.println(" ArrayIndexOutOfBoundsException");
3553 } catch (ConcurrentModificationException e) {
3554 pw.println(" ConcurrentModificationException");
3555 }
3556 }
3557 pw.println();
3558 pw.decreaseIndent();
3559
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003560 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003561 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003562 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003563 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003564 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003565
Junyu Lai0da479b2022-04-20 15:06:29 +08003566 pw.println("Network Offers:");
3567 pw.increaseIndent();
3568 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3569 pw.println(offerInfo.offer);
3570 }
3571 pw.decreaseIndent();
3572 pw.println();
3573
Robert Greenwalt94e22142014-07-30 16:31:24 -07003574 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003575
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003576 pw.println();
markchien5e866652019-09-30 14:40:57 +08003577 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003578
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003579 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003580 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003581
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003582 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003583
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003584 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003585 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003586 pw.println("mNetworkRequestInfoLogs (most recent first):");
3587 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003588 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003589 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003590
3591 pw.println();
3592 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3593 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003594 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003595 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003596
3597 pw.println();
3598 pw.println("NetTransition WakeLock activity (most recent first):");
3599 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003600 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3601 pw.println("total releases: " + mTotalWakelockReleases);
3602 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3603 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3604 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3605 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3606 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3607 }
James Mattiscb1e0362021-04-06 17:07:42 -07003608 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003609
3610 pw.println();
3611 pw.println("bandwidth update requests (by uid):");
3612 pw.increaseIndent();
3613 synchronized (mBandwidthRequests) {
3614 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3615 pw.println("[" + mBandwidthRequests.keyAt(i)
3616 + "]: " + mBandwidthRequests.valueAt(i));
3617 }
3618 }
3619 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003620 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003621
James Mattiscb1e0362021-04-06 17:07:42 -07003622 pw.println();
3623 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3624 pw.increaseIndent();
3625 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003626 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003627 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003628
3629 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003630
3631 pw.println();
3632 pw.println("Permission Monitor:");
3633 pw.increaseIndent();
3634 mPermissionMonitor.dump(pw);
3635 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003636
3637 pw.println();
3638 pw.println("Legacy network activity:");
3639 pw.increaseIndent();
3640 mNetworkActivityTracker.dump(pw);
3641 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003642 }
3643
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003644 private void dumpNetworks(IndentingPrintWriter pw) {
3645 for (NetworkAgentInfo nai : networksSortedById()) {
3646 pw.println(nai.toString());
3647 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003648 pw.println("Nat464Xlat:");
3649 pw.increaseIndent();
3650 nai.dumpNat464Xlat(pw);
3651 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003652 pw.println(String.format(
3653 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3654 nai.numForegroundNetworkRequests(),
3655 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3656 nai.numBackgroundNetworkRequests(),
3657 nai.numNetworkRequests()));
3658 pw.increaseIndent();
3659 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3660 pw.println(nai.requestAt(i).toString());
3661 }
3662 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003663 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003664 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003665 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003666 pw.decreaseIndent();
3667 pw.decreaseIndent();
3668 }
3669 }
3670
James Mattis8b298a02021-06-01 22:34:04 -07003671 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3672 if (!mProfileNetworkPreferences.isEmpty()) {
3673 pw.println("Profile preferences:");
3674 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09003675 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07003676 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003677 }
James Mattis8b298a02021-06-01 22:34:04 -07003678 if (!mOemNetworkPreferences.isEmpty()) {
3679 pw.println("OEM preferences:");
3680 pw.increaseIndent();
3681 pw.println(mOemNetworkPreferences);
3682 pw.decreaseIndent();
3683 }
3684 if (!mMobileDataPreferredUids.isEmpty()) {
3685 pw.println("Mobile data preferred UIDs:");
3686 pw.increaseIndent();
3687 pw.println(mMobileDataPreferredUids);
3688 pw.decreaseIndent();
3689 }
James Mattis45d81842021-01-10 14:24:24 -08003690
James Mattis8b298a02021-06-01 22:34:04 -07003691 pw.println("Default requests:");
3692 pw.increaseIndent();
3693 dumpPerAppDefaultRequests(pw);
3694 pw.decreaseIndent();
3695 }
3696
3697 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003698 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3699 if (mDefaultRequest == defaultRequest) {
3700 continue;
3701 }
3702
James Mattis8b298a02021-06-01 22:34:04 -07003703 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3704 final String networkOutput;
3705 if (null == satisfier) {
3706 networkOutput = "null";
3707 } else if (mNoServiceNetwork.equals(satisfier)) {
3708 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003709 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003710 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003711 }
James Mattis8b298a02021-06-01 22:34:04 -07003712 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3713 ? "" : " asUid: " + defaultRequest.mAsUid;
3714 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3715 + defaultRequest.mPid + asUidString + "]";
3716 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3717 + " Preference order: " + defaultRequest.mPreferenceOrder
3718 + " Tracked UIDs: " + defaultRequest.getUids();
3719 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003720 }
3721 }
3722
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003723 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003724 NetworkRequestInfo[] infos = null;
3725 while (infos == null) {
3726 try {
3727 infos = requestsSortedById();
3728 } catch (ConcurrentModificationException e) {
3729 // mNetworkRequests should only be accessed from handler thread, except dump().
3730 // As dump() is never called in normal usage, it would be needlessly expensive
3731 // to lock the collection only for its benefit. Instead, retry getting the
3732 // requests if ConcurrentModificationException is thrown during dump().
3733 }
3734 }
3735 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003736 pw.println(nri.toString());
3737 }
3738 }
3739
Ken Chene6d511f2022-01-25 11:10:42 +08003740 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
3741 boolean verbose) {
3742 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09003743 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08003744 } catch (ServiceSpecificException e) {
3745 pw.println(e.getMessage());
3746 } catch (IOException e) {
3747 loge("Dump BPF maps failed, " + e);
3748 }
3749 }
3750
Chalard Jean524f0b12021-10-25 21:11:56 +09003751 private void dumpAllRequestInfoLogsToLogcat() {
3752 try (PrintWriter logPw = new PrintWriter(new Writer() {
3753 @Override
3754 public void write(final char[] cbuf, final int off, final int len) {
3755 // This method is called with 0-length and 1-length arrays for empty strings
3756 // or strings containing only the DEL character.
3757 if (len <= 1) return;
3758 Log.e(TAG, new String(cbuf, off, len));
3759 }
3760 @Override public void flush() {}
3761 @Override public void close() {}
3762 })) {
3763 mNetworkRequestInfoLogs.dump(logPw);
3764 }
3765 }
3766
Hugo Benichia480ba52018-09-03 08:19:02 +09003767 /**
3768 * Return an array of all current NetworkAgentInfos sorted by network id.
3769 */
3770 private NetworkAgentInfo[] networksSortedById() {
3771 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003772 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003773 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003774 return networks;
3775 }
3776
3777 /**
3778 * Return an array of all current NetworkRequest sorted by request id.
3779 */
James Mattis258ea3c2020-11-15 15:04:40 -08003780 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003781 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003782 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003783 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003784 // Sort the array based off the NRI containing the min requestId in its requests.
3785 Arrays.sort(requests,
3786 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3787 Comparator.comparingInt(req -> req.requestId)).requestId
3788 )
3789 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003790 return requests;
3791 }
3792
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003793 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003794 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003795 if (officialNai != null && officialNai.equals(nai)) return true;
3796 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003797 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003798 " - " + nai);
3799 }
3800 return false;
3801 }
3802
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003803 private boolean isDisconnectRequest(Message msg) {
3804 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
3805 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
3806 return info.getState() == NetworkInfo.State.DISCONNECTED;
3807 }
3808
Robert Greenwalt2034b912009-08-12 16:08:25 -07003809 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003810 private class NetworkStateTrackerHandler extends Handler {
3811 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003812 super(looper);
3813 }
3814
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003815 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003816 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3817 final NetworkAgentInfo nai = arg.first;
3818 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003819 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003820 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003821 }
3822 return;
3823 }
3824
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003825 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09003826 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003827 return;
3828 }
3829
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003830 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003831 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09003832 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
3833 final NetworkCapabilities sanitized =
3834 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09003835 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003836 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003837 break;
3838 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003839 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003840 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003841 processLinkPropertiesFromAgent(nai, newLp);
3842 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003843 break;
3844 }
3845 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003846 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003847 updateNetworkInfo(nai, info);
3848 break;
3849 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003850 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003851 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003852 break;
3853 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003854 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09003855 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003856 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003857 // Note that if the NAI had been connected, this would affect the
3858 // score, and therefore would require re-mixing the score and performing
3859 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003860 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003861 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3862 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003863 // Mark the network as temporarily accepting partial connectivity so that it
3864 // will be validated (and possibly become default) even if it only provides
3865 // partial internet access. Note that if user connects to partial connectivity
3866 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3867 // out of wifi coverage) and if the same wifi is available again, the device
3868 // will auto connect to this wifi even though the wifi has "no internet".
3869 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003870 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003871 break;
3872 }
junyulai011b1f12019-01-03 18:50:15 +08003873 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003874 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003875 break;
3876 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003877 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003878 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003879 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003880
3881 if (isLegacyLockdownNai(nai)
3882 && (underlying == null || underlying.size() != 1)) {
3883 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3884 + " must have exactly one underlying network: " + underlying);
3885 }
3886
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003887 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3888 nai.declaredUnderlyingNetworks = (underlying != null)
3889 ? underlying.toArray(new Network[0]) : null;
3890
3891 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3892 if (DBG) {
3893 log(nai.toShortString() + " changed underlying networks to "
3894 + Arrays.toString(nai.declaredUnderlyingNetworks));
3895 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003896 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003897 notifyIfacesChangedForNetworkStats();
3898 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003899 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003900 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003901 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3902 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3903 nai.teardownDelayMs = msg.arg1;
3904 } else {
3905 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3906 }
Chalard Jean550b5212021-03-05 23:07:53 +09003907 break;
3908 }
3909 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3910 nai.setLingerDuration((int) arg.second);
3911 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003912 }
Tyler Wear72388212021-09-09 14:49:02 -07003913 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3914 DscpPolicy policy = (DscpPolicy) arg.second;
3915 if (mDscpPolicyTracker != null) {
3916 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3917 }
3918 break;
3919 }
3920 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3921 if (mDscpPolicyTracker != null) {
3922 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3923 }
3924 break;
3925 }
3926 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3927 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08003928 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07003929 }
3930 break;
3931 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09003932 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09003933 if (!nai.everConnected()) {
3934 Log.d(TAG, "unregisterAfterReplacement on never-connected "
3935 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09003936 teardownUnneededNetwork(nai);
3937 break;
3938 }
3939
3940 if (nai.isDestroyed()) {
3941 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
3942 + ", ignoring");
3943 break;
3944 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003945
3946 final int timeoutMs = (int) arg.second;
3947 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3948 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
3949 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
3950 }
3951
3952 // Marking a network awaiting replacement is used to ensure that any requests
3953 // satisfied by the network do not switch to another network until a
3954 // replacement is available or the wait for a replacement times out.
3955 // If the network is inactive (i.e., nascent or lingering), then there are no
3956 // such requests, and there is no point keeping it. Just tear it down.
3957 // Note that setLingerDuration(0) cannot be used to do this because the network
3958 // could be nascent.
3959 nai.clearInactivityState();
3960 if (unneeded(nai, UnneededFor.TEARDOWN)) {
3961 Log.d(TAG, nai.toShortString()
3962 + " marked awaiting replacement is unneeded, tearing down instead");
3963 teardownUnneededNetwork(nai);
3964 break;
3965 }
3966
3967 Log.d(TAG, "Marking " + nai.toShortString()
3968 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
3969 destroyNativeNetwork(nai);
3970
3971 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
3972 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
3973 // consider the fact that the network could already have disconnected or been
3974 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
3975 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
3976 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
3977 mKeepaliveTracker.handleStopAllKeepalives(nai,
3978 SocketKeepalive.ERROR_INVALID_NETWORK);
3979
3980 nai.updateScoreForNetworkAgentUpdate();
3981 // This rematch is almost certainly not going to result in any changes, because
3982 // the destroyed flag is only just above the "current satisfier wins"
3983 // tie-breaker. But technically anything that affects scoring should rematch.
3984 rematchAllNetworksAndRequests();
3985 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
3986 break;
3987 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003988 }
3989 }
3990
3991 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003992 final int netId = msg.arg2;
3993 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003994 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09003995 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003996 switch (msg.what) {
3997 default:
3998 return false;
lucasline117e2e2019-10-22 18:27:33 +08003999 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004000 if (nai == null) {
4001 break;
4002 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004003 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4004 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004005 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004006 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004007 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004008 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004009 if (probePrivateDnsCompleted) {
4010 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4011 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004012 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004013 }
4014 // Only show the notification when the private DNS is broken and the
4015 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004016 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004017 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4018 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004019 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004020 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4021 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4022 // private DNS is broken, it means this network is being reevaluated.
4023 // Either probing private DNS is not necessary any more or it hasn't been
4024 // done yet. In either case, the networkCapabilities should be updated to
4025 // reflect the new status.
4026 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004027 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004028 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004029 }
4030 break;
4031 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004032 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004033 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4034
Erik Kline31b4a9e2018-01-11 21:07:29 +09004035 if (nai == null) break;
4036
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004037 handleNetworkTested(nai, results.mTestResult,
4038 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004039 break;
4040 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004041 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004042 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004043 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004044 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004045 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004046 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004047 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4048 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004049 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004050 if (nai == null) {
4051 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4052 break;
4053 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004054 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004055 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004056 (PendingIntent) msg.obj,
4057 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004058 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004059 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004060 break;
4061 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004062 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004063 if (nai == null) break;
4064
Erik Kline9a62f012018-03-21 07:18:33 -07004065 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004066 break;
4067 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004068 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004069 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004070 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004071 break;
4072 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004073 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004074 return true;
4075 }
4076
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004077 private void handleNetworkTested(
4078 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004079 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4080 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004081 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004082
4083 // If there is any kind of working networking, then the NAI has been evaluated
4084 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4085 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004086 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004087 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004088 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4089 // any callback that receives onAvailable for that rematch receives an extra caps
4090 // callback. To prevent that, update the score in the agent so the updates below won't
4091 // see an update to both caps and score at the same time.
4092 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004093 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4094
he_won.hwang881307a2022-03-15 21:23:52 +09004095 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4096 // Assume the validation failure is due to a temporary failure after roaming
4097 // and ignore it. NetworkMonitor will continue to retry validation. If it
4098 // continues to fail after the block timeout expires, the network will be
4099 // marked unvalidated. If it succeeds, then validation state will not change.
4100 return;
4101 }
4102
Chalard Jean254bd162022-08-25 13:04:51 +09004103 final boolean wasValidated = nai.isValidated();
4104 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004105 final boolean wasPortal = nai.captivePortalDetected();
4106 nai.setPartialConnectivity(partial);
4107 nai.setCaptivePortalDetected(portal);
4108 nai.updateScoreForNetworkAgentUpdate();
4109 final boolean partialConnectivityChanged = (wasPartial != partial);
4110 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004111
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004112 if (DBG) {
4113 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4114 ? " with redirect to " + redirectUrl
4115 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004116 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004117 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004118 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004119 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004120 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004121 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004122 if (valid) {
4123 handleFreshlyValidatedNetwork(nai);
4124 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4125 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004126 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004127 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004128 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004129 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004130 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004131 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004132 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004133 NotificationType.PRIVATE_DNS_BROKEN);
4134 // If network becomes valid, the hasShownBroken should be reset for
4135 // that network so that the notification will be fired when the private
4136 // DNS is broken again.
4137 nai.networkAgentConfig.hasShownBroken = false;
4138 }
4139 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004140 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004141 } else if (portalChanged) {
4142 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
4143 == getCaptivePortalMode()) {
4144 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4145 nai.onPreventAutomaticReconnect();
4146 teardownUnneededNetwork(nai);
4147 return;
4148 } else {
4149 updateCapabilitiesForNetwork(nai);
4150 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004151 } else if (becameEvaluated) {
4152 // If valid or partial connectivity changed, updateCapabilities* has
4153 // done the rematch.
4154 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004155 }
4156 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004157
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004158 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004159 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004160 nai.onValidationStatusChanged(
4161 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4162 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004163
4164 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004165 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004166 // immediately. Re-notify partial connectivity silently if no internet
4167 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004168 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004169 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004170 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4171 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004172 }
4173
Chalard Jean254bd162022-08-25 13:04:51 +09004174 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004175 handleNetworkUnvalidated(nai);
4176 }
4177 }
4178
Calvin Ondada1452016-10-11 15:10:46 -07004179 private int getCaptivePortalMode() {
4180 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004181 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4182 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004183 }
4184
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004185 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4186 switch (msg.what) {
4187 default:
4188 return false;
4189 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4190 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4191 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4192 handleLingerComplete(nai);
4193 }
4194 break;
4195 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004196 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4197 handleNetworkAgentRegistered(msg);
4198 break;
4199 }
4200 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4201 handleNetworkAgentDisconnected(msg);
4202 break;
4203 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004204 }
4205 return true;
4206 }
4207
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004208 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004209 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004210 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004211 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004212 maybeHandleNetworkAgentMessage(msg);
4213 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004214 }
4215 }
4216
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004217 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004218 private final int mNetId;
4219 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004220
4221 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004222 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004223 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004224 }
4225
4226 @Override
4227 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4228 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004229 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004230 }
4231
4232 @Override
4233 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004234 // Legacy version of notifyNetworkTestedWithExtras.
4235 // Would only be called if the system has a NetworkStack module older than the
4236 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004237 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004238 }
4239
4240 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004241 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004242 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4243 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004244 final Message msg = mTrackerHandler.obtainMessage(
4245 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004246 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004247 new NetworkTestedResults(
4248 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004249 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004250
4251 // Invoke ConnectivityReport generation for this Network test event.
4252 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4253 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004254
Cody Kestingf1120be2020-08-03 18:01:40 -07004255 // NetworkMonitor reports the network validation result as a bitmask while
4256 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4257 // logical value for ConnectivityDiagnostics.
4258 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4259 p.result);
4260
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004261 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004262 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004263 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4264 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4265
Aaron Huang959d3642021-01-21 15:47:41 +08004266 ConnectivityReportEvent reportEvent =
4267 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4268 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004269 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004270 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004271 }
4272
4273 @Override
4274 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4275 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4276 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004277 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004278 }
4279
4280 @Override
lucasline117e2e2019-10-22 18:27:33 +08004281 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4282 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4283 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004284 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004285 }
4286
4287 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004288 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4289 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4290 EVENT_CAPPORT_DATA_CHANGED,
4291 0, mNetId, data));
4292 }
4293
4294 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004295 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004296 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004297 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004298
4299 final PendingIntent pendingIntent;
4300 // Only the system server can register notifications with package "android"
4301 final long token = Binder.clearCallingIdentity();
4302 try {
paulhu7746e4e2020-06-09 19:07:03 +08004303 pendingIntent = PendingIntent.getBroadcast(
4304 mContext,
4305 0 /* requestCode */,
4306 intent,
4307 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004308 } finally {
4309 Binder.restoreCallingIdentity(token);
4310 }
4311 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4312 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004313 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004314 }
4315
4316 @Override
4317 public void hideProvisioningNotification() {
4318 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004319 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004320 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004321
4322 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004323 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004324 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004325 }
4326
4327 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004328 public int getInterfaceVersion() {
4329 return this.VERSION;
4330 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004331
4332 @Override
4333 public String getInterfaceHash() {
4334 return this.HASH;
4335 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004336 }
4337
Cody Kestingf1120be2020-08-03 18:01:40 -07004338 /**
4339 * Converts the given NetworkMonitor-specific validation result bitmask to a
4340 * ConnectivityDiagnostics-specific validation result int.
4341 */
4342 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4343 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4344 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4345 }
4346 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4347 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4348 }
4349 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4350 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4351 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4352 }
4353
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004354 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004355 log("Data stall detected with methods: " + p.detectionMethod);
4356
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004357 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004358 int detectionMethod = 0;
4359 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4360 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4361 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4362 }
4363 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4364 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4365 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4366 p.tcpMetricsCollectionPeriodMillis);
4367 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004368 }
4369
Cody Kestingf53a0752020-04-15 12:33:28 -07004370 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004371 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004372 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004373
4374 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4375 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4376 // the cost of going through two handlers.
4377 mConnectivityDiagnosticsHandler.sendMessage(msg);
4378 }
4379
Cody Kestingb37958e2020-05-15 10:36:01 -07004380 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4381 return (p.detectionMethod & detectionMethod) != 0;
4382 }
4383
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004384 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4385 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004386 }
4387
Erik Klinea73af002018-06-26 18:53:43 +09004388 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4389 if (nai == null) return;
4390 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4391 // in order to restart a validation pass from within netd.
4392 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4393 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004394 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004395 }
4396 }
4397
Erik Kline31b4a9e2018-01-11 21:07:29 +09004398 private void handlePrivateDnsSettingsChanged() {
4399 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4400
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004401 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004402 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004403 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004404 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4405 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004406 }
4407 }
4408
Erik Kline9a62f012018-03-21 07:18:33 -07004409 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4410 // Private DNS only ever applies to networks that might provide
4411 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004412 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004413
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004414 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004415 // schedule DNS resolutions. If a DNS resolution is required the
4416 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004417 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004418
4419 // With Private DNS bypass support, we can proceed to update the
4420 // Private DNS config immediately, even if we're in strict mode
4421 // and have not yet resolved the provider name into a set of IPs.
4422 updatePrivateDns(nai, cfg);
4423 }
4424
4425 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4426 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004427 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004428 }
4429
dalyk1720e542018-03-05 12:42:22 -05004430 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4431 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4432 if (nai == null) {
4433 return;
4434 }
4435 mDnsManager.updatePrivateDnsValidation(update);
4436 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4437 }
4438
paulhu7c0a2e62021-01-08 00:51:49 +08004439 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004440 int prefixLength) {
4441 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4442 if (nai == null) return;
4443
paulhu7c0a2e62021-01-08 00:51:49 +08004444 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4445 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004446
4447 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004448 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004449 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004450 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004451 prefixLength);
4452 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004453 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004454 return;
4455 }
4456 }
4457
Lorenzo Colittid523d142020-04-01 20:16:30 +09004458 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004459 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4460 }
4461
Hai Shalome58bdc62021-01-11 18:45:34 -08004462 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004463 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004464 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004465 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4466 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4467 }
4468
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004469 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004470 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004471 * @param nai the agent info to update
4472 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004473 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004474 */
junyulai2b6f0c22021-02-03 20:15:30 +08004475 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4476 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4477 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004478 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004479 // one lingered request, set inactive.
4480 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004481 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004482 if (DBG) log("Unsetting inactive " + nai.toShortString());
4483 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004484 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004485 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004486 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004487 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4488 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004489 }
junyulai2b6f0c22021-02-03 20:15:30 +08004490 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004491 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004492 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004493 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004494 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004495 }
4496
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004497 private void handleNetworkAgentRegistered(Message msg) {
4498 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4499 if (!mNetworkAgentInfos.contains(nai)) {
4500 return;
4501 }
4502
4503 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4504 if (VDBG) log("NetworkAgent registered");
4505 } else {
4506 loge("Error connecting NetworkAgent");
4507 mNetworkAgentInfos.remove(nai);
4508 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004509 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004510 synchronized (mNetworkForNetId) {
4511 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004512 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004513 mNetIdManager.releaseNetId(nai.network.getNetId());
4514 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004515 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004516 }
4517 }
4518 }
Paul Jensend5f53392014-11-25 15:26:53 -05004519
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004520 @VisibleForTesting
4521 protected static boolean shouldCreateNetworksImmediately() {
4522 // Before U, physical networks are only created when the agent advances to CONNECTED.
4523 // In U and above, all networks are immediately created when the agent is registered.
4524 return SdkLevel.isAtLeastU();
4525 }
4526
4527 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4528 @NonNull NetworkInfo.State state) {
4529 if (nai.isCreated()) return false;
4530 if (state == NetworkInfo.State.CONNECTED) return true;
4531 if (state != NetworkInfo.State.CONNECTING) {
4532 // TODO: throw if no WTFs are observed in the field.
4533 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4534 return false;
4535 }
4536 return nai.isVPN() || shouldCreateNetworksImmediately();
4537 }
4538
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004539 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004540 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004541 }
4542
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004543 @VisibleForTesting
4544 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004545 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09004546 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004547
4548 // If the network never roamed, return false. The check below is not sufficient if time
4549 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4550 if (nai.lastRoamTime == 0) return false;
4551
he_won.hwang881307a2022-03-15 21:23:52 +09004552 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4553 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004554 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004555 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004556 final long currentTimeMs = SystemClock.elapsedRealtime();
4557 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004558 if (timeSinceLastRoam <= blockTimeOut) {
4559 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4560 return true;
4561 }
4562 }
4563 return false;
4564 }
4565
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004566 private void handleNetworkAgentDisconnected(Message msg) {
4567 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004568 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004569 }
4570
Chalard Jeand9fffc32018-05-11 20:19:20 +09004571 // Destroys a network, remove references to it from the internal state managed by
4572 // ConnectivityService, free its interfaces and clean up.
4573 // Must be called on the Handler thread.
4574 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004575 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004576
4577 if (!mNetworkAgentInfos.contains(nai)) return;
4578
Chalard Jeand9fffc32018-05-11 20:19:20 +09004579 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004580 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004581 }
lucaslinb25c9a62019-02-12 15:30:13 +08004582 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004583 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004584 // A network agent has disconnected.
4585 // TODO - if we move the logic to the network agent (have them disconnect
4586 // because they lost all their requests or because their score isn't good)
4587 // then they would disconnect organically, report their new state and then
4588 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08004589 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004590 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4591 null, null);
4592 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004593 final boolean wasDefault = isDefaultNetwork(nai);
4594 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004595 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004596 }
4597 notifyIfacesChangedForNetworkStats();
4598 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4599 // by other networks that are already connected. Perhaps that can be done by
4600 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4601 // of rematchAllNetworksAndRequests
4602 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004603 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004604
4605 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004606 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4607 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08004608 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004609 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004610 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004611 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004612 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004613 synchronized (mNetworkForNetId) {
4614 // Remove the NetworkAgent, but don't mark the netId as
4615 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004616 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004617 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004618 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08004619 // Update allowed network lists in netd. This should be called after removing nai
4620 // from mNetworkAgentInfos.
4621 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004622 // Remove all previously satisfied requests.
4623 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004624 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004625 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004626 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004627 if (currentNetwork != null
4628 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004629 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004630 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4631 // rematch not to keep disconnected agents instead of setting it here ; this
4632 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004633 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004634 for (final NetworkOfferInfo noi : mNetworkOffers) {
4635 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004636 }
James Mattise3ef1912020-12-20 11:09:58 -08004637
Chalard Jean5b409c72021-02-04 13:12:59 +09004638 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004639 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004640 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004641 // network, because while incorrect this is the closest to the old (also
4642 // incorrect) behavior.
4643 mNetworkActivityTracker.updateDataActivityTracking(
4644 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004645 ensureNetworkTransitionWakelock(nai.toShortString());
4646 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004647 }
4648 }
junyulai2b6f0c22021-02-03 20:15:30 +08004649 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004650 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004651 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004652 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004653 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004654 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004655 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004656
4657 // Immediate teardown.
4658 if (nai.teardownDelayMs == 0) {
4659 destroyNetwork(nai);
4660 return;
4661 }
4662
4663 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09004664 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304665 try {
4666 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4667 } catch (RemoteException e) {
4668 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4669 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004670 }
4671 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4672 }
4673
4674 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004675 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004676 // Tell netd to clean up the configuration for this network
4677 // (routing rules, DNS, etc).
4678 // This may be slow as it requires a lot of netd shelling out to ip and
4679 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004680 // after we've rematched networks with requests (which might change the default
4681 // network or service a new request from an app), so network traffic isn't interrupted
4682 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004683 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004684 }
Chalard Jeandf29a852023-05-29 17:02:43 +09004685 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004686 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
4687 // This can never run if the code above runs because shouldDestroyNativeNetwork is
4688 // false if the network was never created.
4689 // TODO: delete when S is no longer supported.
4690 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004691 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004692 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004693 }
4694
Ken Chen6df7a902021-04-09 15:08:42 +08004695 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004696 try {
4697 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004698 final NativeNetworkConfig config;
4699 if (nai.isVPN()) {
4700 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004701 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004702 return false;
4703 }
4704 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4705 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004706 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08004707 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004708 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004709 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004710 getNetworkPermission(nai.networkCapabilities),
4711 false /* secure */,
4712 VpnManager.TYPE_VPN_NONE,
4713 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08004714 }
Ken Chen6df7a902021-04-09 15:08:42 +08004715 mNetd.networkCreate(config);
4716 mDnsResolver.createNetworkCache(nai.network.getNetId());
4717 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4718 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004719 return true;
4720 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004721 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004722 return false;
4723 }
4724 }
4725
Ken Chen6df7a902021-04-09 15:08:42 +08004726 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004727 if (mDscpPolicyTracker != null) {
4728 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
4729 }
Luke Huangfdd11f82019-04-09 18:41:49 +08004730 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004731 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004732 } catch (RemoteException | ServiceSpecificException e) {
4733 loge("Exception destroying network(networkDestroy): " + e);
4734 }
4735 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004736 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004737 } catch (RemoteException | ServiceSpecificException e) {
4738 loge("Exception destroying network: " + e);
4739 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004740 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
4741 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
4742 // gets created, could add data to DnsManager data structures that will never get deleted.
4743 mDnsManager.removeNetwork(nai.network);
4744
4745 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09004746 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004747 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
4748 }
4749
Chalard Jean254bd162022-08-25 13:04:51 +09004750 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004751 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08004752 }
4753
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004754 // If this method proves to be too slow then we can maintain a separate
4755 // pendingIntent => NetworkRequestInfo map.
4756 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4757 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004758 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4759 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4760 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004761 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004762 return entry.getValue();
4763 }
4764 }
4765 return null;
4766 }
4767
Chalard Jean524f0b12021-10-25 21:11:56 +09004768 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09004769 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09004770 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4771 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4772 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4773 // bug is fixed.
4774 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004775 throw new IllegalStateException("This NRI is already registered. New : " + nri
4776 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004777 }
4778 }
4779 }
4780 }
4781
Chalard Jeanac9ace02022-01-26 16:54:05 +09004782 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
4783 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08004784 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004785 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
4786 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004787 }
4788 return false;
4789 }
4790
James Mattisf7027322020-12-13 16:28:14 -08004791 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004792 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004793 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4794 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4795 final NetworkRequestInfo existingRequest =
4796 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004797 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004798 if (DBG) {
4799 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4800 + nri.mRequests.get(0) + " because their intents matched.");
4801 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004802 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004803 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004804 }
Erik Kline05f2b402015-04-30 12:58:40 +09004805 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004806 }
4807
James Mattisf7027322020-12-13 16:28:14 -08004808 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004809 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004810 }
4811
James Mattis3ce3d3c2021-02-09 18:18:28 -08004812 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004813 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004814 for (final NetworkRequestInfo nri : nris) {
4815 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004816 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004817 for (final NetworkRequest req : nri.mRequests) {
4818 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004819 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004820 if (req.isListen()) {
4821 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4822 if (req.networkCapabilities.hasSignalStrength()
4823 && network.satisfiesImmutableCapabilitiesOf(req)) {
4824 updateSignalStrengthThresholds(network, "REGISTER", req);
4825 }
James Mattisf7027322020-12-13 16:28:14 -08004826 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004827 }
4828 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004829
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004830 // If this NRI has a satisfier already, it is replacing an older request that
4831 // has been removed. Track it.
4832 final NetworkRequest activeRequest = nri.getActiveRequest();
4833 if (null != activeRequest) {
4834 // If there is an active request, then for sure there is a satisfier.
4835 nri.getSatisfier().addRequest(activeRequest);
4836 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004837 }
James Mattisf7027322020-12-13 16:28:14 -08004838
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004839 if (mFlags.noRematchAllRequestsOnRegister()) {
4840 rematchNetworksAndRequests(nris);
4841 } else {
4842 rematchAllNetworksAndRequests();
4843 }
James Mattis45d81842021-01-10 14:24:24 -08004844
Chalard Jean0354d8c2021-01-12 10:58:56 +09004845 // Requests that have not been matched to a network will not have been sent to the
4846 // providers, because the old satisfier and the new satisfier are the same (null in this
4847 // case). Send these requests to the providers.
4848 for (final NetworkRequestInfo nri : nris) {
4849 for (final NetworkOfferInfo noi : mNetworkOffers) {
4850 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004851 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004852 }
4853 }
4854
James Mattisf7027322020-12-13 16:28:14 -08004855 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4856 final int callingUid) {
4857 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004858 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004859 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4860 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4861 handleReleaseNetworkRequest(
4862 nri.mRequests.get(0),
4863 callingUid,
4864 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004865 }
4866 }
4867
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004868 // Determines whether the network is the best (or could become the best, if it validated), for
4869 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4870 // on the value of reason:
4871 //
4872 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4873 // then it should be torn down.
4874 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4875 // then it should be lingered.
4876 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004877 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004878
Chalard Jean254bd162022-08-25 13:04:51 +09004879 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09004880 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4881 return false;
4882 }
4883
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004884 final int numRequests;
4885 switch (reason) {
4886 case TEARDOWN:
4887 numRequests = nai.numRequestNetworkRequests();
4888 break;
4889 case LINGER:
4890 numRequests = nai.numForegroundNetworkRequests();
4891 break;
4892 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004893 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004894 return true;
4895 }
4896
Chalard Jean947acd42021-03-08 22:29:27 +09004897 if (numRequests > 0) return false;
4898
Paul Jensende49eb12015-06-25 15:30:08 -04004899 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004900 if (reason == UnneededFor.LINGER
4901 && !nri.isMultilayerRequest()
4902 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004903 // Background requests don't affect lingering.
4904 continue;
4905 }
4906
James Mattis3d229892020-11-16 16:46:28 -08004907 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004908 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004909 }
4910 }
Paul Jensende49eb12015-06-25 15:30:08 -04004911 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004912 }
4913
James Mattis3d229892020-11-16 16:46:28 -08004914 private boolean isNetworkPotentialSatisfier(
4915 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4916 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004917 // request, return immediately. For multilayer requests, check to see if any of the
4918 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004919 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4920 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004921 return false;
4922 }
4923 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004924 // This multilayer listen request is satisfied therefore no further requests need to be
4925 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004926 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004927 return false;
4928 }
James Mattis3d229892020-11-16 16:46:28 -08004929 // As non-multilayer listen requests have already returned, the below would only happen
4930 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004931 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004932 continue;
4933 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09004934 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08004935 // there is hope for it to become one if it validated, then it is needed.
4936 if (candidate.satisfies(req)) {
4937 // As soon as a network is found that satisfies a request, return. Specifically for
4938 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4939 // is important so as to not evaluate lower priority requests further in
4940 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004941 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4942 ? nri.getSatisfier() : null;
4943 // Note that this catches two important cases:
4944 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4945 // is currently satisfying the request. This is desirable when
4946 // cellular ends up validating but WiFi does not.
4947 // 2. Unvalidated WiFi will not be reaped when validated cellular
4948 // is currently satisfying the request. This is desirable when
4949 // WiFi ends up validating and out scoring cellular.
4950 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004951 }
4952 }
4953
4954 return false;
4955 }
4956
Erik Kline0c04b742016-07-07 16:50:58 +09004957 private NetworkRequestInfo getNriForAppRequest(
4958 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004959 // Looking up the app passed param request in mRequests isn't possible since it may return
4960 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4961 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004962 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4963 // to avoid potential race conditions when validating a package->uid mapping when sending
4964 // the callback on the very low-chance that an application shuts down prior to the callback
4965 // being sent.
4966 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4967 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004968
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004969 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004970 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004971 log(String.format("UID %d attempted to %s for unowned request %s",
4972 callingUid, requestedOperation, nri));
4973 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004974 }
Erik Kline0c04b742016-07-07 16:50:58 +09004975 }
4976
4977 return nri;
4978 }
4979
James Mattisf7027322020-12-13 16:28:14 -08004980 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4981 final String callingMethod) {
4982 if (nri.isMultilayerRequest()) {
4983 throw new IllegalStateException(
4984 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004985 }
4986 }
4987
James Mattisf7027322020-12-13 16:28:14 -08004988 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004989 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004990 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4991 // single NetworkRequest and thus does not apply to multilayer requests.
4992 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4993 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004994 return;
4995 }
James Mattis2516da32021-01-31 17:06:19 -08004996 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004997 return;
4998 }
James Mattisf7027322020-12-13 16:28:14 -08004999 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5000 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005001 }
5002 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005003 callCallbackForRequest(
5004 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005005 }
5006
James Mattisf7027322020-12-13 16:28:14 -08005007 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5008 final int callingUid,
5009 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005010 final NetworkRequestInfo nri =
5011 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5012 if (nri == null) {
5013 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005014 }
James Mattisf7027322020-12-13 16:28:14 -08005015 if (VDBG || (DBG && request.isRequest())) {
5016 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005017 }
5018 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005019 if (callOnUnavailable) {
5020 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5021 }
Erik Kline155a59a2015-11-25 12:49:38 +09005022 }
Erik Kline0c04b742016-07-07 16:50:58 +09005023
James Mattisa076c532020-12-02 14:12:41 -08005024 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005025 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005026 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005027 if (null == mNetworkRequests.remove(req)) {
5028 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5029 continue;
5030 }
James Mattisa076c532020-12-02 14:12:41 -08005031 if (req.isListen()) {
5032 removeListenRequestFromNetworks(req);
5033 }
5034 }
James Mattis8f036802021-06-20 16:26:01 -07005035 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005036 if (mDefaultNetworkRequests.remove(nri)) {
5037 // If this request was one of the defaults, then the UID rules need to be updated
5038 // WARNING : if the app(s) for which this network request is the default are doing
5039 // traffic, this will kill their connected sockets, even if an equivalent request
5040 // is going to be reinstated right away ; unconnected traffic will go on the default
5041 // until the new default is set, which will happen very soon.
5042 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5043 // remove ranges for those requests that won't have a replacement
5044 final NetworkAgentInfo satisfier = nri.getSatisfier();
5045 if (null != satisfier) {
5046 try {
paulhu0e79d952021-06-09 16:11:35 +08005047 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5048 satisfier.network.getNetId(),
5049 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005050 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005051 } catch (RemoteException e) {
5052 loge("Exception setting network preference default network", e);
5053 }
5054 }
5055 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005056
Junyu Lai00d92df2022-07-05 11:01:52 +08005057 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005058 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005059 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005060
5061 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005062 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005063 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005064 }
5065 }
5066
Chalard Jean0354d8c2021-01-12 10:58:56 +09005067 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5068 // needed for this offer.
5069 for (final NetworkOfferInfo noi : mNetworkOffers) {
5070 for (final NetworkRequest req : nri.mRequests) {
5071 if (req.isRequest() && noi.offer.neededFor(req)) {
5072 noi.offer.onNetworkUnneeded(req);
5073 }
5074 }
5075 }
James Mattisa076c532020-12-02 14:12:41 -08005076 }
5077
James Mattis3ce3d3c2021-02-09 18:18:28 -08005078 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5079 for (final NetworkRequestInfo nri : nris) {
5080 if (mDefaultRequest == nri) {
5081 // Make sure we never remove the default request.
5082 continue;
5083 }
5084 handleRemoveNetworkRequest(nri);
5085 }
5086 }
5087
James Mattisa076c532020-12-02 14:12:41 -08005088 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5089 // listens don't have a singular affected Network. Check all networks to see
5090 // if this listen request applies and remove it.
5091 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5092 nai.removeRequest(req.requestId);
5093 if (req.networkCapabilities.hasSignalStrength()
5094 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5095 updateSignalStrengthThresholds(nai, "RELEASE", req);
5096 }
5097 }
5098 }
5099
5100 /**
5101 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5102 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5103 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5104 */
5105 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5106 boolean wasKept = false;
5107 final NetworkAgentInfo nai = nri.getSatisfier();
5108 if (nai != null) {
5109 final int requestLegacyType = nri.getActiveRequest().legacyType;
5110 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5111 nai.removeRequest(nri.getActiveRequest().requestId);
5112 if (VDBG || DDBG) {
5113 log(" Removing from current network " + nai.toShortString()
5114 + ", leaving " + nai.numNetworkRequests() + " requests.");
5115 }
5116 // If there are still lingered requests on this network, don't tear it down,
5117 // but resume lingering instead.
5118 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005119 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005120 notifyNetworkLosing(nai, now);
5121 }
5122 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5123 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5124 teardownUnneededNetwork(nai);
5125 } else {
5126 wasKept = true;
5127 }
James Mattisa076c532020-12-02 14:12:41 -08005128 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5129 // Went from foreground to background.
5130 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005131 }
5132
Erik Kline0c04b742016-07-07 16:50:58 +09005133 // Maintain the illusion. When this request arrived, we might have pretended
5134 // that a network connected to serve it, even though the network was already
5135 // connected. Now that this request has gone away, we might have to pretend
5136 // that the network disconnected. LegacyTypeTracker will generate that
5137 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005138 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005139 boolean doRemove = true;
5140 if (wasKept) {
5141 // check if any of the remaining requests for this network are for the
5142 // same legacy type - if so, don't remove the nai
5143 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5144 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005145 if (otherRequest.legacyType == requestLegacyType
5146 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005147 if (DBG) log(" still have other legacy request - leaving");
5148 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005149 }
5150 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005151 }
5152
Erik Kline0c04b742016-07-07 16:50:58 +09005153 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005154 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005155 }
5156 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005157 }
5158 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005159
Junyu Lai00d92df2022-07-05 11:01:52 +08005160 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005161 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005162 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5163 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5164 }
5165
Lorenzo Colittid6459092016-07-04 12:55:44 +09005166 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005167 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005168 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005169 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005170 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005171 }
5172
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005173 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005174 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5175 enforceNetworkStackSettingsOrSetup();
5176 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5177 encodeBool(accept), encodeBool(always), network));
5178 }
5179
5180 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005181 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005182 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005183 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5184 }
5185
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005186 @Override
5187 public void setTestAllowBadWifiUntil(long timeMs) {
5188 enforceSettingsPermission();
5189 if (!Build.isDebuggable()) {
5190 throw new IllegalStateException("Does not support in non-debuggable build");
5191 }
5192
5193 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5194 throw new IllegalArgumentException("It should not exceed "
5195 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5196 }
5197
5198 mHandler.sendMessage(
5199 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5200 }
5201
chiachangwange0192a72023-02-06 13:25:01 +00005202 @Override
5203 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5204 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005205
5206 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5207 throw new IllegalArgumentException("Argument should not exceed "
5208 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5209 }
5210
5211 mHandler.sendMessage(
5212 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5213 }
5214
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005215 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5216 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5217 " accept=" + accept + " always=" + always);
5218
5219 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5220 if (nai == null) {
5221 // Nothing to do.
5222 return;
5223 }
5224
Chalard Jean254bd162022-08-25 13:04:51 +09005225 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005226 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005227 return;
5228 }
5229
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005230 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005231 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005232 }
5233
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005234 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5235 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005236 // If network becomes partial connectivity and user already accepted to use this
5237 // network, we should respect the user's option and don't need to popup the
5238 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005239 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005240 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005241 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005242 }
5243
5244 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005245 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005246 }
5247
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005248 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005249 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005250 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005251 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005252 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005253 }
5254
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005255 }
5256
lucaslin2240ef62019-03-12 13:08:03 +08005257 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5258 boolean always) {
5259 if (DBG) {
5260 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5261 + " always=" + always);
5262 }
5263
5264 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5265 if (nai == null) {
5266 // Nothing to do.
5267 return;
5268 }
5269
Chalard Jean254bd162022-08-25 13:04:51 +09005270 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005271 // The network validated while the dialog box was up. Take no action.
5272 return;
5273 }
5274
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005275 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5276 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005277 }
5278
5279 // TODO: Use the current design or save the user choice into IpMemoryStore.
5280 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005281 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005282 }
5283
5284 if (!accept) {
5285 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005286 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005287 // Tear down the network.
5288 teardownUnneededNetwork(nai);
5289 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005290 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5291 // result in a partial connectivity result which will be processed by
5292 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005293 //
5294 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5295 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005296 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005297 }
5298 }
5299
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005300 private void handleSetAvoidUnvalidated(Network network) {
5301 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005302 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005303 // Nothing to do. The network either disconnected or revalidated.
5304 return;
5305 }
Chalard Jean254bd162022-08-25 13:04:51 +09005306 if (0L == nai.getAvoidUnvalidated()) {
5307 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005308 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005309 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005310 }
5311 }
5312
Chalard Jean5fb43c72022-09-08 19:03:14 +09005313 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005314 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005315 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005316 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005317 }
5318
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005319 @Override
5320 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005321 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005322 mHandler.post(() -> {
5323 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5324 if (nai == null) return;
5325 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005326 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005327 });
5328 }
5329
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005330 /**
5331 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5332 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005333 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005334 * @param appExtras Bundle to use as intent extras for the captive portal application.
5335 * Must be treated as opaque to avoid preventing the captive portal app to
5336 * update its arguments.
5337 */
5338 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005339 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005340 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5341 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005342
5343 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5344 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005345 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5346 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005347 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5348
lucaslin75ff7022020-12-17 04:14:35 +08005349 final long token = Binder.clearCallingIdentity();
5350 try {
5351 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5352 } finally {
5353 Binder.restoreCallingIdentity(token);
5354 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005355 }
5356
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005357 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5358 private final Network mNetwork;
5359
5360 private CaptivePortalImpl(Network network) {
5361 mNetwork = network;
5362 }
5363
5364 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005365 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005366 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5367 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005368 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5369 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5370 // Since the network will be disconnected, skip notifying NetworkMonitor
5371 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005372 }
5373
Chiachang Wang938bfba2020-01-09 13:50:55 +08005374 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005375 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005376 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005377 }
5378
5379 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005380 public void appRequest(final int request) {
5381 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5382 if (nm == null) return;
5383
5384 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005385 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005386 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005387 }
5388 }
5389
5390 @Nullable
5391 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5392 // getNetworkAgentInfoForNetwork is thread-safe
5393 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5394 if (nai == null) return null;
5395
5396 // nai.networkMonitor() is thread-safe
5397 return nai.networkMonitor();
5398 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005399 }
5400
Hugo Benichic9048bc2016-09-14 23:23:08 +00005401 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005402 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005403 }
5404
Chalard Jean020b93a2022-09-01 13:20:14 +09005405 private boolean activelyPreferBadWifi() {
5406 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5407 }
5408
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005409 /**
5410 * Return whether the device should maintain continuous, working connectivity by switching away
5411 * from WiFi networks having no connectivity.
5412 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5413 */
5414 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005415 if (!checkNetworkStackPermission()) {
5416 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5417 }
5418 return avoidBadWifi();
5419 }
5420
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005421 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005422 ensureRunningOnConnectivityServiceThread();
5423 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005424 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005425 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005426 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005427 if (avoidBadWifi) {
5428 // If the device is now avoiding bad wifi, remove notifications that might have
5429 // been put up when the device didn't.
5430 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5431 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005432 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005433 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5434 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5435 for (final NetworkOfferInfo noi : offersToUpdate) {
5436 updateOfferScore(noi.offer);
5437 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005438 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005439 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005440 }
5441
Erik Kline95ecfee2016-10-02 18:02:14 +09005442 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005443 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005444 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005445 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005446 if (!configRestrict) {
5447 pw.println("Bad Wi-Fi avoidance: unrestricted");
5448 return;
5449 }
5450
5451 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5452 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005453 pw.println("Config restrict: " + configRestrict);
5454 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005455
Chalard Jeane0fdea32022-09-14 21:44:22 +09005456 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005457 String description;
5458 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005459 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005460 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005461 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005462 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005463 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005464 description = "avoid";
5465 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005466 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005467 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005468 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005469
5470 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5471 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005472 if (null == configValue) {
5473 description = "unset";
5474 } else if (configValue) {
5475 description = "force true";
5476 } else {
5477 description = "force false";
5478 }
5479 pw.println("Actively prefer bad wifi conf: " + description);
5480 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005481 pw.println("Network overrides:");
5482 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005483 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005484 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005485 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005486 }
5487 }
5488 pw.decreaseIndent();
5489 pw.decreaseIndent();
5490 }
5491
paulhu7746e4e2020-06-09 19:07:03 +08005492 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5493 // unify the method.
5494 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5495 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5496 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5497 return settingsComponent != null
5498 ? settingsComponent.getPackageName() : "com.android.settings";
5499 }
5500
lucaslinb1e8e382019-01-24 15:55:30 +08005501 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005502 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005503 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005504 switch (type) {
5505 case NO_INTERNET:
5506 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005507 // High priority because it is only displayed for explicitly selected networks.
5508 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005509 break;
lucasline117e2e2019-10-22 18:27:33 +08005510 case PRIVATE_DNS_BROKEN:
5511 action = Settings.ACTION_WIRELESS_SETTINGS;
5512 // High priority because we should let user know why there is no internet.
5513 highPriority = true;
5514 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005515 case LOST_INTERNET:
5516 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005517 // High priority because it could help the user avoid unexpected data usage.
5518 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005519 break;
lucaslin2240ef62019-03-12 13:08:03 +08005520 case PARTIAL_CONNECTIVITY:
5521 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005522 // Don't bother the user with a high-priority notification if the network was not
5523 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005524 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005525 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005526 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005527 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005528 return;
5529 }
5530
5531 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005532 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005533 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005534 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005535 // Some OEMs have their own Settings package. Thus, need to get the current using
5536 // Settings package name instead of just use default name "com.android.settings".
5537 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5538 intent.setClassName(settingsPkgName,
5539 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005540 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005541
paulhu2af50222020-10-11 22:52:27 +08005542 PendingIntent pendingIntent = PendingIntent.getActivity(
5543 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005544 0 /* requestCode */,
5545 intent,
paulhu2af50222020-10-11 22:52:27 +08005546 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005547
Serik Beketayevec8ad212020-12-07 22:43:07 -08005548 mNotifier.showNotification(
5549 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005550 }
5551
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005552 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5553 // Don't prompt if the network is validated, and don't prompt on captive portals
5554 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005555 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005556 return false;
5557 }
5558
5559 // If a network has partial connectivity, always prompt unless the user has already accepted
5560 // partial connectivity and selected don't ask again. This ensures that if the device
5561 // automatically connects to a network that has partial Internet access, the user will
5562 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005563 // because we have prompted them.
5564 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005565 return true;
5566 }
5567
5568 // If a network has no Internet access, only prompt if the network was explicitly selected
5569 // and if the user has not already told us to use the network regardless of whether it
5570 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005571 if (nai.networkAgentConfig.explicitlySelected
5572 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005573 return true;
5574 }
5575
5576 return false;
5577 }
5578
Chalard Jean5fb43c72022-09-08 19:03:14 +09005579 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5580 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005581
Chalard Jean5fb43c72022-09-08 19:03:14 +09005582 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5583 if (null == nai) return;
5584
5585 if (nai.setEvaluated()) {
5586 // If setEvaluated() returned true, the network never had any form of connectivity.
5587 // This may have an impact on request matching if bad WiFi avoidance is off and the
5588 // network was found not to have Internet access.
5589 nai.updateScoreForNetworkAgentUpdate();
5590 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09005591
5592 // Also, if this is WiFi and it should be preferred actively, now is the time to
5593 // prompt the user that they walked past and connected to a bad WiFi.
5594 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
5595 && !avoidBadWifi()
5596 && activelyPreferBadWifi()) {
5597 // The notification will be removed if the network validates or disconnects.
5598 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
5599 return;
5600 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005601 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005602
Chalard Jean5fb43c72022-09-08 19:03:14 +09005603 if (!shouldPromptUnvalidated(nai)) return;
5604
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005605 // Stop automatically reconnecting to this network in the future. Automatically connecting
5606 // to a network that provides no or limited connectivity is not useful, because the user
5607 // cannot use that network except through the notification shown by this method, and the
5608 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005609 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005610
Chalard Jean254bd162022-08-25 13:04:51 +09005611 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005612 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005613 } else {
5614 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5615 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005616 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005617
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005618 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5619 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005620 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005621
lucaslin2240ef62019-03-12 13:08:03 +08005622 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5623 return;
5624 }
5625
5626 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005627 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005628 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005629 }
5630
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005631 @Override
5632 public int getMultipathPreference(Network network) {
5633 enforceAccessPermission();
5634
5635 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005636 if (nai != null && nai.networkCapabilities
5637 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005638 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5639 }
5640
Aaron Huang9a57acf2020-12-08 10:03:29 +08005641 final NetworkPolicyManager netPolicyManager =
5642 mContext.getSystemService(NetworkPolicyManager.class);
5643
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005644 final long token = Binder.clearCallingIdentity();
5645 final int networkPreference;
5646 try {
5647 networkPreference = netPolicyManager.getMultipathPreference(network);
5648 } finally {
5649 Binder.restoreCallingIdentity(token);
5650 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005651 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005652 return networkPreference;
5653 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005654 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5655 }
5656
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005657 @Override
5658 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005659 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005660 }
5661
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005662 private class InternalHandler extends Handler {
5663 public InternalHandler(Looper looper) {
5664 super(looper);
5665 }
5666
5667 @Override
5668 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005669 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005670 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005671 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005672 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005673 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005674 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005675 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005676 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005677 break;
5678 }
Jason Monka69f1b02013-10-10 14:02:51 -04005679 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005680 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5681 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005682 break;
5683 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005684 case EVENT_REGISTER_NETWORK_PROVIDER: {
5685 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005686 break;
5687 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005688 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5689 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005690 break;
5691 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005692 case EVENT_REGISTER_NETWORK_OFFER: {
5693 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5694 break;
5695 }
5696 case EVENT_UNREGISTER_NETWORK_OFFER: {
5697 final NetworkOfferInfo offer =
5698 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5699 if (null != offer) {
5700 handleUnregisterNetworkOffer(offer);
5701 }
5702 break;
5703 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005704 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005705 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5706 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5707 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005708 break;
5709 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005710 case EVENT_REGISTER_NETWORK_REQUEST:
5711 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005712 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005713 break;
5714 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005715 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5716 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005717 handleRegisterNetworkRequestWithIntent(msg);
5718 break;
5719 }
Erik Kline155a59a2015-11-25 12:49:38 +09005720 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5721 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5722 handleTimedOutNetworkRequest(nri);
5723 break;
5724 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005725 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5726 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5727 break;
5728 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005729 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005730 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5731 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005732 break;
5733 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005734 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005735 Network network = (Network) msg.obj;
5736 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005737 break;
5738 }
lucaslin2240ef62019-03-12 13:08:03 +08005739 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5740 Network network = (Network) msg.obj;
5741 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5742 toBool(msg.arg2));
5743 break;
5744 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005745 case EVENT_SET_AVOID_UNVALIDATED: {
5746 handleSetAvoidUnvalidated((Network) msg.obj);
5747 break;
5748 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09005749 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
5750 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005751 break;
5752 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005753 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5754 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005755 break;
5756 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00005757 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
5758 // handler thread.
5759 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005760 mKeepaliveTracker.handleStartKeepalive(msg);
5761 break;
5762 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00005763 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09005764 final AutomaticOnOffKeepalive ki =
5765 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
5766 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005767
chiachangwang676c84e2023-02-14 09:22:05 +00005768 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005769 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005770 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00005771 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005772 for (NetworkAgentInfo n : mNetworkAgentInfos) {
5773 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00005774 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
5775 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005776 }
5777 }
5778
5779 // If the network no longer exists, then the keepalive should have been
5780 // cleaned up already. There is no point trying to resume keepalives.
5781 if (!networkFound) return;
5782
chiachangwang676c84e2023-02-14 09:22:05 +00005783 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005784 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
chiachangwang676c84e2023-02-14 09:22:05 +00005785 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005786 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00005787 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005788 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005789 }
5790 break;
5791 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005792 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005793 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09005794 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
5795 (IBinder) msg.obj);
5796 if (ki == null) {
5797 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00005798 return;
5799 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09005800 final int reason = msg.arg2;
5801 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005802 break;
5803 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005804 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5805 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5806 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005807 break;
5808 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005809 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5810 handlePrivateDnsSettingsChanged();
5811 break;
dalyk1720e542018-03-05 12:42:22 -05005812 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5813 handlePrivateDnsValidationUpdate(
5814 (PrivateDnsValidationUpdate) msg.obj);
5815 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005816 case EVENT_UID_BLOCKED_REASON_CHANGED:
5817 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005818 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005819 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5820 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5821 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005822 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005823 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5824 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005825 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005826 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005827 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005828 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09005829 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
5830 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005831 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005832 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005833 }
lucaslin1193a5d2021-01-21 02:04:15 +08005834 case EVENT_REPORT_NETWORK_ACTIVITY:
5835 mNetworkActivityTracker.handleReportNetworkActivity();
5836 break;
paulhu51f77dc2021-06-07 02:34:20 +00005837 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5838 handleMobileDataPreferredUidsChanged();
5839 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005840 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5841 final long timeMs = ((Long) msg.obj).longValue();
5842 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5843 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01005844 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
5845 handleIngressRateLimitChanged();
5846 break;
Hansen Kurli55396972022-10-28 03:31:17 +00005847 case EVENT_USER_DOES_NOT_WANT:
5848 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5849 if (nai == null) break;
5850 nai.onPreventAutomaticReconnect();
5851 nai.disconnect();
5852 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00005853 case EVENT_SET_VPN_NETWORK_PREFERENCE:
5854 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
5855 break;
chiachangwange0192a72023-02-06 13:25:01 +00005856 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
5857 final long time = ((Long) msg.obj).longValue();
5858 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
5859 break;
5860 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00005861 case EVENT_UID_FROZEN_STATE_CHANGED:
5862 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
5863 handleFrozenUids(args.mUids, args.mFrozenStates);
5864 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005865 }
5866 }
5867 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005868
Lorenzo Colittid6459092016-07-04 12:55:44 +09005869 @Override
markchien5776f962019-12-16 20:15:20 +08005870 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005871 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08005872 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005873 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5874 Context.TETHERING_SERVICE);
5875 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005876 }
5877
Lorenzo Colittid6459092016-07-04 12:55:44 +09005878 @Override
markchien5776f962019-12-16 20:15:20 +08005879 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005880 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08005881 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005882 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5883 Context.TETHERING_SERVICE);
5884 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005885 }
5886
Lorenzo Colittid6459092016-07-04 12:55:44 +09005887 @Override
markchien5776f962019-12-16 20:15:20 +08005888 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005889 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005890 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005891 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5892 Context.TETHERING_SERVICE);
5893 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005894 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005895
markchien5776f962019-12-16 20:15:20 +08005896
Lorenzo Colittid6459092016-07-04 12:55:44 +09005897 @Override
markchien5776f962019-12-16 20:15:20 +08005898 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005899 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005900 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005901 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5902 Context.TETHERING_SERVICE);
5903
5904 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005905 }
5906
Lorenzo Colittid6459092016-07-04 12:55:44 +09005907 @Override
markchien5776f962019-12-16 20:15:20 +08005908 @Deprecated
5909 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08005910 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005911 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5912 Context.TETHERING_SERVICE);
5913
5914 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005915 }
5916
Udam Saini8f7d6a72017-06-07 12:06:28 -07005917 @Override
markchien5776f962019-12-16 20:15:20 +08005918 @Deprecated
5919 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08005920 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005921 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5922 Context.TETHERING_SERVICE);
5923 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005924 }
5925
Robert Greenwalte0b00512014-07-02 09:59:16 -07005926 // Called when we lose the default network and have no replacement yet.
5927 // This will automatically be cleared after X seconds or a new default network
5928 // becomes CONNECTED, whichever happens first. The timer is started by the
5929 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005930 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005931 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005932 if (mNetTransitionWakeLock.isHeld()) {
5933 return;
5934 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005935 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005936 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5937 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005938 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005939 mWakelockLogs.log("ACQUIRE for " + forWhom);
5940 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005941 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005942 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005943 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005944 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005945
Hugo Benichi471b62a2017-03-30 23:18:10 +09005946 // Called when we gain a new default network to release the network transition wakelock in a
5947 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5948 // message is cancelled.
5949 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005950 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005951 if (!mNetTransitionWakeLock.isHeld()) {
5952 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005953 }
5954 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005955 // Cancel self timeout on wakelock hold.
5956 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5957 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5958 mHandler.sendMessageDelayed(msg, 1000);
5959 }
5960
5961 // Called when either message of ensureNetworkTransitionWakelock or
5962 // scheduleReleaseNetworkTransitionWakelock is processed.
5963 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5964 String event = eventName(eventId);
5965 synchronized (this) {
5966 if (!mNetTransitionWakeLock.isHeld()) {
5967 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005968 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005969 return;
5970 }
5971 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005972 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5973 mTotalWakelockDurationMs += lockDuration;
5974 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5975 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005976 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005977 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005978 }
5979
Robert Greenwalt986c7412010-09-08 15:24:47 -07005980 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005981 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005982 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005983 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005984 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005985 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005986 }
5987
Lorenzo Colittid6459092016-07-04 12:55:44 +09005988 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005989 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005990 enforceAccessPermission();
5991 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005992 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005993 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005994
5995 final NetworkAgentInfo nai;
5996 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005997 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005998 } else {
5999 nai = getNetworkAgentInfoForNetwork(network);
6000 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006001
6002 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006003 mHandler.obtainMessage(
6004 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006005 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006006
Hugo Benichid6b510a2017-04-06 17:22:18 +09006007 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006008 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006009 if (nai == null
6010 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006011 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006012 return;
6013 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006014 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006015 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006016 mConnectivityDiagnosticsHandler.sendMessage(
6017 mConnectivityDiagnosticsHandler.obtainMessage(
6018 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6019 new ReportedNetworkConnectivityInfo(
6020 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006021 return;
6022 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006023 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006024 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006025 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006026 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006027 // Validating a network that has not yet connected could result in a call to
6028 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006029 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006030 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006031 }
paulhu7aeba372020-12-30 00:42:19 +08006032 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6033 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006034 return;
6035 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006036
6037 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6038 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6039 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6040 // completed.
6041 mConnectivityDiagnosticsHandler.sendMessage(
6042 mConnectivityDiagnosticsHandler.obtainMessage(
6043 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6044 new ReportedNetworkConnectivityInfo(
6045 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006046 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006047 }
6048
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006049 // TODO: call into netd.
6050 private boolean queryUserAccess(int uid, Network network) {
6051 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6052 if (nai == null) return false;
6053
6054 // Any UID can use its default network.
6055 if (nai == getDefaultNetworkForUid(uid)) return true;
6056
6057 // Privileged apps can use any network.
6058 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6059 return true;
6060 }
6061
6062 // An unprivileged UID can use a VPN iff the VPN applies to it.
6063 if (nai.isVPN()) {
6064 return nai.networkCapabilities.appliesToUid(uid);
6065 }
6066
6067 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6068 // sockets, i.e., if it is the owner.
6069 final NetworkAgentInfo vpn = getVpnForUid(uid);
6070 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6071 && uid != vpn.networkCapabilities.getOwnerUid()) {
6072 return false;
6073 }
6074
6075 // The UID's permission must be at least sufficient for the network. Since the restricted
6076 // permission was already checked above, that just leaves background networks.
6077 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6078 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6079 }
6080
6081 // Unrestricted network. Anyone gets to use it.
6082 return true;
6083 }
6084
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006085 /**
6086 * Returns information about the proxy a certain network is using. If given a null network, it
6087 * it will return the proxy for the bound network for the caller app or the default proxy if
6088 * none.
6089 *
6090 * @param network the network we want to get the proxy information for.
6091 * @return Proxy information if a network has a proxy configured, or otherwise null.
6092 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006093 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006094 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006095 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006096 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006097 if (network == null) {
6098 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006099 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006100 true);
6101 if (activeNetwork == null) {
6102 return null;
6103 }
6104 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006105 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006106 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6107 // caller may not have.
6108 return getLinkPropertiesProxyInfo(network);
6109 }
6110 // No proxy info available if the calling UID does not have network access.
6111 return null;
6112 }
6113
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006114
6115 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006116 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6117 if (nai == null) return null;
6118 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006119 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6120 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006121 }
6122 }
6123
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006124 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006125 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006126 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006127 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006128 }
6129
Chalard Jean777e2e52018-06-07 18:02:37 +09006130 @Override
6131 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006132 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006133 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006134 }
6135
Junyu Lai970963e2022-10-25 15:46:47 +08006136 private void handleApplyDefaultProxy(@Nullable ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04006137 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05006138 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07006139 proxy = null;
6140 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006141 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006142 }
6143
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006144 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6145 // when any network changes proxy.
6146 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6147 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006148 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6149 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006150 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6151
Chalard Jean7d97afc2018-06-07 17:41:29 +09006152 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006153 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006154 }
6155 }
6156
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006157 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006158 final private HashMap<Uri, Integer> mUriEventMap;
6159 final private Context mContext;
6160 final private Handler mHandler;
6161
6162 SettingsObserver(Context context, Handler handler) {
6163 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006164 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006165 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006166 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006167 }
6168
Erik Kline05f2b402015-04-30 12:58:40 +09006169 void observe(Uri uri, int what) {
6170 mUriEventMap.put(uri, what);
6171 final ContentResolver resolver = mContext.getContentResolver();
6172 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006173 }
6174
6175 @Override
6176 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006177 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006178 }
6179
6180 @Override
6181 public void onChange(boolean selfChange, Uri uri) {
6182 final Integer what = mUriEventMap.get(uri);
6183 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006184 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006185 } else {
6186 loge("No matching event to send for URI=" + uri);
6187 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006188 }
6189 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006190
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006191 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006192 Log.d(TAG, s);
6193 }
6194
6195 private static void logw(String s) {
6196 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006197 }
6198
Daniel Brightf9e945b2020-06-15 16:10:01 -07006199 private static void logwtf(String s) {
6200 Log.wtf(TAG, s);
6201 }
6202
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006203 private static void logwtf(String s, Throwable t) {
6204 Log.wtf(TAG, s, t);
6205 }
6206
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006207 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006208 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006209 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006210
Hugo Benichi39621362017-02-11 17:04:43 +09006211 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006212 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006213 }
6214
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006215 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006216 * Return the information of all ongoing VPNs.
6217 *
6218 * <p>This method is used to update NetworkStatsService.
6219 *
6220 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006221 */
junyulai2050bed2021-01-23 09:46:34 +08006222 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006223 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006224 if (mLockdownEnabled) {
6225 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006226 }
junyulai2050bed2021-01-23 09:46:34 +08006227 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006228 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006229 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006230 if (info != null) {
6231 infoList.add(info);
6232 }
6233 }
junyulai2050bed2021-01-23 09:46:34 +08006234 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006235 }
6236
6237 /**
6238 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006239 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006240 */
junyulai2050bed2021-01-23 09:46:34 +08006241 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006242 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006243 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6244 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006245 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6246 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6247 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006248 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6249 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006250 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006251 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006252 }
6253 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006254
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006255 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006256
6257 List<String> interfaces = new ArrayList<>();
6258 for (Network network : underlyingNetworks) {
6259 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6260 if (underlyingNai == null) continue;
6261 LinkProperties lp = underlyingNai.linkProperties;
6262 for (String iface : lp.getAllInterfaceNames()) {
6263 if (!TextUtils.isEmpty(iface)) {
6264 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006265 }
6266 }
Benedict Wong34857f82019-06-12 17:46:15 +00006267 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006268
6269 if (interfaces.isEmpty()) return null;
6270
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006271 // Must be non-null or NetworkStatsService will crash.
6272 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6273 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006274 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006275 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006276
junyulai2050bed2021-01-23 09:46:34 +08006277 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6278 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006279 }
6280
James Mattisd31bdfa2020-12-23 16:37:26 -08006281 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006282 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6283 Network[] underlyingNetworks) {
6284 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006285 if (underlyingNetworks == null && defaultNetwork != null) {
6286 // null underlying networks means to track the default.
6287 underlyingNetworks = new Network[] { defaultNetwork };
6288 }
6289 return underlyingNetworks;
6290 }
6291
6292 // Returns true iff |network| is an underlying network of |nai|.
6293 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6294 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6295 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006296 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006297 final Network[] underlying = underlyingNetworksOrDefault(
6298 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006299 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006300 }
6301
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006302 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006303 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006304 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006305 * When underlying networks change, such networks may have to update capabilities to reflect
6306 * things like the metered bit, their transports, and so on. The capabilities are calculated
6307 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006308 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006309 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006310 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006311 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006312 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006313 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006314 }
6315 }
6316 }
6317
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006318 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6319 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6320 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6321 // a VPN is not up.
6322 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6323 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6324 for (UidRange range : blockedUidRanges) {
6325 if (range.contains(uid)) return true;
6326 }
6327 return false;
6328 }
6329
6330 @Override
6331 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006332 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006333 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6334 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6335 }
6336
6337 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6338 if (DBG) {
6339 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6340 + Arrays.toString(ranges));
6341 }
6342 // Cannot use a Set since the list of UID ranges might contain duplicates.
6343 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6344 for (int i = 0; i < ranges.length; i++) {
6345 if (requireVpn) {
6346 newVpnBlockedUidRanges.add(ranges[i]);
6347 } else {
6348 newVpnBlockedUidRanges.remove(ranges[i]);
6349 }
6350 }
6351
6352 try {
6353 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6354 } catch (RemoteException | ServiceSpecificException e) {
6355 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6356 + Arrays.toString(ranges) + "): netd command failed: " + e);
6357 }
6358
Chalard Jeandf29a852023-05-29 17:02:43 +09006359 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006360 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6361 }
6362
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006363 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6364 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006365 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6366 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006367 }
6368
6369 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6370 }
6371
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006372 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006373 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006374 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006375 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006376 }
6377
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006378 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6379 return mLockdownEnabled
6380 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6381 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006382 }
6383
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006384 private NetworkAgentInfo getLegacyLockdownNai() {
6385 if (!mLockdownEnabled) {
6386 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006387 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006388 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006389 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6390 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006391
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006392 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006393 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6394 // a local variable. There is no need to make a copy because its contents cannot change.
6395 final Network[] underlying = nai.declaredUnderlyingNetworks;
6396 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006397 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006398 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006399
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006400 // The legacy lockdown VPN always uses the default network.
6401 // If the VPN's underlying network is no longer the current default network, it means that
6402 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006403 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6404 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006405 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006406 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006407 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006408 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006409
6410 return nai;
6411 };
6412
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006413 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6414 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6415 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006416 private DetailedState getLegacyLockdownState(DetailedState origState) {
6417 if (origState != DetailedState.CONNECTED) {
6418 return origState;
6419 }
6420 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6421 ? DetailedState.CONNECTING
6422 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006423 }
6424
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006425 private void filterForLegacyLockdown(NetworkInfo ni) {
6426 if (!mLockdownEnabled || !ni.isConnected()) return;
6427 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6428 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6429 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6430 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6431 // network, this time with a state of CONNECTED.
6432 //
6433 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6434 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6435 // is not too far off the truth, since an always-on VPN, when not connected, is always
6436 // trying to reconnect.
6437 if (getLegacyLockdownNai() == null) {
6438 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6439 }
6440 }
6441
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006442 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006443 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006444 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006445 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006446 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6447 return;
6448 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006449 final long ident = Binder.clearCallingIdentity();
6450 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006451 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006452 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006453 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006454 } finally {
6455 Binder.restoreCallingIdentity(ident);
6456 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006457 }
Wink Savillecb117d32013-08-29 14:57:08 -07006458
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006459 @Override
6460 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006461 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006462 final long ident = Binder.clearCallingIdentity();
6463 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006464 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006465 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006466 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6467 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006468 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006469 } finally {
6470 Binder.restoreCallingIdentity(ident);
6471 }
6472 }
6473
James Mattis02220e22021-03-13 19:27:21 -08006474 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006475 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6476 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6477 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006478 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006479 }
6480
James Mattis02220e22021-03-13 19:27:21 -08006481 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006482 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006483 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006484 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6485 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006486 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006487 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6488 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6489 }
junyulaid91e7052020-08-28 13:44:33 +08006490 }
6491
James Mattis02220e22021-03-13 19:27:21 -08006492 private void onPackageChanged(@NonNull final String packageName) {
6493 // This is necessary in case a package is added or removed, but also when it's replaced to
6494 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6495 // as one in the preferences, then it should follow the same routing as that other package,
6496 // which means updating the rules is never to be needed in this case (whether it joins or
6497 // leaves a UID with a preference).
6498 if (isMappedInOemNetworkPreference(packageName)) {
6499 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6500 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09006501
6502 // Invalidates cache entry when the package is updated.
6503 synchronized (mSelfCertifiedCapabilityCache) {
6504 mSelfCertifiedCapabilityCache.remove(packageName);
6505 }
James Mattis02220e22021-03-13 19:27:21 -08006506 }
6507
6508 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006509 @Override
6510 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006511 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006512 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006513 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006514
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006515 // User should be filled for below intents, check the existence.
6516 if (user == null) {
6517 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6518 return;
6519 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006520
Lorenzo Colitticd675292021-02-04 17:32:07 +09006521 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006522 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006523 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006524 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006525 } else {
junyulaid91e7052020-08-28 13:44:33 +08006526 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006527 }
6528 }
6529 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006530
James Mattis02220e22021-03-13 19:27:21 -08006531 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6532 @Override
6533 public void onReceive(Context context, Intent intent) {
6534 ensureRunningOnConnectivityServiceThread();
6535 switch (intent.getAction()) {
6536 case Intent.ACTION_PACKAGE_ADDED:
6537 case Intent.ACTION_PACKAGE_REMOVED:
6538 case Intent.ACTION_PACKAGE_REPLACED:
6539 onPackageChanged(intent.getData().getSchemeSpecificPart());
6540 break;
6541 default:
6542 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6543 }
6544 }
6545 };
6546
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006547 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006548 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006549
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006550 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006551 public final String name;
6552 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006553 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006554 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006555
lifraf3a3492021-03-10 13:58:14 +08006556 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6557 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006558 this.name = name;
6559 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006560 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006561 mDeathRecipient = deathRecipient;
6562
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006563 if (mDeathRecipient == null) {
6564 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006565 }
6566 }
6567
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006568 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006569 try {
6570 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6571 } catch (RemoteException e) {
6572 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006573 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006574 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006575 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006576
James Mattis4fce5d12020-11-12 15:53:42 -08006577 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6578 for (int i = 0; i < requests.size(); i++) {
6579 ensureNetworkRequestHasType(requests.get(i));
6580 }
6581 }
6582
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006583 private void ensureNetworkRequestHasType(NetworkRequest request) {
6584 if (request.type == NetworkRequest.Type.NONE) {
6585 throw new IllegalArgumentException(
6586 "All NetworkRequests in ConnectivityService must have a type");
6587 }
6588 }
6589
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006590 /**
6591 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006592 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006593 */
James Mattis258ea3c2020-11-15 15:04:40 -08006594 @VisibleForTesting
6595 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006596 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6597 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006598 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006599
James Mattisa076c532020-12-02 14:12:41 -08006600 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6601 void setSatisfier(
6602 @Nullable final NetworkAgentInfo satisfier,
6603 @Nullable final NetworkRequest activeRequest) {
6604 mSatisfier = satisfier;
6605 mActiveRequest = activeRequest;
6606 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006607
James Mattisd31bdfa2020-12-23 16:37:26 -08006608 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006609 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006610 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006611 private NetworkAgentInfo mSatisfier;
6612 NetworkAgentInfo getSatisfier() {
6613 return mSatisfier;
6614 }
6615
6616 // The request in mRequests assigned to a network agent. This is null if none of the
6617 // requests in mRequests can be satisfied. This member has the constraint of only being
6618 // accessible on the handler thread.
6619 @Nullable
6620 private NetworkRequest mActiveRequest;
6621 NetworkRequest getActiveRequest() {
6622 return mActiveRequest;
6623 }
6624
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006625 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006626 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006627 @Nullable
6628 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006629
6630 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006631 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006632 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006633 final int mPid;
6634 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006635 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006636 @Nullable
6637 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006638
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006639 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006640 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006641
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006642 // Effective UID of this request. This is different from mUid when a privileged process
6643 // files a request on behalf of another UID. This UID is used to determine blocked status,
6644 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6645 // maximum limit of registered callbacks per UID.
6646 final int mAsUid;
6647
paulhu48291862021-07-14 14:53:57 +08006648 // Preference order of this request.
6649 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006650
James Mattis3ce3d3c2021-02-09 18:18:28 -08006651 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6652 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6653 // maintained for keying off of. This is only a concern when the original nri
6654 // mNetworkRequests changes which happens currently for apps that register callbacks to
6655 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6656 // that match the per-app default nri that currently tracks the calling app's uid so that
6657 // callbacks are fired at the appropriate time. When the callbacks fire,
6658 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6659 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6660 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6661 @NonNull
6662 private final NetworkRequest mNetworkRequestForCallback;
6663 NetworkRequest getNetworkRequestForCallback() {
6664 return mNetworkRequestForCallback;
6665 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006666
James Mattisd31bdfa2020-12-23 16:37:26 -08006667 /**
6668 * Get the list of UIDs this nri applies to.
6669 */
6670 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006671 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006672 // networkCapabilities.getUids() returns a defensive copy.
6673 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006674 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6675 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006676 }
6677
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006678 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6679 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006680 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006681 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006682 }
6683
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006684 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006685 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006686 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006687 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006688 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006689 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006690 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006691 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006692 mBinder = null;
6693 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006694 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006695 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006696 mPerUidCounter = getRequestCounter(this);
6697 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006698 /**
6699 * Location sensitive data not included in pending intent. Only included in
6700 * {@link NetworkCallback}.
6701 */
6702 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006703 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006704 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006705 }
6706
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006707 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006708 @Nullable final IBinder binder,
6709 @NetworkCallback.Flag int callbackFlags,
6710 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006711 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
6712 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08006713 }
6714
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006715 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006716 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006717 @Nullable final IBinder binder,
6718 @NetworkCallback.Flag int callbackFlags,
6719 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006720 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006721 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006722 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006723 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006724 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006725 mBinder = binder;
6726 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006727 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006728 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006729 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006730 mPerUidCounter = getRequestCounter(this);
6731 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006732 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006733 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006734 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006735 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006736 }
6737
James Mattis3ce3d3c2021-02-09 18:18:28 -08006738 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6739 @NonNull final List<NetworkRequest> r) {
6740 super();
6741 ensureAllNetworkRequestsHaveType(r);
6742 mRequests = initializeRequests(r);
6743 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006744 final NetworkAgentInfo satisfier = nri.getSatisfier();
6745 if (null != satisfier) {
6746 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6747 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09006748 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006749 // As this code creates a new NRI with a new set of requests, figure out which of
6750 // the list of requests should be the active request. It is always the first
6751 // request of the list that can be satisfied by the satisfier since the order of
6752 // requests is a priority order.
6753 // Note even in the presence of a satisfier there may not be an active request,
6754 // when the satisfier is the no-service network.
6755 NetworkRequest activeRequest = null;
6756 for (final NetworkRequest candidate : r) {
6757 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6758 activeRequest = candidate;
6759 break;
6760 }
6761 }
6762 setSatisfier(satisfier, activeRequest);
6763 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006764 mMessenger = nri.mMessenger;
6765 mBinder = nri.mBinder;
6766 mPid = nri.mPid;
6767 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006768 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006769 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006770 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006771 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006772 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006773 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006774 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006775 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006776 }
6777
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006778 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006779 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006780 }
6781
paulhue9913722021-05-26 15:19:20 +08006782 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006783 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006784 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006785 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006786 }
6787
James Mattis2516da32021-01-31 17:06:19 -08006788 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6789 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6790 // false.
6791 boolean isBeingSatisfied() {
6792 return (null != mSatisfier && null != mActiveRequest);
6793 }
6794
James Mattis3d229892020-11-16 16:46:28 -08006795 boolean isMultilayerRequest() {
6796 return mRequests.size() > 1;
6797 }
6798
James Mattis45d81842021-01-10 14:24:24 -08006799 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6800 // Creating a defensive copy to prevent the sender from modifying the list being
6801 // reflected in the return value of this method.
6802 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006803 return Collections.unmodifiableList(tempRequests);
6804 }
6805
James Mattisb1392002021-03-31 13:57:52 -07006806 void linkDeathRecipient() {
6807 if (null != mBinder) {
6808 try {
6809 mBinder.linkToDeath(this, 0);
6810 } catch (RemoteException e) {
6811 binderDied();
6812 }
6813 }
6814 }
6815
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006816 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006817 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006818 try {
6819 mBinder.unlinkToDeath(this, 0);
6820 } catch (NoSuchElementException e) {
6821 // Temporary workaround for b/194394697 pending analysis of additional logs
6822 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6823 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006824 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006825 }
6826
paulhu48291862021-07-14 14:53:57 +08006827 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6828 // Compare two preference orders.
6829 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006830 }
6831
paulhu48291862021-07-14 14:53:57 +08006832 int getPreferenceOrderForNetd() {
6833 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6834 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6835 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006836 }
paulhu48291862021-07-14 14:53:57 +08006837 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006838 }
6839
James Mattis4fce5d12020-11-12 15:53:42 -08006840 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006841 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09006842 // As an immutable collection, mRequests cannot change by the time the
6843 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6844 // is acceptable. Use handleReleaseNetworkRequest and not directly
6845 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6846 // the app already unregistered the request.
6847 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6848 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006849 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006850
James Mattis4fce5d12020-11-12 15:53:42 -08006851 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006852 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006853 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6854 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006855 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006856 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006857 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006858 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006859 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006860 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006861 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006862 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006863 }
6864
Junyu Lai00d92df2022-07-05 11:01:52 +08006865 // Keep backward compatibility since the ServiceSpecificException is used by
6866 // the API surface, see {@link ConnectivityManager#convertServiceException}.
6867 public static class RequestInfoPerUidCounter extends PerUidCounter {
6868 RequestInfoPerUidCounter(int maxCountPerUid) {
6869 super(maxCountPerUid);
6870 }
6871
6872 @Override
6873 public synchronized void incrementCountOrThrow(int uid) {
6874 try {
6875 super.incrementCountOrThrow(uid);
6876 } catch (IllegalStateException e) {
6877 throw new ServiceSpecificException(
6878 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
6879 "Uid " + uid + " exceeded its allotted requests limit");
6880 }
6881 }
6882
6883 @Override
6884 public synchronized void decrementCountOrThrow(int uid) {
6885 throw new UnsupportedOperationException("Use decrementCount instead.");
6886 }
6887
6888 public synchronized void decrementCount(int uid) {
6889 try {
6890 super.decrementCountOrThrow(uid);
6891 } catch (IllegalStateException e) {
6892 logwtf("Exception when decrement per uid request count: ", e);
6893 }
6894 }
6895 }
6896
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006897 // This checks that the passed capabilities either do not request a
6898 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006899 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006900 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006901 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006902 throw new SecurityException("Insufficient permissions to request a specific SSID");
6903 }
paulhu1a407652019-03-22 16:35:06 +08006904
6905 if (nc.hasSignalStrength()
6906 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6907 throw new SecurityException(
6908 "Insufficient permissions to request a specific signal strength");
6909 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006910 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006911
junyulai2217bec2021-04-14 23:33:31 +08006912 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006913 enforceNetworkFactoryPermission();
6914 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006915 }
6916
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006917 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006918 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006919 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006920 // mNetworkRequests may contain the same value multiple times in case of
6921 // multilayer requests. It won't matter in this case because the thresholds
6922 // will then be the same and be deduplicated as they enter the `thresholds` set.
6923 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006924 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6925 for (final NetworkRequest req : nri.mRequests) {
6926 if (req.networkCapabilities.hasSignalStrength()
6927 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6928 thresholds.add(req.networkCapabilities.getSignalStrength());
6929 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006930 }
6931 }
6932 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006933 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006934 }
6935
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006936 private void updateSignalStrengthThresholds(
6937 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006938 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006939
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006940 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006941 String detail;
6942 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6943 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6944 } else {
6945 detail = reason;
6946 }
6947 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006948 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006949 }
6950
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006951 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006952 }
6953
Chalard Jeandd421992021-12-16 23:16:02 +09006954 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07006955 if (nc == null) {
6956 return;
6957 }
6958 NetworkSpecifier ns = nc.getNetworkSpecifier();
6959 if (ns == null) {
6960 return;
6961 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006962 if (ns instanceof MatchAllNetworkSpecifier) {
6963 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6964 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006965 }
6966
Chalard Jeandd421992021-12-16 23:16:02 +09006967 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08006968 ensureValidNetworkSpecifier(nc);
6969 if (nc.isPrivateDnsBroken()) {
6970 throw new IllegalArgumentException("Can't request broken private DNS");
6971 }
Chalard Jeande665262022-02-25 16:12:12 +09006972 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09006973 throw new IllegalArgumentException("Can't request access UIDs");
6974 }
lucasline117e2e2019-10-22 18:27:33 +08006975 }
6976
Chalard Jeandd421992021-12-16 23:16:02 +09006977 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
6978 ensureListenableCapabilities(nc);
6979 final String badCapability = nc.describeFirstNonRequestableCapability();
6980 if (badCapability != null) {
6981 throw new IllegalArgumentException("Cannot request network with " + badCapability);
6982 }
6983 }
6984
Chiachang Wang3bc52762021-11-25 14:17:57 +08006985 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6986 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006987 private boolean isTargetSdkAtleast(int version, int callingUid,
6988 @NonNull String callingPackageName) {
6989 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006990 final PackageManager pm =
6991 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006992 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006993 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006994 if (callingVersion < version) return false;
6995 } catch (PackageManager.NameNotFoundException e) { }
6996 return true;
6997 }
6998
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006999 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007000 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007001 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007002 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007003 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08007004 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007005 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7006 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007007 throw new SecurityException("Insufficient permissions to specify legacy type");
7008 }
markchienfac84a22020-03-18 21:16:15 +08007009 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007010 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007011 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007012 // Privileged callers can track the default network of another UID by passing in a UID.
7013 if (asUid != Process.INVALID_UID) {
7014 enforceSettingsPermission();
7015 } else {
7016 asUid = callingUid;
7017 }
junyulaiad010792021-01-11 16:53:38 +08007018 final NetworkRequest.Type reqType;
7019 try {
7020 reqType = NetworkRequest.Type.values()[reqTypeInt];
7021 } catch (ArrayIndexOutOfBoundsException e) {
7022 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7023 }
7024 switch (reqType) {
7025 case TRACK_DEFAULT:
7026 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007027 // is unused and will be replaced by ones appropriate for the UID (usually, the
7028 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007029 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007030 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007031 enforceAccessPermission();
7032 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007033 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007034 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007035 networkCapabilities = new NetworkCapabilities(defaultNc);
7036 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007037 case BACKGROUND_REQUEST:
7038 enforceNetworkStackOrSettingsPermission();
7039 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007040 case REQUEST:
7041 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7042 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007043 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007044 // TODO: this is incorrect. We mark the request as metered or not depending on
7045 // the state of the app when the request is filed, but we never change the
7046 // request if the app changes network state. http://b/29964605
7047 enforceMeteredApnPolicy(networkCapabilities);
7048 break;
junyulai1b1c8742021-03-12 20:05:08 +08007049 case LISTEN_FOR_BEST:
7050 enforceAccessPermission();
7051 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7052 break;
junyulaiad010792021-01-11 16:53:38 +08007053 default:
7054 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007055 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007056 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007057 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007058 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007059
junyulai1b1c8742021-03-12 20:05:08 +08007060 // Enforce FOREGROUND if the caller does not have permission to use background network.
7061 if (reqType == LISTEN_FOR_BEST) {
7062 restrictBackgroundRequestForCaller(networkCapabilities);
7063 }
7064
7065 // Set the UID range for this request to the single UID of the requester, unless the
7066 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007067 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7068 // are no visible methods to set the UIDs, an app could use reflection to try and get
7069 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007070 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007071 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7072 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007073
Etan Cohen85000162017-02-05 10:42:27 -08007074 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007075 throw new IllegalArgumentException("Bad timeout specified");
7076 }
Etan Cohen9786d922015-11-18 10:56:15 -08007077
James Mattis3ce3d3c2021-02-09 18:18:28 -08007078 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007079 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007080 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007081 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007082 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007083 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007084
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007085 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7086 // copied from the default request above. (This is necessary to ensure, for example, that
7087 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7088 // changes don't alter request matching.
7089 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7090 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007091 throw new IllegalStateException(
7092 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007093 + networkCapabilities + " vs. " + defaultNc);
7094 }
7095
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007096 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007097 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007098 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007099 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007100 }
7101 return networkRequest;
7102 }
7103
James Mattis3ce3d3c2021-02-09 18:18:28 -08007104 /**
7105 * Return the nri to be used when registering a network request. Specifically, this is used with
7106 * requests registered to track the default request. If there is currently a per-app default
7107 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7108 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007109 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7110 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007111 * @param nr the network request for the nri.
7112 * @param msgr the messenger for the nri.
7113 * @param binder the binder for the nri.
7114 * @param callingAttributionTag the calling attribution tag for the nri.
7115 * @return the nri to register.
7116 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007117 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007118 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007119 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007120 @Nullable String callingAttributionTag) {
7121 final List<NetworkRequest> requests;
7122 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7123 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007124 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007125 } else {
7126 requests = Collections.singletonList(nr);
7127 }
Roshan Pius951c0032020-12-22 15:10:42 -08007128 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007129 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007130 }
7131
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007132 private boolean shouldCheckCapabilitiesDeclaration(
7133 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7134 @NonNull final String callingPackageName) {
7135 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7136 // Only run the check if the change is enabled.
7137 if (!mDeps.isChangeEnabled(
7138 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7139 callingPackageName, user)) {
7140 return false;
7141 }
7142
7143 return networkCapabilities.hasCapability(
7144 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7145 || networkCapabilities.hasCapability(
7146 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7147 }
7148
7149 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
7150 @NonNull final NetworkCapabilities networkCapabilities) {
7151 // This check is added to fix the linter error for "current min is 30", which is not going
7152 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007153 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007154 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7155 return;
7156 }
7157 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007158 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007159 try {
7160 synchronized (mSelfCertifiedCapabilityCache) {
7161 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7162 callerPackageName);
7163 if (applicationNetworkCapabilities == null) {
7164 final PackageManager packageManager = mContext.getPackageManager();
7165 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7166 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7167 callerPackageName
7168 );
7169 final XmlResourceParser parser = packageManager
7170 .getResourcesForApplication(callerPackageName)
7171 .getXml(networkSliceProperty.getResourceId());
7172 applicationNetworkCapabilities =
7173 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7174 mSelfCertifiedCapabilityCache.put(callerPackageName,
7175 applicationNetworkCapabilities);
7176 }
7177
7178 }
7179 } catch (PackageManager.NameNotFoundException ne) {
7180 throw new SecurityException(
7181 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7182 + " property");
7183 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7184 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007185 } finally {
7186 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007187 }
7188
7189 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7190 networkCapabilities);
7191 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007192 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007193 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007194 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7195 callingPackageName)) {
7196 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities);
7197 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007198 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007199 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7200 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7201 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7202 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007203 }
junyulai96bd9fe2022-03-08 17:36:42 +08007204 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007205 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007206 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007207 }
7208 }
7209
fenglu3f357402015-03-20 11:29:56 -07007210 @Override
fenglub00f4882015-04-21 17:12:05 -07007211 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007212 enforceAccessPermission();
7213 NetworkAgentInfo nai = null;
7214 if (network == null) {
7215 return false;
7216 }
7217 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007218 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007219 }
7220 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007221 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007222 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007223 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007224 Integer uidReqs = mBandwidthRequests.get(uid);
7225 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007226 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007227 }
7228 mBandwidthRequests.put(uid, ++uidReqs);
7229 }
fenglu3f357402015-03-20 11:29:56 -07007230 return true;
7231 }
7232 return false;
7233 }
7234
Felipe Leme0a5ae422016-06-20 16:36:29 -07007235 private boolean isSystem(int uid) {
7236 return uid < Process.FIRST_APPLICATION_UID;
7237 }
fenglu3f357402015-03-20 11:29:56 -07007238
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007239 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007240 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007241 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007242 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007243 return;
7244 }
Hugo Benichi39621362017-02-11 17:04:43 +09007245 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7246 // Policy already enforced.
7247 return;
7248 }
paulhuaf50d7d2020-12-24 19:47:34 +08007249 final long ident = Binder.clearCallingIdentity();
7250 try {
7251 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7252 // If UID is restricted, don't allow them to bring up metered APNs.
7253 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7254 }
7255 } finally {
7256 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007257 }
7258 }
7259
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007260 @Override
7261 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007262 PendingIntent operation, @NonNull String callingPackageName,
7263 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007264 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007265 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007266 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007267 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007268 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007269 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007270 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007271 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007272 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007273 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7274 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007275
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007276 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007277 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007278 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7279 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007280 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007281 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7282 nri));
7283 return networkRequest;
7284 }
7285
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007286 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7287 mHandler.sendMessageDelayed(
7288 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007289 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007290 }
7291
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007292 @Override
7293 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007294 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007295 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007296 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007297 }
7298
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007299 // In order to implement the compatibility measure for pre-M apps that call
7300 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7301 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7302 // This ensures it has permission to do so.
7303 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7304 if (nc == null) {
7305 return false;
7306 }
7307 int[] transportTypes = nc.getTransportTypes();
7308 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7309 return false;
7310 }
7311 try {
7312 mContext.enforceCallingOrSelfPermission(
7313 android.Manifest.permission.ACCESS_WIFI_STATE,
7314 "ConnectivityService");
7315 } catch (SecurityException e) {
7316 return false;
7317 }
7318 return true;
7319 }
7320
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007321 @Override
7322 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007323 Messenger messenger, IBinder binder,
7324 @NetworkCallback.Flag int callbackFlags,
7325 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007326 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007327 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7328 enforceAccessPermission();
7329 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007330
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007331 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007332 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007333 Binder.getCallingPid(), callingUid, callingPackageName);
7334 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007335 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7336 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7337 // onLost and onAvailable callbacks when networks move in and out of the background.
7338 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7339 // can't request networks.
7340 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007341 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007342
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007343 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007344 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007345 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007346 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007347 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007348 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007349
7350 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7351 return networkRequest;
7352 }
7353
7354 @Override
7355 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007356 PendingIntent operation, @NonNull String callingPackageName,
7357 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007358 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007359 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007360 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7361 enforceAccessPermission();
7362 }
Chalard Jeandd421992021-12-16 23:16:02 +09007363 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007364 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007365 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007366 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007367 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007368
7369 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007370 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007371 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7372 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007373 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007374
WeiZhang1cc3f172021-06-03 19:02:04 -05007375 mHandler.sendMessage(mHandler.obtainMessage(
7376 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007377 }
7378
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007379 /** Returns the next Network provider ID. */
7380 public final int nextNetworkProviderId() {
7381 return mNextNetworkProviderId.getAndIncrement();
7382 }
7383
Erik Kline0c04b742016-07-07 16:50:58 +09007384 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007385 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007386 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007387 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007388 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007389 }
7390
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007391 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7392 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007393 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7394 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7395 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007396 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007397 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007398 return;
7399 }
7400
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007401 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7402 mNetworkProviderInfos.put(npi.messenger, npi);
7403 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007404 }
7405
7406 @Override
7407 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007408 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007409 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007410 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007411 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007412 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7413 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007414 }
7415
7416 @Override
7417 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007418 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007419 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007420 }
7421
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007422 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007423 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007424 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7425 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007426 Objects.requireNonNull(score);
7427 Objects.requireNonNull(caps);
7428 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007429 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007430 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007431 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7432 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007433 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7434 }
7435
Chalard Jeanbb902a52021-08-18 01:35:19 +09007436 private void updateOfferScore(final NetworkOffer offer) {
7437 final boolean yieldToBadWiFi =
7438 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7439 final NetworkOffer newOffer = new NetworkOffer(
7440 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7441 offer.caps, offer.callback, offer.providerId);
7442 if (offer.equals(newOffer)) return;
7443 handleRegisterNetworkOffer(newOffer);
7444 }
7445
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007446 @Override
7447 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007448 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007449 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7450 }
7451
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007452 private void handleUnregisterNetworkProvider(Messenger messenger) {
7453 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7454 if (npi == null) {
7455 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007456 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007457 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007458 // Unregister all the offers from this provider
7459 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7460 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007461 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007462 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7463 toRemove.add(noi);
7464 }
7465 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007466 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007467 handleUnregisterNetworkOffer(noi);
7468 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007469 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007470 }
7471
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007472 @Override
James Mattisf7027322020-12-13 16:28:14 -08007473 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007474 if (request.hasTransport(TRANSPORT_TEST)) {
7475 enforceNetworkFactoryOrTestNetworksPermission();
7476 } else {
7477 enforceNetworkFactoryPermission();
7478 }
James Mattisf7027322020-12-13 16:28:14 -08007479 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7480 if (nri != null) {
7481 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7482 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7483 mHandler.post(() -> handleReleaseNetworkRequest(
7484 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7485 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007486 }
7487
Paul Jensen1f567382015-02-13 14:18:39 -05007488 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7489 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007490 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007491 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007492 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007493 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007494 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007495
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007496 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007497 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007498 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007499
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007500 // UID ranges for users that are currently blocked by VPNs.
7501 // This array is accessed and iterated on multiple threads without holding locks, so its
7502 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7503 // (on the handler thread).
7504 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7505
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007506 // Must only be accessed on the handler thread
7507 @NonNull
7508 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7509
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007510 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007511 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007512
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007513 // Current OEM network preferences. This object must only be written to on the handler thread.
7514 // Since it is immutable and always non-null, other threads may read it if they only care
7515 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007516 @NonNull
7517 private OemNetworkPreferences mOemNetworkPreferences =
7518 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007519 // Current per-profile network preferences. This object follows the same threading rules as
7520 // the OEM network preferences above.
7521 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007522 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7523 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007524
lucaslin3ba7cc22022-12-19 02:35:33 +00007525 // Current VPN network preferences. This object follows the same threading rules as the OEM
7526 // network preferences above.
7527 @NonNull
7528 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7529 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7530
paulhu51f77dc2021-06-07 02:34:20 +00007531 // A set of UIDs that should use mobile data preferentially if available. This object follows
7532 // the same threading rules as the OEM network preferences above.
7533 @NonNull
7534 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7535
James Mattiscb1e0362021-04-06 17:07:42 -07007536 // OemNetworkPreferences activity String log entries.
7537 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7538 @NonNull
7539 private final LocalLog mOemNetworkPreferencesLogs =
7540 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7541
James Mattis02220e22021-03-13 19:27:21 -08007542 /**
7543 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7544 * @param packageName the package name to check existence of a mapping for.
7545 * @return true if a mapping exists, false otherwise
7546 */
7547 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7548 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7549 }
7550
James Mattise3ef1912020-12-20 11:09:58 -08007551 // The always-on request for an Internet-capable network that apps without a specific default
7552 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007553 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007554 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007555 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007556 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007557 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007558 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007559 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007560
James Mattisd31bdfa2020-12-23 16:37:26 -08007561 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7562 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7563 }
7564
7565 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007566 * Return the default network request currently tracking the given uid.
7567 * @param uid the uid to check.
7568 * @return the NetworkRequestInfo tracking the given uid.
7569 */
7570 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007571 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007572 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007573 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007574 // Checking the first request is sufficient as only multilayer requests will have more
7575 // than one request and for multilayer, all requests will track the same uids.
7576 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007577 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007578 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007579 highestPriorityNri = nri;
7580 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007581 }
7582 }
paulhuaa0743d2021-05-26 21:56:03 +08007583 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007584 }
7585
7586 /**
7587 * Get a copy of the network requests of the default request that is currently tracking the
7588 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007589 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7590 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007591 * @param requestorUid the uid to check the default for.
7592 * @param requestorPackageName the requestor's package name.
7593 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7594 */
7595 @NonNull
7596 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007597 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007598 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007599 getDefaultRequestTrackingUid(asUid).mRequests,
7600 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007601 }
7602
7603 /**
7604 * Copy the given nri's NetworkRequest collection.
7605 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007606 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7607 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007608 * @param requestorUid the uid to set on the copied collection.
7609 * @param requestorPackageName the package name to set on the copied collection.
7610 * @return the copied NetworkRequest collection.
7611 */
7612 @NonNull
7613 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007614 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7615 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007616 final List<NetworkRequest> requests = new ArrayList<>();
7617 for (final NetworkRequest nr : requestsToCopy) {
7618 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007619 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007620 nr.legacyType, nextNetworkRequestId(), nr.type));
7621 }
7622 return requests;
7623 }
7624
7625 @NonNull
7626 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007627 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7628 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007629 // These capabilities are for a TRACK_DEFAULT callback, so:
7630 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7631 // mDefaultRequest and a per-UID default request.
7632 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007633 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007634 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007635 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7636 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007637 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007638 restrictRequestUidsForCallerAndSetRequestorInfo(
7639 netCap, requestorUid, requestorPackageName);
7640 return netCap;
7641 }
7642
7643 /**
7644 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7645 * @param nr the network request to check for equality against.
7646 * @return the nri if one exists, null otherwise.
7647 */
7648 @Nullable
7649 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7650 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7651 if (nri.getNetworkRequestForCallback().equals(nr)) {
7652 return nri;
7653 }
7654 }
7655 return null;
7656 }
7657
7658 /**
7659 * Check if an nri is currently being managed by per-app default networking.
7660 * @param nri the nri to check.
7661 * @return true if this nri is currently being managed by per-app default networking.
7662 */
7663 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7664 // nri.mRequests.get(0) is only different from the original request filed in
7665 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7666 // functionality therefore if these two don't match, it means this particular nri is
7667 // currently being managed by a per-app default.
7668 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7669 }
7670
7671 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007672 * Determine if an nri is a managed default request that disallows default networking.
7673 * @param nri the request to evaluate
7674 * @return true if device-default networking is disallowed
7675 */
7676 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7677 // Check if this nri is a managed default that supports the default network at its
7678 // lowest priority request.
7679 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7680 final NetworkCapabilities lowestPriorityNetCap =
7681 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7682 return isPerAppDefaultRequest(nri)
7683 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7684 lowestPriorityNetCap));
7685 }
7686
Erik Kline05f2b402015-04-30 12:58:40 +09007687 // Request used to optionally keep mobile data active even when higher
7688 // priority networks like Wi-Fi are active.
7689 private final NetworkRequest mDefaultMobileDataRequest;
7690
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007691 // Request used to optionally keep wifi data active even when higher
7692 // priority networks like ethernet are active.
7693 private final NetworkRequest mDefaultWifiRequest;
7694
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007695 // Request used to optionally keep vehicle internal network always active
7696 private final NetworkRequest mDefaultVehicleRequest;
7697
James Mattisd31bdfa2020-12-23 16:37:26 -08007698 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7699 // network with no service. This NAI should never be matched against, nor should any public API
7700 // ever return the associated network. For this reason, this NAI is not in the list of available
7701 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7702 // default requests that don't support using the device default network which will ultimately
7703 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7704 @VisibleForTesting
7705 final NetworkAgentInfo mNoServiceNetwork;
7706
Chalard Jean5b409c72021-02-04 13:12:59 +09007707 // The NetworkAgentInfo currently satisfying the default request, if any.
7708 private NetworkAgentInfo getDefaultNetwork() {
7709 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09007710 }
7711
James Mattis2516da32021-01-31 17:06:19 -08007712 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007713 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08007714 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7715 // Currently, all network requests will have the same uids therefore checking the first
7716 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007717 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08007718 if (null == uids) {
7719 continue;
7720 }
7721 for (final UidRange range : uids) {
7722 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08007723 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007724 highestPriorityNri = nri;
7725 }
James Mattis2516da32021-01-31 17:06:19 -08007726 }
7727 }
7728 }
paulhuaa0743d2021-05-26 21:56:03 +08007729 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08007730 }
7731
Varun Ananddf569952019-02-06 10:13:38 -08007732 @Nullable
7733 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
7734 return nai != null ? nai.network : null;
7735 }
7736
7737 private void ensureRunningOnConnectivityServiceThread() {
7738 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
7739 throw new IllegalStateException(
7740 "Not running on ConnectivityService thread: "
7741 + Thread.currentThread().getName());
7742 }
7743 }
7744
Chalard Jean3a3f5f22019-04-10 23:07:55 +09007745 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09007746 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
7747 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007748 }
7749
Chalard Jean29d06db2018-05-02 21:14:54 +09007750 /**
7751 * Register a new agent with ConnectivityService to handle a network.
7752 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007753 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09007754 * @param networkInfo the initial info associated with this network. It can be updated later :
7755 * see {@link #updateNetworkInfo}.
7756 * @param linkProperties the initial link properties of this network. They can be updated
7757 * later : see {@link #updateLinkProperties}.
7758 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007759 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007760 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007761 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007762 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007763 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007764 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007765 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007766 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007767 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7768 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007769 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7770 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7771 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007772 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007773 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007774 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08007775 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007776 } else {
7777 enforceNetworkFactoryPermission();
7778 }
7779
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007780 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007781 final long token = Binder.clearCallingIdentity();
7782 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007783 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007784 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007785 } finally {
7786 Binder.restoreCallingIdentity(token);
7787 }
7788 }
7789
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007790 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007791 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007792 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7793 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007794
Chalard Jeandbc46952022-02-02 00:14:18 +09007795 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
7796 // and mutate them at any time.
7797 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
7798 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
7799 final LinkProperties lpCopy = new LinkProperties(linkProperties);
7800
Chalard Jean366c5252022-01-25 18:27:53 +09007801 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09007802 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09007803 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7804 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007805 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09007806 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007807 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007808 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7809 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007810
Chalard Jeandbc46952022-02-02 00:14:18 +09007811 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09007812 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007813 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007814 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007815 mDeps.getNetworkStack().makeNetworkMonitor(
7816 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007817 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7818 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007819 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007820 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007821 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007822 }
7823
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007824 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007825 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007826 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09007827 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007828 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09007829 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
7830 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
7831 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09007832
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007833 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007834
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007835 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007836 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007837 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007838 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007839
7840 try {
7841 networkMonitor.start();
7842 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007843 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007844 }
Chalard Jean366c5252022-01-25 18:27:53 +09007845
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007846 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007847 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007848 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007849 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007850 }
7851
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007852 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7853 @NonNull public final NetworkOffer offer;
7854
7855 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7856 this.offer = offer;
7857 }
7858
7859 @Override
7860 public void binderDied() {
7861 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7862 }
7863 }
7864
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007865 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7866 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7867 if (npi.providerId == providerId) return true;
7868 }
7869 return false;
7870 }
7871
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007872 /**
7873 * Register or update a network offer.
7874 * @param newOffer The new offer. If the callback member is the same as an existing
7875 * offer, it is an update of that offer.
7876 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007877 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007878 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7879 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007880 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007881 // This may actually happen if a provider updates its score or registers and then
7882 // immediately unregisters. The offer would still be in the handler queue, but the
7883 // provider would have been removed.
7884 if (DBG) log("Received offer from an unregistered provider");
7885 return;
7886 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007887 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7888 if (null != existingOffer) {
7889 handleUnregisterNetworkOffer(existingOffer);
7890 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007891 if (DBG) {
7892 // handleUnregisterNetworkOffer has already logged the old offer
7893 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7894 }
7895 } else {
7896 if (DBG) {
7897 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7898 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007899 }
7900 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7901 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007902 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007903 } catch (RemoteException e) {
7904 noi.binderDied();
7905 return;
7906 }
7907 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007908 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007909 }
7910
7911 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7912 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007913 if (DBG) {
7914 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7915 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007916
7917 // If the provider removes the offer and dies immediately afterwards this
7918 // function may be called twice in a row, but the array will no longer contain
7919 // the offer.
7920 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007921 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007922 }
7923
7924 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7925 @NonNull final INetworkOfferCallback callback) {
7926 ensureRunningOnConnectivityServiceThread();
7927 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007928 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007929 }
7930 return null;
7931 }
7932
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007933 /**
7934 * Called when receiving LinkProperties directly from a NetworkAgent.
7935 * Stores into |nai| any data coming from the agent that might also be written to the network's
7936 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7937 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007938 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007939 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007940 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7941 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007942 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007943 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007944 }
7945
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007946 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08007947 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007948 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007949
Lorenzo Colittid523d142020-04-01 20:16:30 +09007950 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7951 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7952 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007953 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007954
Suprabh Shukla1e312032023-01-24 03:36:37 -08007955 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007956
7957 // update filtering rules, need to happen after the interface update so netd knows about the
7958 // new interface (the interface name -> index map becomes initialized)
7959 updateVpnFiltering(newLp, oldLp, networkAgent);
7960
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007961 updateMtu(newLp, oldLp);
7962 // TODO - figure out what to do for clat
7963// for (LinkProperties lp : newLp.getStackedLinks()) {
7964// updateMtu(lp, null);
7965// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007966 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007967 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7968 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007969
Erik Klineb9888902016-04-05 13:30:49 +09007970 updateRoutes(newLp, oldLp, netId);
7971 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007972 // Make sure LinkProperties represents the latest private DNS status.
7973 // This does not need to be done before updateDnses because the
7974 // LinkProperties are not the source of the private DNS configuration.
7975 // updateDnses will fetch the private DNS configuration from DnsManager.
7976 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007977
Chalard Jean5b409c72021-02-04 13:12:59 +09007978 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007979 handleApplyDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09007980 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007981 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007982 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007983
7984 updateWakeOnLan(newLp);
7985
Hai Shalome58bdc62021-01-11 18:45:34 -08007986 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7987 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7988 // does, it needs to be merged here.
7989 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7990 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007991
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007992 // TODO - move this check to cover the whole function
7993 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007994 synchronized (networkAgent) {
7995 networkAgent.linkProperties = newLp;
7996 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007997 // Start or stop DNS64 detection and 464xlat according to network state.
7998 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08007999 // Notify NSS when relevant events happened. Currently, NSS only cares about
8000 // interface changed to update clat interfaces accounting.
8001 final boolean interfacesChanged = oldLp == null
8002 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8003 if (interfacesChanged) {
8004 notifyIfacesChangedForNetworkStats();
8005 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008006 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8007 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008008 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008009 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008010
8011 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008012 }
8013
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008014 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8015 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8016 }
8017
Hai Shalome58bdc62021-01-11 18:45:34 -08008018 /**
8019 * @param naData captive portal data from NetworkAgent
8020 * @param apiData captive portal data from capport API
8021 */
8022 @Nullable
8023 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8024 CaptivePortalData apiData) {
8025 if (naData == null || apiData == null) {
8026 return naData == null ? apiData : naData;
8027 }
8028 final CaptivePortalData.Builder captivePortalBuilder =
8029 new CaptivePortalData.Builder(naData);
8030
8031 if (apiData.isCaptive()) {
8032 captivePortalBuilder.setCaptive(true);
8033 }
8034 if (apiData.isSessionExtendable()) {
8035 captivePortalBuilder.setSessionExtendable(true);
8036 }
8037 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8038 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8039 // otherwise data would be inconsistent. Prefer the capport API info if present,
8040 // as it can generally be refreshed more often.
8041 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8042 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8043 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8044 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8045 // No source has time / bytes remaining information: surface the newest refresh time
8046 // for other fields
8047 captivePortalBuilder.setRefreshTime(
8048 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8049 }
8050
Hai Shalom7c6ab402021-02-04 19:34:06 -08008051 // Prioritize the user portal URL from the network agent if the source is authenticated.
8052 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8053 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8054 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8055 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008056 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008057 // Prioritize the venue information URL from the network agent if the source is
8058 // authenticated.
8059 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8060 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8061 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8062 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008063 }
8064 return captivePortalBuilder.build();
8065 }
8066
Suprabh Shukla53e16392023-04-26 18:47:36 -07008067 @VisibleForTesting
8068 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008069 // This needs to be kept in sync and backwards compatible with the decoding logic in
8070 // NetdEventListenerService, which is non-mainline code.
8071 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8072 }
8073
Suprabh Shukla75642282023-04-25 23:15:43 -07008074 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8075 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8076 return true;
8077 }
8078 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8079 return true;
8080 }
8081 return false;
8082 }
8083
Suprabh Shukla1e312032023-01-24 03:36:37 -08008084 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008085 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008086 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008087 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008088 return;
8089 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008090
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008091 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
8092 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
8093
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008094 // Mask/mark of zero will not detect anything interesting.
8095 // Don't install rules unless both values are nonzero.
8096 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008097 return;
8098 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008099
Suprabh Shukla1e312032023-01-24 03:36:37 -08008100 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008101 try {
8102 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08008103 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008104 } else {
Luke Huang46289a22018-09-27 19:33:11 +08008105 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008106 }
8107 } catch (Exception e) {
8108 loge("Exception modifying wakeup packet monitoring: " + e);
8109 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008110 }
8111
Junyu Lai970963e2022-10-25 15:46:47 +08008112 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008113 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008114 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008115 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008116 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008117 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008118 for (final String iface : interfaceDiff.added) {
8119 try {
8120 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008121 mNetd.networkAddInterface(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008122 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008123 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008124 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008125 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008126 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008127 }
Paul Jensenbff73492014-04-28 10:33:11 -04008128 }
8129 }
Chalard Jean9589e722019-11-19 19:03:53 +09008130 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008131 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008132 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008133 wakeupModifyInterface(iface, nai, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008134 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008135 } catch (Exception e) {
8136 loge("Exception removing interface: " + e);
8137 }
8138 }
8139 }
8140
Tyler Weare4314862019-12-05 14:55:30 -08008141 // TODO: move to frameworks/libs/net.
8142 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
8143 final String nextHop;
8144
8145 switch (route.getType()) {
8146 case RouteInfo.RTN_UNICAST:
8147 if (route.hasGateway()) {
8148 nextHop = route.getGateway().getHostAddress();
8149 } else {
8150 nextHop = INetd.NEXTHOP_NONE;
8151 }
8152 break;
8153 case RouteInfo.RTN_UNREACHABLE:
8154 nextHop = INetd.NEXTHOP_UNREACHABLE;
8155 break;
8156 case RouteInfo.RTN_THROW:
8157 nextHop = INetd.NEXTHOP_THROW;
8158 break;
8159 default:
8160 nextHop = INetd.NEXTHOP_NONE;
8161 break;
8162 }
8163
8164 final RouteInfoParcel rip = new RouteInfoParcel();
8165 rip.ifName = route.getInterface();
8166 rip.destination = route.getDestination().toString();
8167 rip.nextHop = nextHop;
8168 rip.mtu = route.getMtu();
8169
8170 return rip;
8171 }
8172
Paul Jensene0fd4a82014-08-06 15:51:33 -04008173 /**
8174 * Have netd update routes from oldLp to newLp.
8175 * @return true if routes changed between oldLp and newLp
8176 */
Junyu Lai970963e2022-10-25 15:46:47 +08008177 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8178 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008179 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008180 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8181 new CompareOrUpdateResult<>(
8182 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008183 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008184 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008185
8186 // add routes before removing old in case it helps with continuous connectivity
8187
Chalard Jean9dd11612018-06-04 16:52:49 +09008188 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008189 for (RouteInfo route : routeDiff.added) {
8190 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008191 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008192 try {
Tyler Weare4314862019-12-05 14:55:30 -08008193 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008194 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008195 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008196 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008197 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008198 }
8199 }
8200 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008201 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008202 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008203 try {
Tyler Weare4314862019-12-05 14:55:30 -08008204 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008205 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008206 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008207 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008208 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008209 }
8210 }
8211
8212 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008213 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008214 try {
Tyler Weare4314862019-12-05 14:55:30 -08008215 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008216 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08008217 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008218 }
8219 }
Tyler Weare4314862019-12-05 14:55:30 -08008220
8221 for (RouteInfo route : routeDiff.updated) {
8222 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8223 try {
8224 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
8225 } catch (Exception e) {
8226 loge("Exception in networkUpdateRouteParcel: " + e);
8227 }
8228 }
8229 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8230 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008231 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008232
Junyu Lai970963e2022-10-25 15:46:47 +08008233 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8234 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008235 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8236 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008237 }
Erik Klineb9888902016-04-05 13:30:49 +09008238
Erik Kline31b4a9e2018-01-11 21:07:29 +09008239 if (DBG) {
8240 final Collection<InetAddress> dnses = newLp.getDnsServers();
8241 log("Setting DNS servers for network " + netId + " to " + dnses);
8242 }
Erik Klineb9888902016-04-05 13:30:49 +09008243 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008244 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008245 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008246 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008247 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008248 }
Erik Kline54e35c02017-04-07 15:29:29 +09008249 }
8250
Junyu Lai970963e2022-10-25 15:46:47 +08008251 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8252 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008253 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8254 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008255 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8256 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008257
8258 if (!wasFiltering && !needsFiltering) {
8259 // Nothing to do.
8260 return;
8261 }
8262
8263 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8264 // Nothing changed.
8265 return;
8266 }
8267
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008268 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008269 if (ranges == null || ranges.isEmpty()) {
8270 return;
8271 }
8272
Qingxi Libb8da982020-01-17 17:54:27 -08008273 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008274 // TODO: this create a window of opportunity for apps to receive traffic between the time
8275 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008276 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008277 // old rules are being removed.
8278 if (wasFiltering) {
8279 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8280 }
8281 if (needsFiltering) {
8282 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8283 }
8284 }
8285
Valentin Iftime9fa35092019-09-24 13:32:13 +02008286 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008287 if (mWolSupportedInterfaces == null) {
8288 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008289 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008290 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008291 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8292 }
8293
Luke Huangb913c812018-08-24 20:33:16 +08008294 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008295 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008296 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008297 }
8298 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008299 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008300 }
Luke Huangb913c812018-08-24 20:33:16 +08008301 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008302 }
8303
Chalard Jean62edfd82019-12-02 18:39:29 +09008304 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8305 @NonNull final NetworkCapabilities newNc) {
8306 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8307 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008308 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008309 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008310 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008311 } catch (RemoteException | ServiceSpecificException e) {
8312 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008313 }
8314 }
8315 }
8316
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008317 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008318 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008319 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008320 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008321 underlyingNetworks = underlyingNetworksOrDefault(
8322 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008323 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008324 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8325 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008326 // metered if any underlying is metered, or originally declared metered by the agent.
8327 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008328 boolean roaming = false; // roaming if any underlying is roaming
8329 boolean congested = false; // congested if any underlying is congested
8330 boolean suspended = true; // suspended if all underlying are suspended
8331
8332 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008333 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008334 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008335 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008336 for (Network underlyingNetwork : underlyingNetworks) {
8337 final NetworkAgentInfo underlying =
8338 getNetworkAgentInfoForNetwork(underlyingNetwork);
8339 if (underlying == null) continue;
8340
8341 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8342 hadUnderlyingNetworks = true;
8343 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008344 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008345 }
8346
8347 // Merge capabilities of this underlying network. For bandwidth, assume the
8348 // worst case.
8349 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8350 underlyingCaps.getLinkDownstreamBandwidthKbps());
8351 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8352 underlyingCaps.getLinkUpstreamBandwidthKbps());
8353 // If this underlying network is metered, the VPN is metered (it may cost money
8354 // to send packets on this network).
8355 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8356 // If this underlying network is roaming, the VPN is roaming (the billing structure
8357 // is different than the usual, local one).
8358 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8359 // If this underlying network is congested, the VPN is congested (the current
8360 // condition of the network affects the performance of this network).
8361 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8362 // If this network is not suspended, the VPN is not suspended (the VPN
8363 // is able to transfer some data).
8364 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008365 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008366 }
8367 }
8368 if (!hadUnderlyingNetworks) {
8369 // No idea what the underlying networks are; assume reasonable defaults
8370 metered = true;
8371 roaming = false;
8372 congested = false;
8373 suspended = false;
8374 }
8375
Chalard Jean1d420b32022-10-12 16:39:37 +09008376 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008377 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8378 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8379 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8380 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8381 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8382 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008383 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008384 }
8385
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008386 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008387 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8388 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8389 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008390 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008391 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008392 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008393 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008394 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8395 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008396 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008397 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008398 if (nai.everConnected()
8399 && !nai.isVPN()
8400 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008401 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008402 // does not cause any request (that is not a listen) currently matching that agent to
8403 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008404 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008405 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008406 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008407 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008408 }
8409
Paul Jensen53f08952015-06-16 14:27:36 -04008410 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008411 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008412 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008413 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008414 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008415 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008416 }
Chalard Jean254bd162022-08-25 13:04:51 +09008417 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008418 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008419 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008420 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008421 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008422 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008423 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008424 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008425 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008426 }
Chalard Jean254bd162022-08-25 13:04:51 +09008427 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008428 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8429 } else {
8430 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8431 }
lucasline117e2e2019-10-22 18:27:33 +08008432 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008433
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008434 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008435 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8436 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008437 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008438 }
8439
Lorenzo Colittibd079452021-07-02 11:47:57 +09008440 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008441 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008442 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008443 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008444 }
8445
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008446 return newNc;
8447 }
8448
Lorenzo Colitti44840702021-01-11 22:27:57 +09008449 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8450 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8451 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8452 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8453 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8454 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8455 if (prevSuspended != suspended) {
8456 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8457 // onResumed have been removed.
8458 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8459 : ConnectivityManager.CALLBACK_RESUMED);
8460 }
8461 if (prevSuspended != suspended || prevRoaming != roaming) {
8462 // updateNetworkInfo will mix in the suspended info from the capabilities and
8463 // take appropriate action for the network having possibly changed state.
8464 updateNetworkInfo(nai, nai.networkInfo);
8465 }
8466 }
8467
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008468 /**
8469 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8470 *
8471 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8472 * capabilities we manage and store in {@code nai}, such as validated status and captive
8473 * portal status)
8474 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8475 * potentially triggers rematches.
8476 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8477 * change.)
8478 *
8479 * @param oldScore score of the network before any of the changes that prompted us
8480 * to call this function.
8481 * @param nai the network having its capabilities updated.
8482 * @param nc the new network capabilities.
8483 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008484 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008485 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008486 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008487 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008488 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8489 if (null != differences) {
8490 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8491 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008492 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008493 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008494
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008495 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008496 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008497 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008498
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008499 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008500 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8501 // the change we're processing can't affect any requests, it can only affect the listens
8502 // on this network. We might have been called by rematchNetworkAndRequests when a
8503 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008504 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008505 } else {
8506 // If the requestable capabilities have changed or the score changed, we can't have been
8507 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008508 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008509 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008510 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008511 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008512
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008513 final boolean oldMetered = prevNc.isMetered();
8514 final boolean newMetered = newNc.isMetered();
8515 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008516
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008517 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008518 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8519 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008520 }
junyulaif2c67e42018-08-07 19:50:45 +08008521
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008522 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8523 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008524
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008525 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008526 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008527 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008528 }
8529
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008530 // This network might have been underlying another network. Propagate its capabilities.
8531 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008532
8533 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008534 mDnsManager.updateTransportsForNetwork(
8535 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008536 }
lucaslin53e8a262021-06-08 01:43:59 +08008537
8538 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008539 }
8540
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008541 /** Convenience method to update the capabilities for a given network. */
8542 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008543 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008544 }
8545
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008546 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008547 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008548 *
8549 * Ingress interface filtering enforces that all apps under the given network can only receive
8550 * packets from the network's interface (and loopback). This is important for VPNs because
8551 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8552 * non-VPN interfaces.
8553 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008554 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008555 * 1. the network is an app VPN (not legacy VPN)
8556 * 2. the VPN does not allow bypass
8557 * 3. the VPN is fully-routed
8558 * 4. the VPN interface is non-null
8559 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008560 * @see INetd#firewallAddUidInterfaceRules
8561 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008562 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008563 @Nullable
8564 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008565 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008566 if (nc == null || lp == null) return null;
8567 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008568 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008569 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008570 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008571 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008572 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008573 && !lp.hasExcludeRoute()) {
8574 return lp.getInterfaceName();
8575 }
8576 return null;
8577 }
8578
8579 /**
8580 * Returns whether we need to set interface filtering rule or not
8581 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008582 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008583 String isolationIface) {
8584 // Allow rules are always needed if VPN isolation is enabled.
8585 if (isolationIface != null) return true;
8586
8587 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8588 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8589 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09008590 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008591 }
8592
Chiachang Wang28afaff2020-12-10 22:24:47 +08008593 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8594 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8595 int index = 0;
8596 for (UidRange range : ranges) {
8597 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8598 index++;
8599 }
8600 return stableRanges;
8601 }
8602
Chalard Jeane6c95272022-01-25 21:04:21 +09008603 private static UidRangeParcel[] intsToUidRangeStableParcels(
8604 final @NonNull ArraySet<Integer> uids) {
8605 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8606 int index = 0;
8607 for (int uid : uids) {
8608 stableRanges[index] = new UidRangeParcel(uid, uid);
8609 index++;
8610 }
8611 return stableRanges;
8612 }
8613
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008614 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8615 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8616 for (int i = 0; i < ranges.length; i++) {
8617 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8618 }
8619 return stableRanges;
8620 }
8621
Motomu Utsumi93a22182023-03-16 17:04:21 +09008622 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
8623 Set<Integer> exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08008624 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8625 try {
Motomu Utsumi93a22182023-03-16 17:04:21 +09008626 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008627 } catch (Exception e) {
8628 loge("Exception in socket destroy: ", e);
8629 }
8630 }
8631 }
8632
paulhuaa0743d2021-05-26 21:56:03 +08008633 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi93a22182023-03-16 17:04:21 +09008634 final Set<Integer> exemptUids = new ArraySet<>();
Ken Chen5e65a852020-12-24 12:59:10 +08008635 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8636 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8637 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi93a22182023-03-16 17:04:21 +09008638 exemptUids.add(VPN_UID);
8639 exemptUids.add(nai.networkCapabilities.getOwnerUid());
Ken Chen5e65a852020-12-24 12:59:10 +08008640 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8641
Motomu Utsumi6345e462023-03-13 13:24:50 +09008642 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi93a22182023-03-16 17:04:21 +09008643 maybeCloseSockets(nai, uidRanges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008644 try {
8645 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008646 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008647 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008648 } else {
paulhu0e79d952021-06-09 16:11:35 +08008649 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008650 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008651 }
8652 } catch (Exception e) {
8653 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8654 " on netId " + nai.network.netId + ". " + e);
8655 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09008656 // Close sockets that established connection while requesting netd.
Motomu Utsumi93a22182023-03-16 17:04:21 +09008657 maybeCloseSockets(nai, uidRanges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008658 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008659
lucaslin53e8a262021-06-08 01:43:59 +08008660 private boolean isProxySetOnAnyDefaultNetwork() {
8661 ensureRunningOnConnectivityServiceThread();
8662 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8663 final NetworkAgentInfo nai = nri.getSatisfier();
8664 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8665 return true;
8666 }
8667 }
8668 return false;
8669 }
8670
8671 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8672 NetworkCapabilities newNc) {
8673 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8674 // the proxy might be changed since the default network satisfied by the apps might also
8675 // changed.
8676 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
8677 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09008678 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
8679 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09008680 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08008681 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
8682 mProxyTracker.sendProxyBroadcast();
8683 }
8684 }
8685
Chalard Jeane6c95272022-01-25 21:04:21 +09008686 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
8687 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008688 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
8689 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008690 if (null == prevRanges) prevRanges = new ArraySet<>();
8691 if (null == newRanges) newRanges = new ArraySet<>();
8692 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
8693
8694 prevRanges.removeAll(newRanges);
8695 newRanges.removeAll(prevRangesCopy);
8696
8697 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008698 // When updating the VPN uid routing rules, add the new range first then remove the old
8699 // range. If old range were removed first, there would be a window between the old
8700 // range being removed and the new range being added, during which UIDs contained
8701 // in both ranges are not subject to any VPN routing rules. Adding new range before
8702 // removing old range works because, unlike the filtering rules below, it's possible to
8703 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08008704 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
8705 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
8706 // [1-5] & [1-2],[4-5] == [3]
8707 // Then we can do:
8708 // maybeCloseSockets([3])
8709 // mNetd.networkAddUidRanges([1-2],[4-5])
8710 // mNetd.networkRemoveUidRanges([1-5])
8711 // maybeCloseSockets([3])
8712 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
8713 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09008714 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008715 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008716 }
8717 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008718 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008719 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00008720 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
8721 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008722 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
8723 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008724 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09008725 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008726 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
8727 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
8728 // were added first and then newRanges got removed later, there would be only one uid
8729 // 10013 left. A consequence of removing old ranges before adding new ranges is that
8730 // there is now a window of opportunity when the UIDs are not subject to any filtering.
8731 // Note that this is in contrast with the (more robust) update of VPN routing rules
8732 // above, where the addition of new ranges happens before the removal of old ranges.
8733 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
8734 // to be removed will never overlap with the new range to be added.
8735 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008736 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
8737 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008738 }
8739 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008740 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008741 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09008742 } catch (Exception e) {
8743 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008744 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008745 }
8746 }
8747
Chalard Jeande665262022-02-25 16:12:12 +09008748 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09008749 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
8750 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09008751 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
8752 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09008753 if (prevEmpty && newEmpty) return;
8754
8755 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09008756 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008757 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09008758 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008759
8760 if (prevUids.equals(newUids)) return;
8761
8762 // This implementation is very simple and vastly faster for sets of Integers than
8763 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
8764 // a key computed from the value and has storage for that.
8765 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
8766 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
8767 toRemove.removeAll(newUids);
8768 toAdd.removeAll(prevUids);
8769
8770 try {
8771 if (!toAdd.isEmpty()) {
8772 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
8773 nai.network.netId,
8774 intsToUidRangeStableParcels(toAdd),
8775 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8776 }
8777 if (!toRemove.isEmpty()) {
8778 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
8779 nai.network.netId,
8780 intsToUidRangeStableParcels(toRemove),
8781 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8782 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008783 } catch (ServiceSpecificException e) {
8784 // Has the interface disappeared since the network was built ?
8785 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09008786 } catch (RemoteException e) {
8787 // Netd died. This usually causes a runtime restart anyway.
8788 }
8789 }
8790
Junyu Lai2ed7d412022-10-07 16:52:21 +08008791 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
8792 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008793 ensureRunningOnConnectivityServiceThread();
8794
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008795 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008796 // Ignore updates for disconnected networks
8797 return;
8798 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008799 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008800 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09008801 + "; created=" + nai.getCreatedTime()
8802 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00008803 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008804 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8805 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008806 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008807 }
8808
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008809 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8810 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008811 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008812 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008813 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008814 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8815 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8816 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008817 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8818 // need to be sent as a separate extra.
8819 final NetworkRequest req = nri.isMultilayerRequest()
8820 ? nri.getActiveRequest()
8821 // Non-multilayer listen requests do not have an active request
8822 : nri.mRequests.get(0);
8823 if (req == null) {
8824 Log.wtf(TAG, "No request in NRI " + nri);
8825 }
8826 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008827 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008828 sendIntent(nri.mPendingIntent, intent);
8829 }
8830 // else not handled
8831 }
8832
8833 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8834 mPendingIntentWakeLock.acquire();
8835 try {
8836 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00008837 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09008838 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00008839 // Explicitly disallow the receiver from starting activities, to prevent apps from
8840 // utilizing the PendingIntent as a backdoor to do this.
8841 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
8842 }
8843 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
8844 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09008845 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008846 } catch (PendingIntent.CanceledException e) {
8847 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8848 mPendingIntentWakeLock.release();
8849 releasePendingNetworkRequest(pendingIntent);
8850 }
8851 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8852 }
8853
8854 @Override
8855 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8856 String resultData, Bundle resultExtras) {
8857 if (DBG) log("Finished sending " + pendingIntent);
8858 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008859 // Release with a delay so the receiving client has an opportunity to put in its
8860 // own request.
8861 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008862 }
8863
Chalard Jean46bfbf02022-02-02 00:56:25 +09008864 // networkAgent is only allowed to be null if notificationType is
8865 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
8866 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08008867 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09008868 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08008869 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008870 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008871 // Default request has no msgr. Also prevents callbacks from being invoked for
8872 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8873 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8874 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008875 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008876 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008877 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008878 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008879 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008880 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008881 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008882 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8883 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008884 }
Roshan Pius951c0032020-12-22 15:10:42 -08008885 final boolean includeLocationSensitiveInfo =
8886 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008887 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008888 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008889 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08008890 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09008891 networkCapabilitiesRestrictedForCallerPermissions(
8892 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
8893 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008894 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09008895 nri.mCallingAttributionTag);
8896 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008897 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8898 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008899 // For this notification, arg1 contains the blocked status.
8900 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008901 break;
8902 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008903 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008904 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008905 break;
8906 }
8907 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008908 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008909 final NetworkCapabilities netCap =
8910 networkCapabilitiesRestrictedForCallerPermissions(
8911 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8912 putParcelable(
8913 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008914 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008915 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008916 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008917 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008918 break;
8919 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008920 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008921 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8922 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008923 break;
8924 }
junyulaif2c67e42018-08-07 19:50:45 +08008925 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008926 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008927 msg.arg1 = arg1;
8928 break;
8929 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008930 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008931 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008932 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008933 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008934 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008935 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008936 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008937 }
James Mattis45d81842021-01-10 14:24:24 -08008938 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008939 } catch (RemoteException e) {
8940 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008941 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008942 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008943 }
8944
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008945 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8946 bundle.putParcelable(t.getClass().getSimpleName(), t);
8947 }
8948
Chalard Jean0702f982021-09-16 21:50:07 +09008949 /**
8950 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8951 *
8952 * When a request should be assigned to a new network, it is normally lingered to give
8953 * time for apps to gracefully migrate their connections. When both networks are on the same
8954 * radio, but that radio can't do time-sharing efficiently, this may end up being
8955 * counter-productive because any traffic on the old network may drastically reduce the
8956 * performance of the new network.
8957 * The stack supports a configuration to let modem vendors state that their radio can't
8958 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8959 * from one cell network to another can't be done gracefully.
8960 *
8961 * @param oldNai the old network serving the request
8962 * @param newNai the new network serving the request
8963 * @return whether the switch can be graceful
8964 */
8965 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8966 @NonNull final NetworkAgentInfo newSatisfier) {
8967 if (mCellularRadioTimesharingCapable) return true;
8968 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8969 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8970 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8971 }
8972
Paul Jensenaf94b982014-09-30 15:37:41 -04008973 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008974 if (nai.numRequestNetworkRequests() != 0) {
8975 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8976 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008977 // Ignore listening and track default requests.
8978 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008979 loge("Dead network still had at least " + nr);
8980 break;
8981 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008982 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008983 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008984 }
8985
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008986 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8987 if (oldNetwork == null) {
8988 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8989 return;
8990 }
Chalard Jean49707572019-12-10 21:07:02 +09008991 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008992
8993 // If we get here it means that the last linger timeout for this network expired. So there
8994 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008995 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008996
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008997 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008998 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008999 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009000 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009001 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009002 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009003 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009004 }
9005
James Mattise3ef1912020-12-20 11:09:58 -08009006 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9007 boolean isDefaultChanged = false;
9008 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9009 final NetworkReassignment.RequestReassignment reassignment =
9010 changes.getReassignment(defaultRequestInfo);
9011 if (null == reassignment) {
9012 continue;
9013 }
9014 // reassignment only contains those instances where the satisfying network changed.
9015 isDefaultChanged = true;
9016 // Notify system services of the new default.
9017 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9018 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009019
James Mattise3ef1912020-12-20 11:09:58 -08009020 if (isDefaultChanged) {
9021 // Hold a wakelock for a short time to help apps in migrating to a new default.
9022 scheduleReleaseNetworkTransitionWakelock();
9023 }
9024 }
9025
9026 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9027 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9028 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9029 if (DBG) {
9030 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9031 }
Chalard Jean8e382112019-12-03 20:45:30 +09009032
James Mattisd31bdfa2020-12-23 16:37:26 -08009033 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9034 if (newDefaultNetwork != null) {
9035 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009036 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009037
James Mattisd31bdfa2020-12-23 16:37:26 -08009038 // Set an app level managed default and return since further processing only applies to the
9039 // default network.
9040 if (mDefaultRequest != nri) {
9041 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9042 return;
9043 }
9044
9045 makeDefaultNetwork(newDefaultNetwork);
9046
James Mattise3ef1912020-12-20 11:09:58 -08009047 if (oldDefaultNetwork != null) {
9048 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9049 }
9050 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009051 handleApplyDefaultProxy(null != newDefaultNetwork
9052 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
9053 updateTcpBufferSizes(null != newDefaultNetwork
9054 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009055 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009056 }
9057
James Mattisd31bdfa2020-12-23 16:37:26 -08009058 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9059 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9060 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9061 try {
9062 if (VDBG) {
9063 log("Setting default network for " + nri
9064 + " using UIDs " + nri.getUids()
9065 + " with old network " + (oldDefaultNetwork != null
9066 ? oldDefaultNetwork.network().getNetId() : "null")
9067 + " and new network " + (newDefaultNetwork != null
9068 ? newDefaultNetwork.network().getNetId() : "null"));
9069 }
9070 if (nri.getUids().isEmpty()) {
9071 throw new IllegalStateException("makeDefaultForApps called without specifying"
9072 + " any applications to set as the default." + nri);
9073 }
9074 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009075 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009076 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009077 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009078 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009079 }
9080 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009081 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009082 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009083 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009084 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009085 }
9086 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009087 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009088 }
9089 }
9090
Junyu Lai35665cc2022-12-19 17:37:48 +08009091 /**
9092 * Collect restricted uid ranges for the given network and UserHandle, these uids
9093 * are not restricted for matched enterprise networks but being restricted for non-matched
9094 * enterprise networks and non-enterprise networks.
9095 */
9096 @NonNull
9097 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9098 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9099 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9100 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9101 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9102
9103 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9104 // The NC is built from a `ProfileNetworkPreference` which has only one
9105 // enterprise ID, so it's guaranteed to have exactly one.
9106 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9107 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9108 continue;
9109 }
9110 }
9111
9112 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9113 pref.capabilities.getUidRanges())) {
9114 throw new IllegalArgumentException(
9115 "Overlapping uid range in preference: " + pref);
9116 }
9117 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9118 }
9119 return restrictedUidRanges;
9120 }
9121
9122 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009123 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +09009124 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +08009125
Junyu Lai35665cc2022-12-19 17:37:48 +08009126 ensureRunningOnConnectivityServiceThread();
9127 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9128 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9129 .getUserHandles(true /* excludeDying */);
9130 if (users.isEmpty()) {
9131 throw new IllegalStateException("No user is available");
9132 }
9133
9134 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9135 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9136 for (final UserHandle user : users) {
9137 final ArraySet<UidRange> restrictedUidRanges =
9138 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9139 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9140 UidRange.createForUser(user), restrictedUidRanges));
9141 }
9142
9143 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9144 configs.add(new NativeUidRangeConfig(
9145 nai.network.netId, rangesParcel, 0 /* subPriority */));
9146 }
9147
9148 // The netd API replaces the previous configs with the current configs.
9149 // Thus, for network disconnection or preference removal, no need to
9150 // unset previous config. Instead, collecting all currently needed
9151 // configs and issue to netd.
9152 try {
9153 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9154 } catch (ServiceSpecificException e) {
9155 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009156 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009157 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009158 // Netd died. This will cause a runtime restart anyway.
9159 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009160 }
9161 }
9162
James Mattisd31bdfa2020-12-23 16:37:26 -08009163 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9164 try {
9165 if (null != newDefaultNetwork) {
9166 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9167 } else {
9168 mNetd.networkClearDefault();
9169 }
9170 } catch (RemoteException | ServiceSpecificException e) {
9171 loge("Exception setting default network :" + e);
9172 }
9173 }
9174
Chalard Jean05cbe972019-12-09 11:50:38 +09009175 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009176 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009177 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009178 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009179 processNewlySatisfiedListenRequests(nai);
9180 }
9181
9182 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009183 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9184 if (nri.isMultilayerRequest()) {
9185 continue;
9186 }
9187 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009188 if (!nr.isListen()) continue;
9189 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009190 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009191 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9192 }
9193 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009194 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009195
Chalard Jeancd397a22019-11-22 22:33:33 +09009196 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009197 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9198 if (nri.isMultilayerRequest()) {
9199 continue;
9200 }
9201 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009202 if (!nr.isListen()) continue;
9203 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9204 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009205 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009206 }
9207 }
9208 }
9209
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009210 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009211 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009212 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009213 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009214 @Nullable public final NetworkRequest mOldNetworkRequest;
9215 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009216 @Nullable public final NetworkAgentInfo mOldNetwork;
9217 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009218 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009219 @Nullable final NetworkRequest oldNetworkRequest,
9220 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009221 @Nullable final NetworkAgentInfo oldNetwork,
9222 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009223 mNetworkRequestInfo = networkRequestInfo;
9224 mOldNetworkRequest = oldNetworkRequest;
9225 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009226 mOldNetwork = oldNetwork;
9227 mNewNetwork = newNetwork;
9228 }
Chalard Jean49707572019-12-10 21:07:02 +09009229
9230 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009231 final NetworkRequest requestToShow = null != mNewNetworkRequest
9232 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9233 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009234 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9235 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009236 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009237 }
9238
Chalard Jean46a62372019-12-10 21:25:24 +09009239 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009240
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009241 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009242 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009243 }
9244
9245 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009246 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009247 // The code is never supposed to add two reassignments of the same request. Make
9248 // sure this stays true, but without imposing this expensive check on all
9249 // reassignments on all user devices.
9250 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009251 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009252 throw new IllegalStateException("Trying to reassign ["
9253 + reassignment + "] but already have ["
9254 + existing + "]");
9255 }
9256 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009257 }
Chalard Jean46a62372019-12-10 21:25:24 +09009258 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009259 }
9260
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009261 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009262 // the passed request.
9263 @Nullable
9264 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009265 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009266 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009267 }
9268 return null;
9269 }
Chalard Jean49707572019-12-10 21:07:02 +09009270
9271 public String toString() {
9272 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9273 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009274 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009275 for (final RequestReassignment rr : getRequestReassignments()) {
9276 sj.add(rr.toString());
9277 }
9278 return sj.toString();
9279 }
9280
9281 public String debugString() {
9282 final StringBuilder sb = new StringBuilder();
9283 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009284 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009285 for (final RequestReassignment rr : getRequestReassignments()) {
9286 sb.append("\n ").append(rr);
9287 }
9288 return sb.append("\n").toString();
9289 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009290 }
9291
Chalard Jean24344d72019-12-04 13:32:31 +09009292 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009293 @Nullable final NetworkRequest previousRequest,
9294 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009295 @Nullable final NetworkAgentInfo previousSatisfier,
9296 @Nullable final NetworkAgentInfo newSatisfier,
9297 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009298 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009299 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009300 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009301 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009302 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09009303 }
James Mattisa076c532020-12-02 14:12:41 -08009304 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009305 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009306 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009307 // If this network switch can't be supported gracefully, the request is not
9308 // lingered. This allows letting go of the network sooner to reclaim some
9309 // performance on the new network, since the radio can't do both at the same
9310 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009311 //
9312 // Also don't linger the request if the old network has been destroyed.
9313 // A destroyed network does not provide actual network connectivity, so
9314 // lingering it is not useful. In particular this ensures that a destroyed
9315 // network is outscored by its replacement,
9316 // then it is torn down immediately instead of being lingered, and any apps that
9317 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009318 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9319 }
Chalard Jean24344d72019-12-04 13:32:31 +09009320 } else {
9321 if (VDBG || DDBG) log(" accepting network in place of null");
9322 }
junyulai0ac374f2020-12-14 18:41:52 +08009323
9324 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9325 // and immediately satisfies a request then remove the timer. This will happen for
9326 // all networks except in the case of an underlying network for a VCN.
9327 if (newSatisfier.isNascent()) {
9328 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009329 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009330 }
9331
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009332 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009333 newSatisfier.unlingerRequest(newRequest.requestId);
9334 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009335 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009336 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009337 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009338 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009339 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009340 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009341 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009342 }
James Mattisa076c532020-12-02 14:12:41 -08009343 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009344 }
James Mattisa076c532020-12-02 14:12:41 -08009345 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009346 }
9347
James Mattisa076c532020-12-02 14:12:41 -08009348 /**
9349 * This function is triggered when something can affect what network should satisfy what
9350 * request, and it computes the network reassignment from the passed collection of requests to
9351 * network match to the one that the system should now have. That data is encoded in an
9352 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9353 * satisfier.
9354 *
9355 * After the reassignment is computed, it is applied to the state objects.
9356 *
9357 * @param networkRequests the nri objects to evaluate for possible network reassignment
9358 * @return NetworkReassignment listing of proposed network assignment changes
9359 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009360 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009361 private NetworkReassignment computeNetworkReassignment(
9362 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009363 final NetworkReassignment changes = new NetworkReassignment();
9364
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009365 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009366 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009367 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009368 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009369 }
Chalard Jean857a1712019-12-10 21:08:07 +09009370
James Mattisa076c532020-12-02 14:12:41 -08009371 for (final NetworkRequestInfo nri : networkRequests) {
9372 // Non-multilayer listen requests can be ignored.
9373 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9374 continue;
9375 }
9376 NetworkAgentInfo bestNetwork = null;
9377 NetworkRequest bestRequest = null;
9378 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009379 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009380 // Stop evaluating as the highest possible priority request is satisfied.
9381 if (null != bestNetwork) {
9382 bestRequest = req;
9383 break;
9384 }
9385 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009386 if (null == bestNetwork && isDefaultBlocked(nri)) {
9387 // Remove default networking if disallowed for managed default requests.
9388 bestNetwork = mNoServiceNetwork;
9389 }
9390 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009391 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009392 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009393 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009394 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009395 }
9396 return changes;
9397 }
9398
James Mattisa076c532020-12-02 14:12:41 -08009399 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9400 return new HashSet<>(mNetworkRequests.values());
9401 }
9402
Paul Jensenc88b39b2015-06-16 14:27:36 -04009403 /**
James Mattisa076c532020-12-02 14:12:41 -08009404 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009405 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009406 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009407 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009408 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9409 }
9410
9411 /**
9412 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9413 * being disconnected.
9414 */
9415 private void rematchNetworksAndRequests(
9416 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9417 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009418 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009419 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009420 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09009421 final long computed = SystemClock.elapsedRealtime();
9422 applyNetworkReassignment(changes, start);
9423 final long applied = SystemClock.elapsedRealtime();
9424 issueNetworkNeeds();
9425 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09009426 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009427 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
9428 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009429 log(changes.debugString());
9430 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009431 // Shorter form, only one line of log
9432 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
9433 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009434 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09009435 }
Chalard Jean64520dc2019-12-04 19:55:32 +09009436
Chalard Jeand7f762d2019-12-10 19:01:29 +09009437 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09009438 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009439 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09009440
9441 // Since most of the time there are only 0 or 1 background networks, it would probably
9442 // be more efficient to just use an ArrayList here. TODO : measure performance
9443 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
9444 for (final NetworkAgentInfo nai : nais) {
9445 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
9446 }
9447
Chalard Jeand7f762d2019-12-10 19:01:29 +09009448 // First, update the lists of satisfied requests in the network agents. This is necessary
9449 // because some code later depends on this state to be correct, most prominently computing
9450 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09009451 for (final NetworkReassignment.RequestReassignment event :
9452 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009453 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
9454 event.mOldNetworkRequest, event.mNewNetworkRequest,
9455 event.mOldNetwork, event.mNewNetwork,
9456 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09009457 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009458
James Mattise3ef1912020-12-20 11:09:58 -08009459 // Process default network changes if applicable.
9460 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009461
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009462 // Notify requested networks are available after the default net is switched, but
9463 // before LegacyTypeTracker sends legacy broadcasts
9464 for (final NetworkReassignment.RequestReassignment event :
9465 changes.getRequestReassignments()) {
9466 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009467 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009468 } else {
James Mattisa076c532020-12-02 14:12:41 -08009469 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009470 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009471 }
9472 }
9473
junyulai0ac374f2020-12-14 18:41:52 +08009474 // Update the inactivity state before processing listen callbacks, because the background
9475 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009476 // just yet though, because they have to be sent after the listens are processed to keep
9477 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08009478 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09009479 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08009480 // Rematching may have altered the inactivity state of some networks, so update all
9481 // inactivity timers. updateInactivityState reads the state from the network agent
9482 // and does nothing if the state has not changed : the source of truth is controlled
9483 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
9484 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08009485 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08009486 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009487 }
9488 }
9489
Chalard Jeanb10ab412019-12-11 14:12:30 +09009490 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009491 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009492 // Process listen requests and update capabilities if the background state has
9493 // changed for this network. For consistency with previous behavior, send onLost
9494 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09009495 processNewlyLostListenRequests(nai);
9496 if (oldBackground != nai.isBackgroundNetwork()) {
9497 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009498 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09009499 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009500 }
9501
junyulai0ac374f2020-12-14 18:41:52 +08009502 for (final NetworkAgentInfo nai : inactiveNetworks) {
9503 // For nascent networks, if connecting with no foreground request, skip broadcasting
9504 // LOSING for backward compatibility. This is typical when mobile data connected while
9505 // wifi connected with mobile data always-on enabled.
9506 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009507 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009508 }
9509
James Mattise3ef1912020-12-20 11:09:58 -08009510 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09009511
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009512 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009513 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009514 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08009515 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009516 // This network has active linger timers and no requests, but is not
9517 // lingering. Linger it.
9518 //
9519 // One way (the only way?) this can happen if this network is unvalidated
9520 // and became unneeded due to another network improving its score to the
9521 // point where this network will no longer be able to satisfy any requests
9522 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08009523 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009524 notifyNetworkLosing(nai, now);
9525 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09009526 } else {
Chalard Jean49707572019-12-10 21:07:02 +09009527 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09009528 teardownUnneededNetwork(nai);
9529 }
9530 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04009531 }
9532 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009533
Chalard Jean62edfd82019-12-02 18:39:29 +09009534 /**
9535 * Apply a change in background state resulting from rematching networks with requests.
9536 *
9537 * During rematch, a network may change background states by starting to satisfy or stopping
9538 * to satisfy a foreground request. Listens don't count for this. When a network changes
9539 * background states, its capabilities need to be updated and callbacks fired for the
9540 * capability change.
9541 *
9542 * @param nai The network that changed background states
9543 */
9544 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
9545 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
9546 if (Objects.equals(nai.networkCapabilities, newNc)) return;
9547 updateNetworkPermissions(nai, newNc);
9548 nai.getAndSetNetworkCapabilities(newNc);
9549 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
9550 }
9551
Chalard Jeanf0344532019-11-19 19:23:38 +09009552 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08009553 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009554 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09009555 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
9556 changes.getReassignment(mDefaultRequest);
9557 final NetworkAgentInfo oldDefaultNetwork =
9558 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
9559 final NetworkAgentInfo newDefaultNetwork =
9560 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08009561
Chalard Jean5b409c72021-02-04 13:12:59 +09009562 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009563 // Maintain the illusion : since the legacy API only understands one network at a time,
9564 // if the default network changed, apps should see a disconnected broadcast for the
9565 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09009566 if (oldDefaultNetwork != null) {
9567 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
9568 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009569 }
Chalard Jean5b409c72021-02-04 13:12:59 +09009570 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009571 // The new default network can be newly null if and only if the old default
9572 // network doesn't satisfy the default request any more because it lost a
9573 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09009574 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08009575 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09009576 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009577 }
9578 }
9579
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009580 // Now that all the callbacks have been sent, send the legacy network broadcasts
9581 // as needed. This is necessary so that legacy requests correctly bind dns
9582 // requests to this network. The legacy users are listening for this broadcast
9583 // and will generally do a dns request so they can ensureRouteToHost and if
9584 // they do that before the callbacks happen they'll use the default network.
9585 //
9586 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
9587 // callbacks, but if apps can receive the broadcast before the callback, they still might
9588 // have an inconsistent view of networking.
9589 //
9590 // This *does* introduce a race where if the user uses the new api
9591 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
9592 // they may get old info. Reverse this after the old startUsing api is removed.
9593 // This is on top of the multiple intent sequencing referenced in the todo above.
9594 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09009595 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009596 addNetworkToLegacyTypeTracker(nai);
9597 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08009598 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009599 }
9600
Chalard Jean0354d8c2021-01-12 10:58:56 +09009601 private void issueNetworkNeeds() {
9602 ensureRunningOnConnectivityServiceThread();
9603 for (final NetworkOfferInfo noi : mNetworkOffers) {
9604 issueNetworkNeeds(noi);
9605 }
9606 }
9607
9608 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
9609 ensureRunningOnConnectivityServiceThread();
9610 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9611 informOffer(nri, noi.offer, mNetworkRanker);
9612 }
9613 }
9614
9615 /**
9616 * Inform a NetworkOffer about any new situation of a request.
9617 *
9618 * This function handles updates to offers. A number of events may happen that require
9619 * updating the registrant for this offer about the situation :
9620 * • The offer itself was updated. This may lead the offer to no longer being able
9621 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
9622 * or conversely being strengthened enough to beat the satisfier (and therefore
9623 * start being needed)
9624 * • The network satisfying a request changed (including cases where the request
9625 * starts or stops being satisfied). The new network may be a stronger or weaker
9626 * match than the old one, possibly affecting whether the offer is needed.
9627 * • The network satisfying a request updated their score. This may lead the offer
9628 * to no longer be able to beat it if the current satisfier got better, or
9629 * conversely start being a good choice if the current satisfier got weaker.
9630 *
9631 * @param nri The request
9632 * @param offer The offer. This may be an updated offer.
9633 */
9634 private static void informOffer(@NonNull NetworkRequestInfo nri,
9635 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9636 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9637 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009638
9639 // Multi-layer requests have a currently active request, the one being satisfied.
9640 // Since the system will try to bring up a better network than is currently satisfying
9641 // the request, NetworkProviders need to be told the offers matching the requests *above*
9642 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9643 // not needed, and the offer is needed for the active request iff the offer can beat
9644 // the satisfier.
9645 // For non-multilayer requests, the logic above gracefully degenerates to only the
9646 // last case.
9647 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9648 // providers that the offer is needed for this request, until the active request is found.
9649 // In a second phase, deal with the currently active request. In a third phase, inform
9650 // the providers that offer is unneeded for the remaining requests.
9651
9652 // First phase : inform providers of all requests above the active request.
9653 int i;
9654 for (i = 0; nri.mRequests.size() > i; ++i) {
9655 final NetworkRequest request = nri.mRequests.get(i);
9656 if (activeRequest == request) break; // Found the active request : go to phase 2
9657 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9658 // Since this request is higher-priority than the one currently satisfied, if the
9659 // offer can satisfy it, the provider should try and bring up the network for sure ;
9660 // no need to even ask the ranker – an offer that can satisfy is always better than
9661 // no network. Hence tell the provider so unless it already knew.
9662 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
9663 offer.onNetworkNeeded(request);
9664 }
9665 }
9666
9667 // Second phase : deal with the active request (if any)
9668 if (null != activeRequest && activeRequest.isRequest()) {
9669 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00009670 // If an offer can satisfy the request, it is considered needed if it is currently
9671 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09009672 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00009673 && satisfier.factorySerialNumber == offer.providerId
9674 && activeRequest.canBeSatisfiedBy(offer.caps);
9675 final boolean newNeeded = currentlyServing
9676 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09009677 if (newNeeded != oldNeeded) {
9678 if (newNeeded) {
9679 offer.onNetworkNeeded(activeRequest);
9680 } else {
9681 // The offer used to be able to beat the satisfier. Now it can't.
9682 offer.onNetworkUnneeded(activeRequest);
9683 }
9684 }
9685 }
9686
9687 // Third phase : inform the providers that the offer isn't needed for any request
9688 // below the active one.
9689 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
9690 final NetworkRequest request = nri.mRequests.get(i);
9691 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9692 // Since this request is lower-priority than the one currently satisfied, if the
9693 // offer can satisfy it, the provider should not try and bring up the network.
9694 // Hence tell the provider so unless it already knew.
9695 if (offer.neededFor(request)) {
9696 offer.onNetworkUnneeded(request);
9697 }
9698 }
9699 }
9700
Chalard Jean61c79252019-11-07 23:07:32 +09009701 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
9702 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9703 NetworkRequest nr = nai.requestAt(i);
9704 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
9705 // legacy type tracker filters out repeat adds
9706 mLegacyTypeTracker.add(nr.legacyType, nai);
9707 }
9708 }
9709
9710 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09009711 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09009712 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
9713 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
9714 if (nai.isVPN()) {
9715 mLegacyTypeTracker.add(TYPE_VPN, nai);
9716 }
9717 }
9718
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09009719 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04009720 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +09009721 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09009722 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04009723 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09009724 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009725
Chalard Jean254bd162022-08-25 13:04:51 +09009726 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009727 // Don't repeat publish.
9728 if (newInetCondition == mDefaultInetConditionPublished) return;
9729
9730 mDefaultInetConditionPublished = newInetCondition;
9731 sendInetConditionBroadcast(nai.networkInfo);
9732 }
9733
Chalard Jeand61375d2020-01-14 22:46:36 +09009734 @NonNull
9735 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
9736 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009737 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09009738 final boolean suspended =
9739 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9740 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
9741 // Only override the state with SUSPENDED if the network is currently in CONNECTED
9742 // state. This is because the network could have been suspended before connecting,
9743 // or it could be disconnecting while being suspended, and in both these cases
9744 // the state should not be overridden. Note that the only detailed state that
9745 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
9746 // worry about multiple different substates of CONNECTED.
9747 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
9748 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009749 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
9750 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
9751 // network agent is created, then goes to suspended, then goes out of suspended without
9752 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +09009753 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009754 ? NetworkInfo.DetailedState.CONNECTED
9755 : NetworkInfo.DetailedState.CONNECTING,
9756 info.getReason(),
9757 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09009758 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009759 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09009760 return newInfo;
9761 }
9762
9763 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
9764 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
9765
Erik Kline99f301b2017-02-15 19:59:17 +09009766 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009767 NetworkInfo oldInfo = null;
9768 synchronized (networkAgent) {
9769 oldInfo = networkAgent.networkInfo;
9770 networkAgent.networkInfo = newInfo;
9771 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009772
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009773 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009774 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
9775 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009776 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009777
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09009778 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009779 // A network that has just connected has zero requests and is thus a foreground network.
9780 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
9781
Luke Huangfdd11f82019-04-09 18:41:49 +08009782 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09009783
9784 networkAgent.setCreated();
9785
9786 // If the network is created immediately on register, then apply the LinkProperties now.
9787 // Otherwise, this is done further down when the network goes into connected state.
9788 // Applying the LinkProperties means that the network is ready to carry traffic -
9789 // interfaces and routing rules have been added, DNS servers programmed, etc.
9790 // For VPNs, this must be done before the capabilities are updated, because as soon as
9791 // that happens, UIDs are routed to the network.
9792 if (shouldCreateNetworksImmediately()) {
9793 applyInitialLinkProperties(networkAgent);
9794 }
9795
9796 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
9797 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +09009798 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009799 // Initialize the network's capabilities to their starting values according to the
9800 // underlying networks. This ensures that the capabilities are correct before
9801 // anything happens to the network.
9802 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09009803 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +08009804 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +09009805 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +08009806 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009807 }
9808
Chalard Jean254bd162022-08-25 13:04:51 +09009809 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
9810 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009811
lucaslin45e639b2019-04-03 17:09:28 +08009812 // NetworkCapabilities need to be set before sending the private DNS config to
9813 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09009814 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
9815
Erik Kline9a62f012018-03-21 07:18:33 -07009816 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09009817 if (!shouldCreateNetworksImmediately()) {
9818 applyInitialLinkProperties(networkAgent);
9819 } else {
9820 // The network was created when the agent registered, and the LinkProperties are
9821 // already up-to-date. However, updateLinkProperties also makes some changes only
9822 // when the network connects. Apply those changes here. On T and below these are
9823 // handled by the applyInitialLinkProperties call just above.
9824 // TODO: stop relying on updateLinkProperties(..., null) to do this.
9825 // If something depends on both LinkProperties and connected state, it should be in
9826 // this method as well.
9827 networkAgent.clatd.update();
9828 updateProxy(networkAgent.linkProperties, null);
9829 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009830
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +01009831 // If a rate limit has been configured and is applicable to this network (network
9832 // provides internet connectivity), apply it. The tc police filter cannot be attached
9833 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
9834 // updateInterfaces -> INetd#networkAddInterface.
9835 // Note: in case of a system server crash, the NetworkController constructor in netd
9836 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
9837 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
9838 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
9839 mIngressRateLimit);
9840 }
9841
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009842 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
9843 // command must be sent after updating LinkProperties to maximize chances of
9844 // NetworkMonitor seeing the correct LinkProperties when starting.
9845 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009846 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09009847 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009848 }
Chalard Jeand4900722022-02-06 12:25:38 +09009849 final NetworkMonitorParameters params = new NetworkMonitorParameters();
9850 params.networkAgentConfig = networkAgent.networkAgentConfig;
9851 params.networkCapabilities = networkAgent.networkCapabilities;
9852 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
9853 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +09009854 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
9855 // newer callback even before T. However getInterfaceVersion is a synchronized binder
9856 // call that would cause a Log.wtf to be emitted from the system_server process, and
9857 // in the absence of a satisfactory, scalable solution which follows an easy/standard
9858 // process to check the interface version, just use an SDK check. NetworkStack will
9859 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +09009860 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +09009861 networkAgent.networkMonitor().notifyNetworkConnected(params);
9862 } else {
9863 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
9864 params.networkCapabilities);
9865 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09009866 final long delay = !avoidBadWifi() && activelyPreferBadWifi()
Chalard Jeane63c42f2022-09-16 19:31:45 +09009867 ? ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS
9868 : DONT_ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
9869 scheduleEvaluationTimeout(networkAgent.network, delay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009870
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009871 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
9872 // be communicated to a particular NetworkAgent depends only on the network's immutable,
9873 // capabilities, so it only needs to be done once on initial connect, not every time the
9874 // network's capabilities change. Note that we do this before rematching the network,
9875 // so we could decide to tear it down immediately afterwards. That's fine though - on
9876 // disconnection NetworkAgents should stop any signal strength monitoring they have been
9877 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09009878 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009879
junyulai0ac374f2020-12-14 18:41:52 +08009880 // Before first rematching networks, put an inactivity timer without any request, this
9881 // allows {@code updateInactivityState} to update the state accordingly and prevent
9882 // tearing down for any {@code unneeded} evaluation in this period.
9883 // Note that the timer will not be rescheduled since the expiry time is
9884 // fixed after connection regardless of the network satisfying other requests or not.
9885 // But it will be removed as soon as the network satisfies a request for the first time.
9886 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
9887 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08009888 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009889
Paul Jensen05e85ee2014-09-11 11:00:39 -04009890 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009891 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009892
9893 // This has to happen after matching the requests, because callbacks are just requests.
9894 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009895 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009896 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04009897 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009898 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04009899 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09009900 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00009901 if (networkAgent.isVPN()) {
9902 // As the active or bound network changes for apps, broadcast the default proxy, as
9903 // apps may need to update their proxy data. This is called after disconnecting from
9904 // VPN to make sure we do not broadcast the old proxy data.
9905 // TODO(b/122649188): send the broadcast only to VPN users.
9906 mProxyTracker.sendProxyBroadcast();
9907 }
Chalard Jean254bd162022-08-25 13:04:51 +09009908 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
9909 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009910 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009911 }
9912 }
9913
Chalard Jean28018572020-12-21 18:36:52 +09009914 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09009915 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
9916 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009917 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07009918 }
9919
Erik Kline99f301b2017-02-15 19:59:17 +09009920 // Notify only this one new request of the current state. Transfer all the
9921 // current state by calling NetworkCapabilities and LinkProperties callbacks
9922 // so that callers can be guaranteed to have as close to atomicity in state
9923 // transfer as can be supported by this current API.
9924 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07009925 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09009926 if (nri.mPendingIntent != null) {
9927 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
9928 // Attempt no subsequent state pushes where intents are involved.
9929 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009930 }
Erik Kline99f301b2017-02-15 19:59:17 +09009931
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009932 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08009933 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009934 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
9935 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
9936 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08009937 }
9938
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009939 // Notify the requests on this NAI that the network is now lingered.
9940 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08009941 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009942 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
9943 }
9944
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009945 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
9946 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
9947 return vpnBlocked
9948 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
9949 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
9950 }
9951
9952 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
9953 if (blockedReasons == BLOCKED_REASON_NONE) {
9954 mUidBlockedReasons.delete(uid);
9955 } else {
9956 mUidBlockedReasons.put(uid, blockedReasons);
9957 }
9958 }
9959
junyulaif2c67e42018-08-07 19:50:45 +08009960 /**
9961 * Notify of the blocked state apps with a registered callback matching a given NAI.
9962 *
9963 * Unlike other callbacks, blocked status is different between each individual uid. So for
9964 * any given nai, all requests need to be considered according to the uid who filed it.
9965 *
9966 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009967 * @param oldMetered True if the previous network capabilities were metered.
9968 * @param newMetered True if the current network capabilities are metered.
9969 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
9970 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08009971 */
9972 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00009973 boolean newMetered, List<UidRange> oldBlockedUidRanges,
9974 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08009975
9976 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9977 NetworkRequest nr = nai.requestAt(i);
9978 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009979
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009980 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9981 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9982 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009983 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009984 : oldVpnBlocked;
9985
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009986 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9987 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9988 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009989 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009990 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009991 }
9992 }
9993 }
9994
9995 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009996 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009997 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009998 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009999 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010000 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010001 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010002 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010003 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010004
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010005 final int oldBlockedState = getBlockedState(
10006 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
10007 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
10008 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080010009 continue;
junyulaif2c67e42018-08-07 19:50:45 +080010010 }
junyulaif2c67e42018-08-07 19:50:45 +080010011 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10012 NetworkRequest nr = nai.requestAt(i);
10013 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010014 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010015 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10016 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010017 }
10018 }
10019 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010020 }
10021
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010022 @VisibleForTesting
10023 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010024 // The NetworkInfo we actually send out has no bearing on the real
10025 // state of affairs. For example, if the default connection is mobile,
10026 // and a request for HIPRI has just gone away, we need to pretend that
10027 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10028 // the state to DISCONNECTED, even though the network is of type MOBILE
10029 // and is still connected.
10030 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10031 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010032 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010033 if (state != DetailedState.DISCONNECTED) {
10034 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010035 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010036 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010037 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010038 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10039 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10040 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10041 if (info.isFailover()) {
10042 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10043 nai.networkInfo.setFailover(false);
10044 }
10045 if (info.getReason() != null) {
10046 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10047 }
10048 if (info.getExtraInfo() != null) {
10049 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10050 }
10051 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010052 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010053 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010054 if (newDefaultAgent != null) {
10055 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10056 newDefaultAgent.networkInfo);
10057 } else {
10058 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10059 }
10060 }
10061 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10062 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010063 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010064 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010065 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010066 }
10067 }
10068 }
10069
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010070 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010071 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010072 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010073 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010074 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010075 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10076 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010077 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10078 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010079 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010080 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010081 } else {
10082 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10083 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010084 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010085 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010086
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010087 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10088 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10089 }
10090
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010091 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010092 * Returns the list of all interfaces that could be used by network traffic that does not
10093 * explicitly specify a network. This includes the default network, but also all VPNs that are
10094 * currently connected.
10095 *
10096 * Must be called on the handler thread.
10097 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010098 @NonNull
10099 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010100 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010101 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010102 final Set<Integer> activeNetIds = new ArraySet<>();
10103 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10104 if (nri.isBeingSatisfied()) {
10105 activeNetIds.add(nri.getSatisfier().network().netId);
10106 }
10107 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010108 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010109 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010110 defaultNetworks.add(nai.network);
10111 }
10112 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010113 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010114 }
10115
10116 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010117 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10118 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010119 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010120 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010121 ensureRunningOnConnectivityServiceThread();
10122 String activeIface = null;
10123 LinkProperties activeLinkProperties = getActiveLinkProperties();
10124 if (activeLinkProperties != null) {
10125 activeIface = activeLinkProperties.getInterfaceName();
10126 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010127
junyulai2050bed2021-01-23 09:46:34 +080010128 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010129 try {
junyulaide41fc22021-01-22 22:46:01 +080010130 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010131 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010132 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10133 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010134 } catch (Exception ignored) {
10135 }
10136 }
10137
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010138 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010139 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010140 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010141 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010142 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010143
10144 if (!TextUtils.isEmpty(settingUrl)) {
10145 return settingUrl;
10146 }
10147
10148 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010149 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010150 if (!TextUtils.isEmpty(settingUrl)) {
10151 return settingUrl;
10152 }
10153
10154 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010155 }
10156
10157 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010158 public void startNattKeepalive(Network network, int intervalSeconds,
10159 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010160 enforceKeepalivePermission();
10161 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010162 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000010163 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
10164 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000010165 // false and set the underpinned network to null because there is no way and no
10166 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10167 // deprecated method.
10168 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010169 }
10170
10171 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010172 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010173 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010174 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010175 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010176 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010177 mKeepaliveTracker.startNattKeepalive(
10178 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010179 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10180 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010181 } finally {
10182 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10183 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010184 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10185 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010186 }
10187 }
junyulaid05a1922019-01-15 11:32:44 +080010188 }
10189
10190 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010191 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010192 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010193 try {
10194 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010195 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010196 mKeepaliveTracker.startTcpKeepalive(
10197 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10198 } finally {
10199 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10200 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010201 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10202 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010203 }
10204 }
junyulai0835a1e2019-01-08 20:04:33 +080010205 }
10206
10207 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010208 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010209 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010210 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10211 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010212 }
10213
10214 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090010215 public int[] getSupportedKeepalives() {
10216 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
10217 // Backwards compatibility with CTS 13
10218 android.Manifest.permission.QUERY_ALL_PACKAGES);
10219
10220 return BinderUtils.withCleanCallingIdentity(() ->
10221 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
10222 }
10223
10224 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010225 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010226 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010227
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010228 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010229 final long token = Binder.clearCallingIdentity();
10230 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010231 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10232 UserHandle.getUserHandleForUid(uid))) {
10233 return;
10234 }
10235
Heemin Seogdb8489d2019-06-12 09:21:44 -070010236 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10237 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010238
10239 // Turn airplane mode off
10240 setAirplaneMode(false);
10241
10242 // restore private DNS settings to default mode (opportunistic)
10243 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10244 UserHandle.getUserHandleForUid(uid))) {
10245 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10246 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10247 }
10248
10249 Settings.Global.putString(mContext.getContentResolver(),
10250 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010251 } finally {
10252 Binder.restoreCallingIdentity(token);
10253 }
Stuart Scottd5463642015-04-02 18:00:02 -070010254 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010255
Ricky Wai7097cc92018-01-23 04:09:45 +000010256 @Override
10257 public byte[] getNetworkWatchlistConfigHash() {
10258 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10259 if (nwm == null) {
10260 loge("Unable to get NetworkWatchlistManager");
10261 return null;
10262 }
10263 // Redirect it to network watchlist service to access watchlist file and calculate hash.
10264 return nwm.getWatchlistConfigHash();
10265 }
10266
Hugo Benichibe0c7652016-05-31 16:28:06 +090010267 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090010268 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080010269 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090010270 }
Hugo Benichif4210292017-04-21 15:07:12 +090010271
10272 private static boolean toBool(int encodedBoolean) {
10273 return encodedBoolean != 0; // Only 0 means false.
10274 }
10275
10276 private static int encodeBool(boolean b) {
10277 return b ? 1 : 0;
10278 }
mswest4632928412018-03-12 10:34:34 -070010279
10280 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010281 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
10282 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
10283 @NonNull String[] args) {
10284 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
10285 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070010286 }
10287
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010288 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070010289 @Override
10290 public int onCommand(String cmd) {
10291 if (cmd == null) {
10292 return handleDefaultCommands(cmd);
10293 }
10294 final PrintWriter pw = getOutPrintWriter();
10295 try {
10296 switch (cmd) {
10297 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010298 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
10299 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070010300 final String action = getNextArg();
10301 if ("enable".equals(action)) {
10302 setAirplaneMode(true);
10303 return 0;
10304 } else if ("disable".equals(action)) {
10305 setAirplaneMode(false);
10306 return 0;
10307 } else if (action == null) {
10308 final ContentResolver cr = mContext.getContentResolver();
10309 final int enabled = Settings.Global.getInt(cr,
10310 Settings.Global.AIRPLANE_MODE_ON);
10311 pw.println(enabled == 0 ? "disabled" : "enabled");
10312 return 0;
10313 } else {
10314 onHelp();
10315 return -1;
10316 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010317 case "reevaluate":
10318 // Usage : adb shell cmd connectivity reevaluate <netId>
10319 // If netId is omitted, then reevaluate the default network
10320 final String netId = getNextArg();
10321 final NetworkAgentInfo nai;
10322 if (null == netId) {
10323 // Note that the command is running on the wrong thread to call this,
10324 // so this could in principle return stale data. But it can't crash.
10325 nai = getDefaultNetwork();
10326 } else {
10327 // If netId can't be parsed, this throws NumberFormatException, which
10328 // is passed back to adb who prints it.
10329 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
10330 }
10331 if (null == nai) {
10332 pw.println("Unknown network (net ID not found or no default network)");
10333 return 0;
10334 }
10335 Log.d(TAG, "Reevaluating network " + nai.network);
10336 reportNetworkConnectivity(nai.network, !nai.isValidated());
10337 return 0;
mswest4632928412018-03-12 10:34:34 -070010338 default:
10339 return handleDefaultCommands(cmd);
10340 }
10341 } catch (Exception e) {
10342 pw.println(e);
10343 }
10344 return -1;
10345 }
10346
10347 @Override
10348 public void onHelp() {
10349 PrintWriter pw = getOutPrintWriter();
10350 pw.println("Connectivity service commands:");
10351 pw.println(" help");
10352 pw.println(" Print this help text.");
10353 pw.println(" airplane-mode [enable|disable]");
10354 pw.println(" Turn airplane mode on or off.");
10355 pw.println(" airplane-mode");
10356 pw.println(" Get airplane mode.");
10357 }
10358 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010359
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090010360 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010361 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
10362 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
10363 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080010364 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010365 }
10366
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090010367 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
10368 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090010369 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
10370 final TransportInfo newInfo = nc.getTransportInfo();
10371 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
10372 return;
10373 }
10374 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090010375 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090010376 }
10377 }
10378
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010379 /**
10380 * @param connectionInfo the connection to resolve.
10381 * @return {@code uid} if the connection is found and the app has permission to observe it
10382 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
10383 * connection is not found.
10384 */
10385 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010386 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
10387 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
10388 }
10389
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090010390 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010391 connectionInfo.local, connectionInfo.remote);
10392
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010393 if (uid == INVALID_UID) return uid; // Not found.
10394
10395 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
10396 // VPN, if any, that applies to the UID that owns the connection.
10397 if (checkNetworkStackPermission()) return uid;
10398
10399 final NetworkAgentInfo vpn = getVpnForUid(uid);
10400 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090010401 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010402 return INVALID_UID;
10403 }
10404
10405 return uid;
10406 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000010407
Benedict Wong493e04b2018-11-09 14:45:34 -080010408 /**
10409 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
10410 *
10411 * <p>The TestNetworkService must be run in the system server due to TUN creation.
10412 */
10413 @Override
10414 public IBinder startOrGetTestNetworkService() {
10415 synchronized (mTNSLock) {
10416 TestNetworkService.enforceTestNetworkPermissions(mContext);
10417
10418 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080010419 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080010420 }
10421
10422 return mTNS;
10423 }
10424 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080010425
Cody Kesting73708bf2019-12-18 10:57:50 -080010426 /**
10427 * Handler used for managing all Connectivity Diagnostics related functions.
10428 *
10429 * @see android.net.ConnectivityDiagnosticsManager
10430 *
10431 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
10432 */
10433 @VisibleForTesting
10434 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010435 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
10436
Cody Kesting73708bf2019-12-18 10:57:50 -080010437 /**
10438 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
10439 * android.net.ConnectivityDiagnosticsManager}.
10440 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
10441 * NetworkRequestInfo to be registered
10442 */
10443 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
10444
10445 /**
10446 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
10447 * android.net.ConnectivityDiagnosticsManager}.
10448 * obj = the IConnectivityDiagnosticsCallback to be unregistered
10449 * arg1 = the uid of the caller
10450 */
10451 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
10452
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010453 /**
10454 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010455 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010456 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
10457 * NetworkMonitor.
10458 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010459 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010460 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010461
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010462 /**
10463 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
10464 * been detected on the network.
10465 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
10466 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
10467 * arg2 = NetID.
10468 * data = PersistableBundle of extras passed from NetworkMonitor.
10469 */
10470 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
10471
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010472 /**
10473 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
10474 * the platform. This event will invoke {@link
10475 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
10476 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070010477 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010478 */
10479 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
10480
Cody Kesting73708bf2019-12-18 10:57:50 -080010481 private ConnectivityDiagnosticsHandler(Looper looper) {
10482 super(looper);
10483 }
10484
10485 @Override
10486 public void handleMessage(Message msg) {
10487 switch (msg.what) {
10488 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10489 handleRegisterConnectivityDiagnosticsCallback(
10490 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
10491 break;
10492 }
10493 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10494 handleUnregisterConnectivityDiagnosticsCallback(
10495 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
10496 break;
10497 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010498 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010499 final ConnectivityReportEvent reportEvent =
10500 (ConnectivityReportEvent) msg.obj;
10501
Aaron Huang959d3642021-01-21 15:47:41 +080010502 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010503 break;
10504 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010505 case EVENT_DATA_STALL_SUSPECTED: {
10506 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080010507 final Pair<Long, PersistableBundle> arg =
10508 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010509 if (nai == null) break;
10510
Aaron Huang959d3642021-01-21 15:47:41 +080010511 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010512 break;
10513 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010514 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070010515 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010516 break;
10517 }
10518 default: {
10519 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
10520 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010521 }
10522 }
10523 }
10524
10525 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
10526 @VisibleForTesting
10527 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
10528 @NonNull private final IConnectivityDiagnosticsCallback mCb;
10529 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010530 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010531
10532 @VisibleForTesting
10533 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010534 @NonNull IConnectivityDiagnosticsCallback cb,
10535 @NonNull NetworkRequestInfo nri,
10536 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010537 mCb = cb;
10538 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010539 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010540 }
10541
10542 @Override
10543 public void binderDied() {
10544 log("ConnectivityDiagnosticsCallback IBinder died.");
10545 unregisterConnectivityDiagnosticsCallback(mCb);
10546 }
10547 }
10548
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010549 /**
10550 * Class used for sending information from {@link
10551 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
10552 */
10553 private static class NetworkTestedResults {
10554 private final int mNetId;
10555 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010556 @Nullable private final String mRedirectUrl;
10557
10558 private NetworkTestedResults(
10559 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
10560 mNetId = netId;
10561 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010562 mRedirectUrl = redirectUrl;
10563 }
10564 }
10565
10566 /**
10567 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
10568 * ConnectivityDiagnosticsHandler}.
10569 */
10570 private static class ConnectivityReportEvent {
10571 private final long mTimestampMillis;
10572 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080010573 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010574
Aaron Huang959d3642021-01-21 15:47:41 +080010575 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
10576 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010577 mTimestampMillis = timestampMillis;
10578 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080010579 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010580 }
10581 }
10582
Cody Kestingf1120be2020-08-03 18:01:40 -070010583 /**
10584 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
10585 * ConnectivityDiagnosticsHandler}.
10586 */
10587 private static class ReportedNetworkConnectivityInfo {
10588 public final boolean hasConnectivity;
10589 public final boolean isNetworkRevalidating;
10590 public final int reporterUid;
10591 @NonNull public final NetworkAgentInfo nai;
10592
10593 private ReportedNetworkConnectivityInfo(
10594 boolean hasConnectivity,
10595 boolean isNetworkRevalidating,
10596 int reporterUid,
10597 @NonNull NetworkAgentInfo nai) {
10598 this.hasConnectivity = hasConnectivity;
10599 this.isNetworkRevalidating = isNetworkRevalidating;
10600 this.reporterUid = reporterUid;
10601 this.nai = nai;
10602 }
10603 }
10604
Cody Kesting73708bf2019-12-18 10:57:50 -080010605 private void handleRegisterConnectivityDiagnosticsCallback(
10606 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
10607 ensureRunningOnConnectivityServiceThread();
10608
10609 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080010610 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010611 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
10612
James Mattis64b8b0f2020-11-24 17:40:49 -080010613 // Connectivity Diagnostics are meant to be used with a single network request. It would be
10614 // confusing for these networks to change when an NRI is satisfied in another layer.
10615 if (nri.isMultilayerRequest()) {
10616 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
10617 + "network requests.");
10618 }
10619
Cody Kesting73708bf2019-12-18 10:57:50 -080010620 // This means that the client registered the same callback multiple times. Do
10621 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080010622 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010623 if (VDBG) log("Diagnostics callback is already registered");
10624
10625 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10626 // incremented when the NetworkRequestInfo is created as part of
10627 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010628 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080010629 return;
10630 }
10631
Cody Kesting31f1ff62020-03-05 10:46:02 -080010632 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080010633
10634 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080010635 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010636 } catch (RemoteException e) {
10637 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080010638 return;
10639 }
10640
10641 // Once registered, provide ConnectivityReports for matching Networks
10642 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
10643 synchronized (mNetworkForNetId) {
10644 for (int i = 0; i < mNetworkForNetId.size(); i++) {
10645 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080010646 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
10647 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080010648 matchingNetworks.add(nai);
10649 }
10650 }
10651 }
10652 for (final NetworkAgentInfo nai : matchingNetworks) {
10653 final ConnectivityReport report = nai.getConnectivityReport();
10654 if (report == null) {
10655 continue;
10656 }
10657 if (!checkConnectivityDiagnosticsPermissions(
10658 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10659 continue;
10660 }
10661
10662 try {
10663 cb.onConnectivityReportAvailable(report);
10664 } catch (RemoteException e) {
10665 // Exception while sending the ConnectivityReport. Move on to the next network.
10666 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010667 }
10668 }
10669
10670 private void handleUnregisterConnectivityDiagnosticsCallback(
10671 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
10672 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010673 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010674
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010675 final ConnectivityDiagnosticsCallbackInfo cbInfo =
10676 mConnectivityDiagnosticsCallbacks.remove(iCb);
10677 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010678 if (VDBG) log("Removing diagnostics callback that is not currently registered");
10679 return;
10680 }
10681
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010682 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080010683
Cody Kesting70fa2b22020-12-02 12:16:56 -080010684 // Caller's UID must either be the registrants (if they are unregistering) or the System's
10685 // (if the Binder died)
10686 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
10687 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080010688 return;
10689 }
10690
Cody Kesting46cb1672020-03-04 13:35:20 -080010691 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10692 // incremented when the NetworkRequestInfo is created as part of
10693 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010694 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080010695
Cody Kesting31f1ff62020-03-05 10:46:02 -080010696 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010697 }
10698
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010699 private void handleNetworkTestedWithExtras(
10700 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
10701 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080010702 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010703 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010704 final ConnectivityReport report =
10705 new ConnectivityReport(
10706 reportEvent.mNai.network,
10707 reportEvent.mTimestampMillis,
10708 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010709 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010710 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080010711 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070010712
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010713 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010714 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010715 for (final IConnectivityDiagnosticsCallback cb : results) {
10716 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080010717 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010718 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070010719 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010720 }
10721 }
10722 }
10723
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010724 private void handleDataStallSuspected(
10725 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
10726 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080010727 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010728 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010729 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080010730 new DataStallReport(
10731 nai.network,
10732 timestampMillis,
10733 detectionMethod,
10734 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010735 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080010736 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010737 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010738 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010739 for (final IConnectivityDiagnosticsCallback cb : results) {
10740 try {
10741 cb.onDataStallSuspected(report);
10742 } catch (RemoteException ex) {
10743 loge("Error invoking onDataStallSuspected", ex);
10744 }
10745 }
10746 }
10747
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010748 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070010749 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
10750 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
10751 final ConnectivityReport cachedReport = nai.getConnectivityReport();
10752
10753 // If the Network is being re-validated as a result of this call to
10754 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
10755 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010756 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010757 getMatchingPermissionedCallbacks(
10758 nai,
10759 reportedNetworkConnectivityInfo.isNetworkRevalidating
10760 ? Process.INVALID_UID
10761 : reportedNetworkConnectivityInfo.reporterUid);
10762
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010763 for (final IConnectivityDiagnosticsCallback cb : results) {
10764 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070010765 cb.onNetworkConnectivityReported(
10766 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010767 } catch (RemoteException ex) {
10768 loge("Error invoking onNetworkConnectivityReported", ex);
10769 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010770
10771 // If the Network isn't re-validating, also provide the cached report. If there is no
10772 // cached report, the Network is still being validated and a report will be sent once
10773 // validation is complete. Note that networks which never undergo validation will still
10774 // have a cached ConnectivityReport with RESULT_SKIPPED.
10775 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
10776 try {
10777 cb.onConnectivityReportAvailable(cachedReport);
10778 } catch (RemoteException ex) {
10779 loge("Error invoking onConnectivityReportAvailable", ex);
10780 }
10781 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010782 }
10783 }
10784
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010785 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090010786 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
10787 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010788 sanitized.setUids(null);
10789 sanitized.setAdministratorUids(new int[0]);
10790 sanitized.setOwnerUid(Process.INVALID_UID);
10791 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080010792 }
10793
Cody Kestingf1120be2020-08-03 18:01:40 -070010794 /**
10795 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
10796 *
10797 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
10798 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010799 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070010800 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010801 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010802 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010803 mConnectivityDiagnosticsCallbacks.entrySet()) {
10804 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
10805 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070010806
James Mattis64b8b0f2020-11-24 17:40:49 -080010807 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070010808 if (!nai.satisfies(nri.mRequests.get(0))) {
10809 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010810 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010811
10812 // UID for this callback must either be:
10813 // - INVALID_UID (which sends callbacks to all UIDs), or
10814 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
10815 // notified as a result)
10816 if (uid != Process.INVALID_UID && uid != nri.mUid) {
10817 continue;
10818 }
10819
10820 if (!checkConnectivityDiagnosticsPermissions(
10821 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10822 continue;
10823 }
10824
10825 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010826 }
10827 return results;
10828 }
10829
Cody Kesting7474f672021-05-11 14:22:40 -070010830 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
10831 @NonNull NetworkAgentInfo nai) {
10832 // TODO(b/188483916): replace with a transport-agnostic location-aware check
10833 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
10834 }
10835
Cody Kesting160ef392021-05-05 13:17:22 -070010836 private boolean hasLocationPermission(String packageName, int uid) {
10837 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
10838 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
10839 // call in a try-catch.
10840 try {
10841 if (!mLocationPermissionChecker.checkLocationPermission(
10842 packageName, null /* featureId */, uid, null /* message */)) {
10843 return false;
10844 }
10845 } catch (SecurityException e) {
10846 return false;
10847 }
10848
10849 return true;
10850 }
10851
10852 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
10853 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090010854 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070010855 && virtual.networkCapabilities.getOwnerUid() == uid
10856 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
10857 return true;
10858 }
10859 }
10860
10861 return false;
10862 }
10863
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010864 @VisibleForTesting
10865 boolean checkConnectivityDiagnosticsPermissions(
10866 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
10867 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
10868 return true;
10869 }
10870
Cody Kesting160ef392021-05-05 13:17:22 -070010871 // Administrator UIDs also contains the Owner UID
10872 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
10873 if (!CollectionUtils.contains(administratorUids, callbackUid)
10874 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010875 return false;
10876 }
10877
Cody Kesting7474f672021-05-11 14:22:40 -070010878 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
10879 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010880 }
10881
Cody Kestingd199a9d2019-12-17 12:55:28 -080010882 @Override
10883 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010884 @NonNull IConnectivityDiagnosticsCallback callback,
10885 @NonNull NetworkRequest request,
10886 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010887 Objects.requireNonNull(callback, "callback must not be null");
10888 Objects.requireNonNull(request, "request must not be null");
10889 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
10890
Cody Kesting73708bf2019-12-18 10:57:50 -080010891 if (request.legacyType != TYPE_NONE) {
10892 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
10893 + " Please use NetworkCapabilities instead.");
10894 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010895 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080010896 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010897
10898 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
10899 // and administrator uids to be safe.
10900 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080010901 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010902
10903 final NetworkRequest requestWithId =
10904 new NetworkRequest(
10905 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
10906
10907 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
10908 //
10909 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
10910 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
10911 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010912 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080010913 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010914 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010915
10916 mConnectivityDiagnosticsHandler.sendMessage(
10917 mConnectivityDiagnosticsHandler.obtainMessage(
10918 ConnectivityDiagnosticsHandler
10919 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
10920 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010921 }
10922
10923 @Override
10924 public void unregisterConnectivityDiagnosticsCallback(
10925 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010926 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080010927 mConnectivityDiagnosticsHandler.sendMessage(
10928 mConnectivityDiagnosticsHandler.obtainMessage(
10929 ConnectivityDiagnosticsHandler
10930 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010931 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080010932 0,
10933 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010934 }
Cody Kestingf53a0752020-04-15 12:33:28 -070010935
Yan Yanfe96dde2022-12-05 23:00:01 +000010936 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
10937 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
10938 if (underlyingNetworks == null) return false;
10939
10940 for (Network network : underlyingNetworks) {
10941 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
10942 return true;
10943 }
10944 }
10945 return false;
10946 }
10947
Cody Kestingf53a0752020-04-15 12:33:28 -070010948 @Override
10949 public void simulateDataStall(int detectionMethod, long timestampMillis,
10950 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010951 Objects.requireNonNull(network, "network must not be null");
10952 Objects.requireNonNull(extras, "extras must not be null");
10953
paulhu3ffffe72021-09-16 10:15:22 +080010954 enforceAnyPermissionOf(mContext,
10955 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070010956 android.Manifest.permission.NETWORK_STACK);
10957 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000010958 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
10959 throw new SecurityException(
10960 "Data Stall simulation is only possible for test networks or networks built on"
10961 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070010962 }
10963
10964 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000010965 if (nai == null
10966 || (nai.creatorUid != mDeps.getCallingUid()
10967 && nai.creatorUid != Process.SYSTEM_UID)) {
10968 throw new SecurityException(
10969 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070010970 }
10971
Cody Kesting652e3ec2020-05-21 12:08:21 -070010972 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
10973 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
10974 // Data Stall information as a DataStallReportParcelable and passing to
10975 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
10976 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070010977 final DataStallReportParcelable p = new DataStallReportParcelable();
10978 p.timestampMillis = timestampMillis;
10979 p.detectionMethod = detectionMethod;
10980
10981 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
10982 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
10983 }
10984 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
10985 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
10986 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
10987 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
10988 }
10989
Serik Beketayevec8ad212020-12-07 22:43:07 -080010990 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070010991 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010992
lucaslin66f44212021-02-23 01:12:55 +080010993 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
10994 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080010995 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080010996 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080010997 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080010998 }
lucaslin37a16d92021-01-21 19:48:09 +080010999
11000 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011001 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080011002 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080011003 nai.clatd.interfaceLinkStateChanged(iface, up);
11004 }
11005 }
11006
11007 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011008 public void onInterfaceRemoved(@NonNull String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080011009 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080011010 nai.clatd.interfaceRemoved(iface);
11011 }
lucaslin66f44212021-02-23 01:12:55 +080011012 }
11013 }
11014
lucaslin1a8b4c62021-01-21 02:02:55 +080011015 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11016
11017 /**
11018 * Class used for updating network activity tracking with netd and notify network activity
11019 * changes.
11020 */
11021 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011022 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011023 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011024 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080011025 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11026 new RemoteCallbackList<>();
11027 // Indicate the current system default network activity is active or not.
11028 @GuardedBy("mActiveIdleTimers")
11029 private boolean mNetworkActive;
11030 @GuardedBy("mActiveIdleTimers")
Chalard Jean46bfbf02022-02-02 00:56:25 +090011031 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1193a5d2021-01-21 02:04:15 +080011032 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080011033
Chalard Jean46bfbf02022-02-02 00:56:25 +090011034 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080011035 public final int timeout;
11036 public final int transportType;
11037
11038 IdleTimerParams(int timeout, int transport) {
11039 this.timeout = timeout;
11040 this.transportType = transport;
11041 }
11042 }
11043
11044 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080011045 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011046 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080011047 mNetd = netd;
11048 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080011049 }
11050
lucaslin66f44212021-02-23 01:12:55 +080011051 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
11052 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
11053 synchronized (mActiveIdleTimers) {
11054 mNetworkActive = active;
11055 // If there are no idle timers, it means that system is not monitoring
11056 // activity, so the system default network for those default network
11057 // unspecified apps is always considered active.
11058 //
11059 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
11060 // any network activity change event. Whenever this event is received,
11061 // the mActiveIdleTimers should be always not empty. The legacy behavior
11062 // is no-op. Remove to refer to mNetworkActive only.
11063 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
11064 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
11065 }
11066 }
11067 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011068
lucaslin1193a5d2021-01-21 02:04:15 +080011069 // The network activity should only be updated from ConnectivityService handler thread
11070 // when mActiveIdleTimers lock is held.
11071 @GuardedBy("mActiveIdleTimers")
11072 private void reportNetworkActive() {
11073 final int length = mNetworkActivityListeners.beginBroadcast();
11074 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
11075 try {
11076 for (int i = 0; i < length; i++) {
11077 try {
11078 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
11079 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011080 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080011081 }
11082 }
11083 } finally {
11084 mNetworkActivityListeners.finishBroadcast();
11085 }
11086 }
11087
11088 @GuardedBy("mActiveIdleTimers")
11089 public void handleReportNetworkActivity() {
11090 synchronized (mActiveIdleTimers) {
11091 reportNetworkActive();
11092 }
11093 }
11094
lucaslin1a8b4c62021-01-21 02:02:55 +080011095 // This is deprecated and only to support legacy use cases.
11096 private int transportTypeToLegacyType(int type) {
11097 switch (type) {
11098 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011099 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080011100 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011101 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080011102 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011103 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080011104 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011105 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080011106 default:
11107 loge("Unexpected transport in transportTypeToLegacyType: " + type);
11108 }
11109 return ConnectivityManager.TYPE_NONE;
11110 }
11111
11112 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
11113 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
11114 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
11115 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
11116 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
11117 final long ident = Binder.clearCallingIdentity();
11118 try {
11119 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
11120 RECEIVE_DATA_ACTIVITY_CHANGE,
11121 null /* resultReceiver */,
11122 null /* scheduler */,
11123 0 /* initialCode */,
11124 null /* initialData */,
11125 null /* initialExtra */);
11126 } finally {
11127 Binder.restoreCallingIdentity(ident);
11128 }
11129 }
11130
11131 /**
11132 * Setup data activity tracking for the given network.
11133 *
11134 * Every {@code setupDataActivityTracking} should be paired with a
11135 * {@link #removeDataActivityTracking} for cleanup.
11136 */
11137 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
11138 final String iface = networkAgent.linkProperties.getInterfaceName();
11139
11140 final int timeout;
11141 final int type;
11142
11143 if (networkAgent.networkCapabilities.hasTransport(
11144 NetworkCapabilities.TRANSPORT_CELLULAR)) {
11145 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011146 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080011147 10);
11148 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11149 } else if (networkAgent.networkCapabilities.hasTransport(
11150 NetworkCapabilities.TRANSPORT_WIFI)) {
11151 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011152 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080011153 15);
11154 type = NetworkCapabilities.TRANSPORT_WIFI;
11155 } else {
11156 return; // do not track any other networks
11157 }
11158
lucaslinb961efc2021-01-21 02:03:17 +080011159 updateRadioPowerState(true /* isActive */, type);
11160
lucaslin1a8b4c62021-01-21 02:02:55 +080011161 if (timeout > 0 && iface != null) {
11162 try {
lucaslin1193a5d2021-01-21 02:04:15 +080011163 synchronized (mActiveIdleTimers) {
11164 // Networks start up.
11165 mNetworkActive = true;
11166 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
11167 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
11168 reportNetworkActive();
11169 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011170 } catch (Exception e) {
11171 // You shall not crash!
11172 loge("Exception in setupDataActivityTracking " + e);
11173 }
11174 }
11175 }
11176
11177 /**
11178 * Remove data activity tracking when network disconnects.
11179 */
11180 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
11181 final String iface = networkAgent.linkProperties.getInterfaceName();
11182 final NetworkCapabilities caps = networkAgent.networkCapabilities;
11183
lucaslinb961efc2021-01-21 02:03:17 +080011184 if (iface == null) return;
11185
11186 final int type;
11187 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
11188 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11189 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
11190 type = NetworkCapabilities.TRANSPORT_WIFI;
11191 } else {
11192 return; // do not track any other networks
11193 }
11194
11195 try {
11196 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080011197 synchronized (mActiveIdleTimers) {
11198 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
11199 // The call fails silently if no idle timer setup for this interface
11200 mNetd.idletimerRemoveInterface(iface, params.timeout,
11201 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080011202 }
lucaslinb961efc2021-01-21 02:03:17 +080011203 } catch (Exception e) {
11204 // You shall not crash!
11205 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080011206 }
11207 }
11208
11209 /**
11210 * Update data activity tracking when network state is updated.
11211 */
11212 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
11213 NetworkAgentInfo oldNetwork) {
11214 if (newNetwork != null) {
11215 setupDataActivityTracking(newNetwork);
11216 }
11217 if (oldNetwork != null) {
11218 removeDataActivityTracking(oldNetwork);
11219 }
11220 }
lucaslinb961efc2021-01-21 02:03:17 +080011221
11222 private void updateRadioPowerState(boolean isActive, int transportType) {
11223 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
11224 switch (transportType) {
11225 case NetworkCapabilities.TRANSPORT_CELLULAR:
11226 bs.reportMobileRadioPowerState(isActive, NO_UID);
11227 break;
11228 case NetworkCapabilities.TRANSPORT_WIFI:
11229 bs.reportWifiRadioPowerState(isActive, NO_UID);
11230 break;
11231 default:
11232 logw("Untracked transport type:" + transportType);
11233 }
11234 }
lucaslin1193a5d2021-01-21 02:04:15 +080011235
11236 public boolean isDefaultNetworkActive() {
11237 synchronized (mActiveIdleTimers) {
11238 // If there are no idle timers, it means that system is not monitoring activity,
11239 // so the default network is always considered active.
11240 //
11241 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
11242 // tracking is disabled (negative idle timer value configured), or no active default
11243 // network. In the latter case, this reports active but it should report inactive.
11244 return mNetworkActive || mActiveIdleTimers.isEmpty();
11245 }
11246 }
11247
11248 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
11249 mNetworkActivityListeners.register(l);
11250 }
11251
11252 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
11253 mNetworkActivityListeners.unregister(l);
11254 }
lucaslin012f7a12021-01-21 02:04:35 +080011255
11256 public void dump(IndentingPrintWriter pw) {
11257 synchronized (mActiveIdleTimers) {
11258 pw.print("mNetworkActive="); pw.println(mNetworkActive);
11259 pw.println("Idle timers:");
11260 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
11261 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
11262 final IdleTimerParams params = ent.getValue();
11263 pw.print(" timeout="); pw.print(params.timeout);
11264 pw.print(" type="); pw.println(params.transportType);
11265 }
11266 }
11267 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011268 }
James Mattis47db0582021-01-01 14:13:35 -080011269
Daniel Brightf9e945b2020-06-15 16:10:01 -070011270 /**
11271 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
11272 *
11273 * @param socketInfo the socket information
11274 * @param callback the callback to register
11275 */
11276 @Override
11277 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
11278 @NonNull final IQosCallback callback) {
11279 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
11280 if (nai == null || nai.networkCapabilities == null) {
11281 try {
11282 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
11283 } catch (final RemoteException ex) {
11284 loge("registerQosCallbackInternal: RemoteException", ex);
11285 }
11286 return;
11287 }
11288 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
11289 }
11290
11291 /**
11292 * Register a {@link IQosCallback} with base {@link QosFilter}.
11293 *
11294 * @param filter the filter to register
11295 * @param callback the callback to register
11296 * @param nai the agent information related to the filter's network
11297 */
11298 @VisibleForTesting
11299 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
11300 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011301 Objects.requireNonNull(filter, "filter must be non-null");
11302 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011303
11304 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080011305 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
11306 // on this network is unregistered when the app loses permission or b) no QoS
11307 // callbacks are sent for restricted networks unless the app currently has permission
11308 // to access restricted networks.
11309 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070011310 }
11311 mQosCallbackTracker.registerCallback(callback, filter, nai);
11312 }
11313
11314 /**
11315 * Unregisters the given callback.
11316 *
11317 * @param callback the callback to unregister
11318 */
11319 @Override
11320 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011321 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011322 mQosCallbackTracker.unregisterCallback(callback);
11323 }
James Mattis47db0582021-01-01 14:13:35 -080011324
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011325 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
11326 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
11327 // Enterprise device can be fully managed like device owner and such use case
11328 // also should be supported. Calling app check for work profile and fully managed device
11329 // is already done in DevicePolicyManager.
11330 // This check is an extra caution to be sure device is fully managed or not.
11331 final UserManager um = mContext.getSystemService(UserManager.class);
11332 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
11333 if (um.isManagedProfile(profile.getIdentifier())) {
11334 return true;
11335 }
Chalard Jeandf29a852023-05-29 17:02:43 +090011336 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011337 return false;
11338 }
11339
James Mattis45d81842021-01-10 14:24:24 -080011340 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011341 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011342 *
11343 * See the documentation for the individual preferences for a description of the supported
11344 * behaviors.
11345 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011346 * @param profile If the device owner is set, any profile is allowed.
11347 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011348 * @param preferences the list of profile network preferences for the
11349 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011350 * @param listener an optional listener to listen for completion of the operation.
11351 */
11352 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011353 public void setProfileNetworkPreferences(
11354 @NonNull final UserHandle profile,
11355 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090011356 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011357 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011358 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011359
11360 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011361 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
11362 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
11363 .build();
11364 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011365 }
11366
paulhu3ffffe72021-09-16 10:15:22 +080011367 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011368 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011369 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011370 }
11371 if (profile.getIdentifier() < 0) {
11372 throw new IllegalArgumentException("Must explicitly specify a user handle ("
11373 + "UserHandle.CURRENT not supported)");
11374 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011375 if (!isNetworkPreferenceAllowedForProfile(profile)) {
11376 throw new IllegalArgumentException("Profile must be a managed profile "
11377 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011378 }
paulhuaa0743d2021-05-26 21:56:03 +080011379
Chalard Jean0606fc82022-12-14 20:34:43 +090011380 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011381 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011382 for (final ProfileNetworkPreference preference : preferences) {
11383 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011384 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080011385 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011386 switch (preference.getPreference()) {
11387 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
11388 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011389 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011390 if (preference.getPreferenceEnterpriseId() != 0) {
11391 throw new IllegalArgumentException(
11392 "Invalid enterprise identifier in setProfileNetworkPreferences");
11393 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011394 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080011395 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
11396 blockingNonEnterprise = true;
11397 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011398 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
11399 allowFallback = false;
11400 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011401 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011402 // This code is needed even though there is a check later on,
11403 // because isRangeAlreadyInPreferenceList assumes that every preference
11404 // has a UID list.
11405 if (hasDefaultPreference) {
11406 throw new IllegalArgumentException(
11407 "Default profile preference should not be set along with other "
11408 + "preference");
11409 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011410 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
11411 throw new IllegalArgumentException(
11412 "Invalid enterprise identifier in setProfileNetworkPreferences");
11413 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011414 final Set<UidRange> uidRangeSet =
11415 getUidListToBeAppliedForNetworkPreference(profile, preference);
11416 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
11417 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
11418 } else {
11419 throw new IllegalArgumentException(
11420 "Overlapping uid range in setProfileNetworkPreferences");
11421 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011422 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011423 nc.addEnterpriseId(
11424 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011425 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11426 break;
11427 default:
11428 throw new IllegalArgumentException(
11429 "Invalid preference in setProfileNetworkPreferences");
11430 }
Junyu Lai35665cc2022-12-19 17:37:48 +080011431 preferenceList.add(new ProfileNetworkPreferenceInfo(
11432 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011433 if (hasDefaultPreference && preferenceList.size() > 1) {
11434 throw new IllegalArgumentException(
11435 "Default profile preference should not be set along with other preference");
11436 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011437 }
11438 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011439 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011440 }
11441
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011442 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
11443 @NonNull final UserHandle profile,
11444 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
11445 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080011446 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
11447 profileNetworkPreference.getIncludedUids());
11448
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011449 if (uidRangeSet.size() > 0) {
11450 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
11451 throw new IllegalArgumentException(
11452 "Allow uid range is outside the uid range of profile.");
11453 }
11454 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080011455 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011456 profileNetworkPreference.getExcludedUids());
11457 if (disallowUidRangeSet.size() > 0) {
11458 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
11459 throw new IllegalArgumentException(
11460 "disallow uid range is outside the uid range of profile.");
11461 }
11462 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
11463 disallowUidRangeSet);
11464 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011465 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011466 uidRangeSet.add(profileUids);
11467 }
11468 }
11469 return uidRangeSet;
11470 }
11471
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011472 private boolean isEnterpriseIdentifierValid(
11473 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011474 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011475 return true;
11476 }
11477 return false;
11478 }
11479
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011480 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090011481 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011482 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090011483 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011484 // The NRI for a user should contain the request for capabilities.
11485 // If fallback to default network is needed then NRI should include
11486 // the request for the default network. Create an image of it to
11487 // have the correct UIDs in it (also a request can only be part of one NRI, because
11488 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011489 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
11490 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011491 if (pref.allowFallback) {
11492 nrs.add(createDefaultInternetRequestForTransport(
11493 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11494 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011495 if (VDBG) {
11496 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
11497 pref.capabilities.getUids()));
11498 }
11499
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011500 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080011501 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080011502 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011503 result.add(nri);
11504 }
11505 return result;
11506 }
11507
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011508 /**
11509 * Compare if the given UID range sets have the same UIDs.
11510 *
11511 */
11512 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090011513 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011514 @NonNull Set<UidRange> uidRangeSet) {
11515 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
11516 return false;
11517 }
Chalard Jean0606fc82022-12-14 20:34:43 +090011518 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011519 if (UidRangeUtils.doesRangeSetOverlap(
11520 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
11521 return true;
11522 }
11523 }
11524 return false;
11525 }
11526
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011527 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090011528 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011529 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011530 /*
11531 * handleSetProfileNetworkPreference is always called for single user.
11532 * preferenceList only contains preferences for different uids within the same user
11533 * (enforced by getUidListToBeAppliedForNetworkPreference).
11534 * Clear all the existing preferences for the user before applying new preferences.
11535 *
11536 */
Chalard Jean0606fc82022-12-14 20:34:43 +090011537 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
11538 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011539 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
11540 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011541
paulhu74128522021-09-28 02:29:03 +000011542 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
11543 addPerAppDefaultNetworkRequests(
11544 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080011545 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080011546
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011547 // Finally, rematch.
11548 rematchAllNetworksAndRequests();
11549
11550 if (null != listener) {
11551 try {
11552 listener.onComplete();
11553 } catch (RemoteException e) {
11554 loge("Listener for setProfileNetworkPreference has died");
11555 }
11556 }
11557 }
11558
paulhu51f77dc2021-06-07 02:34:20 +000011559 @VisibleForTesting
11560 @NonNull
11561 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
11562 @NonNull final Set<Integer> uids) {
11563 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11564 if (uids.size() == 0) {
11565 // Should not create NetworkRequestInfo if no preferences. Without uid range in
11566 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
11567 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
11568 return nris;
11569 }
11570
11571 final List<NetworkRequest> requests = new ArrayList<>();
11572 // The NRI should be comprised of two layers:
11573 // - The request for the mobile network preferred.
11574 // - The request for the default network, for fallback.
11575 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090011576 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000011577 requests.add(createDefaultInternetRequestForTransport(
11578 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11579 final Set<UidRange> ranges = new ArraySet<>();
11580 for (final int uid : uids) {
11581 ranges.add(new UidRange(uid, uid));
11582 }
11583 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080011584 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080011585 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000011586 return nris;
11587 }
11588
11589 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000011590 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000011591 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
11592 addPerAppDefaultNetworkRequests(
11593 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000011594 // Finally, rematch.
11595 rematchAllNetworksAndRequests();
11596 }
11597
Patrick Rohr2857ac42022-01-21 14:58:16 +010011598 private void handleIngressRateLimitChanged() {
11599 final long oldIngressRateLimit = mIngressRateLimit;
11600 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
11601 mContext);
11602 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
11603 if (canNetworkBeRateLimited(networkAgent)) {
11604 // If rate limit has previously been enabled, remove the old limit first.
11605 if (oldIngressRateLimit >= 0) {
11606 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
11607 }
11608 if (mIngressRateLimit >= 0) {
11609 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
11610 mIngressRateLimit);
11611 }
11612 }
11613 }
11614 }
11615
11616 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090011617 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090011618 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090011619
Patrick Rohrff3b3f82022-02-09 15:15:52 +010011620 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
11621 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
11622 // internet connectivity can be rate limited.
11623 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
11624 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010011625 return false;
11626 }
11627
11628 final String iface = networkAgent.linkProperties.getInterfaceName();
11629 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010011630 // This may happen in tests, but if there is no interface then there is nothing that
11631 // can be rate limited.
11632 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010011633 return false;
11634 }
11635 return true;
11636 }
11637
James Mattis45d81842021-01-10 14:24:24 -080011638 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080011639 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
11640 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080011641 }
11642
11643 /**
11644 * Used by automotive devices to set the network preferences used to direct traffic at an
11645 * application level as per the given OemNetworkPreferences. An example use-case would be an
11646 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
11647 * vehicle via a particular network.
11648 *
11649 * Calling this will overwrite the existing preference.
11650 *
James Mattisda32cfe2021-01-26 16:23:52 -080011651 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090011652 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080011653 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080011654 */
James Mattis47db0582021-01-01 14:13:35 -080011655 @Override
James Mattis45d81842021-01-10 14:24:24 -080011656 public void setOemNetworkPreference(
11657 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011658 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080011659
James Mattisfa270db2021-05-31 17:11:10 -070011660 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11661 // Only bypass the permission/device checks if this is a valid test request.
11662 if (isValidTestOemNetworkPreference(preference)) {
11663 enforceManageTestNetworksPermission();
11664 } else {
11665 enforceAutomotiveDevice();
11666 enforceOemNetworkPreferencesPermission();
11667 validateOemNetworkPreferences(preference);
11668 }
James Mattis45d81842021-01-10 14:24:24 -080011669
James Mattis45d81842021-01-10 14:24:24 -080011670 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
11671 new Pair<>(preference, listener)));
11672 }
11673
James Mattisfa270db2021-05-31 17:11:10 -070011674 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000011675 * Sets the specified UIDs to get/receive the VPN as the only default network.
11676 *
11677 * Calling this will overwrite the existing network preference for this session, and the
11678 * specified UIDs won't get any default network when no VPN is connected.
11679 *
11680 * @param session The VPN session which manages the passed UIDs.
11681 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
11682 * setting for this session if the array is empty. Null is not allowed, the
11683 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
11684 * @hide
11685 */
11686 @Override
11687 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
11688 Objects.requireNonNull(ranges);
11689 enforceNetworkStackOrSettingsPermission();
11690 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
11691 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
11692 throw new IllegalArgumentException(
11693 "setVpnNetworkPreference: Passed UID ranges overlap");
11694 }
11695
11696 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
11697 new VpnNetworkPreferenceInfo(session,
11698 new ArraySet<UidRange>(Arrays.asList(ranges)))));
11699 }
11700
11701 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
11702 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
11703
11704 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
11705 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
11706
11707 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
11708 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
11709 // Finally, rematch.
11710 rematchAllNetworksAndRequests();
11711 }
11712
11713 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
11714 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
11715 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11716 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
11717 final List<NetworkRequest> requests = new ArrayList<>();
11718 // Request VPN only, so other networks won't be the fallback options when VPN is not
11719 // connected temporarily.
11720 requests.add(createVpnRequest());
11721 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
11722 setNetworkRequestUids(requests, uidRanges);
11723 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
11724 }
11725 return nris;
11726 }
11727
11728 /**
James Mattisfa270db2021-05-31 17:11:10 -070011729 * Check the validity of an OEM network preference to be used for testing purposes.
11730 * @param preference the preference to validate
11731 * @return true if this is a valid OEM network preference test request.
11732 */
11733 private boolean isValidTestOemNetworkPreference(
11734 @NonNull final OemNetworkPreferences preference) {
11735 // Allow for clearing of an existing OemNetworkPreference used for testing.
11736 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
11737 // changes after this check is complete. This is an unlikely scenario as calling of this API
11738 // is controlled by the OEM therefore the added complexity is not worth adding given those
11739 // circumstances. That said, it is an edge case to be aware of hence this comment.
11740 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
11741 && isTestOemNetworkPreference(mOemNetworkPreferences);
11742 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
11743 }
11744
11745 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
11746 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
11747 return prefMap.size() == 1
11748 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
11749 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
11750 }
11751
James Mattis45d81842021-01-10 14:24:24 -080011752 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
11753 for (@OemNetworkPreferences.OemNetworkPreference final int pref
11754 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070011755 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
11756 throw new IllegalArgumentException(
11757 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
11758 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080011759 }
11760 }
11761 }
11762
11763 private void handleSetOemNetworkPreference(
11764 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011765 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080011766 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11767 if (DBG) {
11768 log("set OEM network preferences :" + preference.toString());
11769 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011770
James Mattiscb1e0362021-04-06 17:07:42 -070011771 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000011772 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
11773 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
11774 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080011775 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080011776
11777 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011778 try {
11779 listener.onComplete();
11780 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080011781 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011782 }
James Mattis45d81842021-01-10 14:24:24 -080011783 }
11784 }
11785
paulhu74128522021-09-28 02:29:03 +000011786 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080011787 // Skip the requests which are set by other network preference. Because the uid range rules
11788 // should stay in netd.
11789 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080011790 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080011791 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080011792 }
11793
James Mattis3ce3d3c2021-02-09 18:18:28 -080011794 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
11795 ensureRunningOnConnectivityServiceThread();
11796 mDefaultNetworkRequests.addAll(nris);
11797 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
11798 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080011799 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000011800 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
11801 nrisToRegister.addAll(
11802 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
11803 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011804 }
11805
11806 /**
11807 * All current requests that are tracking the default network need to be assessed as to whether
11808 * or not the current set of per-application default requests will be changing their default
11809 * network. If so, those requests will need to be updated so that they will send callbacks for
11810 * default network changes at the appropriate time. Additionally, those requests tracking the
11811 * default that were previously updated by this flow will need to be reassessed.
11812 * @return the nris which will need to be updated.
11813 */
11814 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
11815 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
11816 // Get the distinct nris to check since for multilayer requests, it is possible to have the
11817 // same nri in the map's values for each of its NetworkRequest objects.
11818 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080011819 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011820 // Include this nri if it is currently being tracked.
11821 if (isPerAppTrackedNri(nri)) {
11822 defaultCallbackRequests.add(nri);
11823 continue;
11824 }
11825 // We only track callbacks for requests tracking the default.
11826 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
11827 continue;
11828 }
11829 // Include this nri if it will be tracked by the new per-app default requests.
11830 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011831 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080011832 if (isNriGoingToBeTracked) {
11833 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080011834 }
11835 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080011836 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080011837 }
11838
James Mattis3ce3d3c2021-02-09 18:18:28 -080011839 /**
11840 * Create nris for those network requests that are currently tracking the default network that
11841 * are being controlled by a per-application default.
11842 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
11843 * foundation when creating the nri. Important items include the calling uid's original
11844 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
11845 * requests are assumed to have already been validated as needing to be updated.
11846 * @return the Set of nris to use when registering network requests.
11847 */
11848 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
11849 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
11850 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
11851 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
11852 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011853 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011854
Chalard Jean9473c982021-07-29 20:03:04 +090011855 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080011856 if (trackingNri == mDefaultRequest) {
11857 callbackRequestsToRegister.add(new NetworkRequestInfo(
11858 callbackRequest,
11859 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
11860 continue;
11861 }
11862
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011863 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011864 callbackRequestsToRegister.add(new NetworkRequestInfo(
11865 callbackRequest,
11866 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011867 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090011868 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080011869 }
11870 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080011871 }
11872
Chalard Jean17215832021-03-01 14:06:28 +090011873 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
11874 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090011875 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011876 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090011877 }
11878 }
11879
James Mattis45d81842021-01-10 14:24:24 -080011880 /**
11881 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
11882 */
11883 @VisibleForTesting
11884 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011885 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080011886 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011887 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080011888 final SparseArray<Set<Integer>> uids =
11889 createUidsFromOemNetworkPreferences(preference);
11890 for (int i = 0; i < uids.size(); i++) {
11891 final int key = uids.keyAt(i);
11892 final Set<Integer> value = uids.valueAt(i);
11893 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
11894 // No need to add an nri without any requests.
11895 if (0 == nri.mRequests.size()) {
11896 continue;
11897 }
11898 nris.add(nri);
11899 }
11900
11901 return nris;
11902 }
11903
11904 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
11905 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070011906 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080011907 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080011908 final List<UserHandle> users =
11909 mContext.getSystemService(UserManager.class).getUserHandles(true);
11910 if (null == users || users.size() == 0) {
11911 if (VDBG || DDBG) {
11912 log("No users currently available for setting the OEM network preference.");
11913 }
James Mattisb6b6a432021-06-01 22:30:36 -070011914 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080011915 }
James Mattis45d81842021-01-10 14:24:24 -080011916 for (final Map.Entry<String, Integer> entry :
11917 preference.getNetworkPreferences().entrySet()) {
11918 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070011919 // Add the rules for all users as this policy is device wide.
11920 for (final UserHandle user : users) {
11921 try {
11922 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
11923 if (!prefToUids.contains(pref)) {
11924 prefToUids.put(pref, new ArraySet<>());
11925 }
11926 prefToUids.get(pref).add(uid);
11927 } catch (PackageManager.NameNotFoundException e) {
11928 // Although this may seem like an error scenario, it is ok that uninstalled
11929 // packages are sent on a network preference as the system will watch for
11930 // package installations associated with this network preference and update
11931 // accordingly. This is done to minimize race conditions on app install.
11932 continue;
James Mattis45d81842021-01-10 14:24:24 -080011933 }
James Mattis45d81842021-01-10 14:24:24 -080011934 }
11935 }
James Mattisb6b6a432021-06-01 22:30:36 -070011936 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080011937 }
11938
11939 private NetworkRequestInfo createNriFromOemNetworkPreferences(
11940 @OemNetworkPreferences.OemNetworkPreference final int preference,
11941 @NonNull final Set<Integer> uids) {
11942 final List<NetworkRequest> requests = new ArrayList<>();
11943 // Requests will ultimately be evaluated by order of insertion therefore it matters.
11944 switch (preference) {
11945 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
11946 requests.add(createUnmeteredNetworkRequest());
11947 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070011948 requests.add(createDefaultInternetRequestForTransport(
11949 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080011950 break;
11951 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
11952 requests.add(createUnmeteredNetworkRequest());
11953 requests.add(createOemPaidNetworkRequest());
11954 break;
11955 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
11956 requests.add(createOemPaidNetworkRequest());
11957 break;
11958 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
11959 requests.add(createOemPrivateNetworkRequest());
11960 break;
James Mattisfa270db2021-05-31 17:11:10 -070011961 case OEM_NETWORK_PREFERENCE_TEST:
11962 requests.add(createUnmeteredNetworkRequest());
11963 requests.add(createTestNetworkRequest());
11964 requests.add(createDefaultRequest());
11965 break;
11966 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
11967 requests.add(createTestNetworkRequest());
11968 break;
James Mattis45d81842021-01-10 14:24:24 -080011969 default:
11970 // This should never happen.
11971 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
11972 + " called with invalid preference of " + preference);
11973 }
11974
James Mattisfa270db2021-05-31 17:11:10 -070011975 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090011976 for (final int uid : uids) {
11977 ranges.add(new UidRange(uid, uid));
11978 }
11979 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080011980 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080011981 }
11982
11983 private NetworkRequest createUnmeteredNetworkRequest() {
11984 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11985 .addCapability(NET_CAPABILITY_NOT_METERED)
11986 .addCapability(NET_CAPABILITY_VALIDATED);
11987 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
11988 }
11989
11990 private NetworkRequest createOemPaidNetworkRequest() {
11991 // NET_CAPABILITY_OEM_PAID is a restricted capability.
11992 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11993 .addCapability(NET_CAPABILITY_OEM_PAID)
11994 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11995 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11996 }
11997
11998 private NetworkRequest createOemPrivateNetworkRequest() {
11999 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
12000 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12001 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
12002 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12003 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12004 }
12005
12006 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070012007 final NetworkCapabilities netcap = new NetworkCapabilities();
12008 netcap.addCapability(NET_CAPABILITY_INTERNET);
12009 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
12010 return netcap;
12011 }
12012
12013 private NetworkRequest createTestNetworkRequest() {
12014 final NetworkCapabilities netcap = new NetworkCapabilities();
12015 netcap.clearAll();
12016 netcap.addTransportType(TRANSPORT_TEST);
12017 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080012018 }
James Mattis47db0582021-01-01 14:13:35 -080012019 }
markchien738ad912021-12-09 18:15:45 +080012020
12021 @Override
12022 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
12023 enforceNetworkStackOrSettingsPermission();
12024
12025 try {
12026 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012027 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012028 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012029 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012030 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012031 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012032 throw new IllegalStateException(e);
12033 }
12034 }
12035
12036 @Override
12037 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
12038 enforceNetworkStackOrSettingsPermission();
12039
12040 try {
12041 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012042 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012043 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012044 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012045 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012046 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012047 throw new IllegalStateException(e);
12048 }
12049 }
markchiene1561fa2021-12-09 22:00:56 +080012050
12051 @Override
markchien3c04e662022-03-22 16:29:56 +080012052 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080012053 enforceNetworkStackOrSettingsPermission();
12054
markchien3c04e662022-03-22 16:29:56 +080012055 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
12056 int firewallRule = getFirewallRuleType(chain, rule);
12057
12058 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
12059 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
12060 }
12061
markchiene1561fa2021-12-09 22:00:56 +080012062 try {
markchien3c04e662022-03-22 16:29:56 +080012063 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012064 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080012065 throw new IllegalStateException(e);
12066 }
12067 }
markchien98a6f952022-01-13 23:43:53 +080012068
Motomu Utsumi900b8062023-01-19 16:16:49 +090012069 @Override
12070 public int getUidFirewallRule(final int chain, final int uid) {
12071 enforceNetworkStackOrSettingsPermission();
12072 return mBpfNetMaps.getUidRule(chain, uid);
12073 }
12074
markchien3c04e662022-03-22 16:29:56 +080012075 private int getFirewallRuleType(int chain, int rule) {
12076 final int defaultRule;
12077 switch (chain) {
12078 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000012079 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
12080 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000012081 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080012082 defaultRule = FIREWALL_RULE_ALLOW;
12083 break;
12084 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
12085 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
12086 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
12087 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
12088 defaultRule = FIREWALL_RULE_DENY;
12089 break;
12090 default:
12091 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
12092 }
12093 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
12094
12095 return rule;
12096 }
12097
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012098 private void closeSocketsForFirewallChainLocked(final int chain)
12099 throws ErrnoException, SocketException, InterruptedIOException {
12100 if (mBpfNetMaps.isFirewallAllowList(chain)) {
12101 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
12102 // So, close all non-system socket owned by uids that are not explicitly allowed
12103 Set<Range<Integer>> ranges = new ArraySet<>();
12104 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
12105 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
12106 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
12107 } else {
12108 // Denylist means the firewall allows all by default, uids must be explicitly denied
12109 // So, close socket owned by uids that are explicitly denied
12110 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
12111 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
12112 }
12113 }
12114
markchien98a6f952022-01-13 23:43:53 +080012115 @Override
12116 public void setFirewallChainEnabled(final int chain, final boolean enable) {
12117 enforceNetworkStackOrSettingsPermission();
12118
12119 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012120 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012121 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080012122 throw new IllegalStateException(e);
12123 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012124
Chalard Jeandf29a852023-05-29 17:02:43 +090012125 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090012126 try {
12127 closeSocketsForFirewallChainLocked(chain);
12128 } catch (ErrnoException | SocketException | InterruptedIOException e) {
12129 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
12130 }
12131 }
markchien98a6f952022-01-13 23:43:53 +080012132 }
12133
markchien00a0bed2022-01-13 23:46:13 +080012134 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012135 public boolean getFirewallChainEnabled(final int chain) {
12136 enforceNetworkStackOrSettingsPermission();
12137
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000012138 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012139 }
12140
12141 @Override
markchien00a0bed2022-01-13 23:46:13 +080012142 public void replaceFirewallChain(final int chain, final int[] uids) {
12143 enforceNetworkStackOrSettingsPermission();
12144
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000012145 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080012146 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080012147
12148 @Override
12149 public IBinder getCompanionDeviceManagerProxyService() {
12150 enforceNetworkStackPermission(mContext);
12151 return mCdmps;
12152 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070012153}