blob: 33c01949f163e16e182247928df63bd1b5477204 [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 Fasheh7501e762023-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;
Aaron Huang25ef1712021-06-08 13:11:45 +080037import static android.net.ConnectivityManager.CALLBACK_IP_CHANGED;
Jeff Sharkey971cd162011-08-29 16:02:57 -070038import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
markchien3c04e662022-03-22 16:29:56 +080039import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
40import static android.net.ConnectivityManager.FIREWALL_RULE_DEFAULT;
41import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090042import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090043import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090044import static android.net.ConnectivityManager.TYPE_MOBILE;
45import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
46import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
47import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
48import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
49import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
50import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
51import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
52import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
53import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070054import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090055import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070056import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090057import static android.net.ConnectivityManager.TYPE_WIFI;
58import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070059import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070060import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080061import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080062import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080063import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070064import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080065import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen53f08952015-06-16 14:27:36 -040066import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090067import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090068import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090069import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090070import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090071import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
72import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060073import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090074import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080075import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090076import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080077import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
78import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080079import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090080import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080081import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
82import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080083import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
84import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
85import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090086import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090087import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060088import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070089import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080090import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090091import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070092import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
93import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070094import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080095import static android.os.Process.VPN_UID;
Motomu Utsumi6f4d8062023-04-21 12:35:22 +090096import static android.provider.DeviceConfig.NAMESPACE_TETHERING;
Patrick Rohr2857ac42022-01-21 14:58:16 +010097import static android.system.OsConstants.ETH_P_ALL;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070098import static android.system.OsConstants.IPPROTO_TCP;
99import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey07e19362017-10-27 17:22:59 -0600100
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900101import static com.android.net.module.util.DeviceConfigUtils.TETHERING_MODULE_NAME;
Xiao Ma60142372022-07-16 17:30:20 +0900102import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Junyu Lai4c6fe232023-04-11 11:33:46 +0800103import static com.android.net.module.util.PermissionUtils.checkAnyPermissionOf;
paulhu3ffffe72021-09-16 10:15:22 +0800104import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
105import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
106import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900107
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800108import static java.util.Map.Entry;
109
Chalard Jean5b639762020-03-09 21:25:37 +0900110import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000111import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800112import android.annotation.Nullable;
Michael Groover73f69482023-01-27 11:01:25 -0600113import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800114import android.annotation.TargetApi;
Mark Fasheh7501e762023-05-04 20:23:11 +0000115import android.app.ActivityManager;
116import android.app.ActivityManager.UidFrozenStateChangedCallback;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800117import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800118import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700119import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700120import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900121import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800122import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700123import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800124import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800125import android.content.ContentResolver;
126import android.content.Context;
127import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700128import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800129import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900130import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700131import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900132import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900133import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700134import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800135import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800136import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800137import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900138import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800139import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900140import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800141import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900142import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800143import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700144import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900145import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800146import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800147import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800148import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800149import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800150import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900151import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900152import android.net.INetworkMonitor;
153import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900154import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900155import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700156import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800157import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900158import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900159import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900160import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800161import android.net.LinkProperties;
Charles He9369e612017-05-15 17:07:18 +0100162import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800163import android.net.NativeNetworkConfig;
164import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800165import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700166import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700167import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900168import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700169import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800170import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700171import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900172import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900173import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000174import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900175import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700176import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900177import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700178import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900179import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700180import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800181import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900182import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700183import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000184import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800185import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900186import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800187import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400188import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700189import android.net.QosCallbackException;
190import android.net.QosFilter;
191import android.net.QosSocketFilter;
192import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700193import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800194import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800195import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800196import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900197import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400198import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800199import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800200import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400201import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800202import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900203import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900204import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900205import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900206import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800207import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900208import android.net.networkstack.ModuleNetworkStackClient;
209import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900210import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800211import android.net.resolv.aidl.DnsHealthEventParcel;
212import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
213import android.net.resolv.aidl.Nat64PrefixEventParcel;
214import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900215import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900216import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800217import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800218import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800219import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700220import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000221import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800222import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700223import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700224import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800225import android.os.Looper;
226import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700227import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700228import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900229import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800230import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700231import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700232import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800233import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700234import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900235import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900236import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700237import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700238import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400239import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800240import android.provider.Settings;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900241import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700242import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700243import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700244import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800245import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900246import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000247import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600248import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900249import android.util.Pair;
Motomu Utsumia20f7602023-03-16 17:04:21 +0900250import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700251import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700252import android.util.SparseIntArray;
Tommy Webb34f81dc2023-02-20 14:10:55 -0500253import android.util.SparseLongArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800254
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800255import androidx.annotation.RequiresApi;
256
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900257import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400258import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400259import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700260import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900261import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800262import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900263import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800264import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000265import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900266import com.android.net.module.util.BitUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900267import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900268import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100269import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900270import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
271import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900272import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800273import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800274import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100275import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000276import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800277import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
278import com.android.networkstack.apishim.ConstantsShim;
279import com.android.networkstack.apishim.common.BroadcastOptionsShim;
280import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900281import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900282import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000283import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900284import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800285import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800286import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900287import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VAN6ca02962023-02-20 20:10:09 +0900288import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900289import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500290import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700291import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900292import com.android.server.connectivity.FullScore;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900293import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VAN6ca02962023-02-20 20:10:09 +0900294import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000295import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100296import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700297import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900298import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700299import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600300import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900301import com.android.server.connectivity.NetworkNotificationManager;
302import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900303import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900304import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900305import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700306import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900307import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900308import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700309import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800310import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000311import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800312import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600313
Josh Gao461a1222020-06-16 15:58:11 -0700314import libcore.io.IoUtils;
315
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900316import org.xmlpull.v1.XmlPullParserException;
317
The Android Open Source Project28527d22009-03-03 19:31:44 -0800318import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100319import java.io.IOException;
Motomu Utsumia20f7602023-03-16 17:04:21 +0900320import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800321import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900322import java.io.Writer;
Jean Chalard01a7d322023-06-27 08:54:23 +0000323import java.lang.IllegalArgumentException;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700324import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700325import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900326import java.net.InetSocketAddress;
Motomu Utsumia20f7602023-03-16 17:04:21 +0900327import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700328import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700329import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700330import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700331import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800332import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900333import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800334import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700335import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700336import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700337import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700338import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900339import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700340import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900341import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600342import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900343import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600344import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900345import java.util.concurrent.atomic.AtomicInteger;
Tommy Webb34f81dc2023-02-20 14:10:55 -0500346import java.util.stream.Collectors;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800347
348/**
349 * @hide
350 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800351public class ConnectivityService extends IConnectivityManager.Stub
352 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900353 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800354
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900355 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900356 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900357 private static final String NETWORK_ARG = "networks";
358 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800359 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900360
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900361 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900362 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
363 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800364
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900365 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700366
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100367 /**
368 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
369 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800370 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100371 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
372 * (preferably via runtime resource overlays).
373 */
374 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
375 "http://connectivitycheck.gstatic.com/generate_204";
376
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700377 // TODO: create better separation between radio types and network types
378
Robert Greenwalt2034b912009-08-12 16:08:25 -0700379 // how long to wait before switching back to a radio's default network
380 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
381 // system property that can override the above value
382 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
383 "android.telephony.apn-restore";
384
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900385 // How long to wait before putting up a "This network doesn't have an Internet connection,
386 // connect anyway?" dialog after the user selects a network that doesn't validate.
387 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
388
Chalard Jean5fb43c72022-09-08 19:03:14 +0900389 // How long to wait before considering that a network is bad in the absence of any form
390 // of connectivity (valid, partial, captive portal). If none has been detected after this
391 // delay, the stack considers this network bad, which may affect how it's handled in ranking
392 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900393 // Timeout in case the "actively prefer bad wifi" feature is on
394 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
395 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean3f0ff5b2023-06-05 19:26:17 +0900396 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900397
junyulai0ac374f2020-12-14 18:41:52 +0800398 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900399 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
400 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800401 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700402
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800403 // Delimiter used when creating the broadcast delivery group for sending
404 // CONNECTIVITY_ACTION broadcast.
405 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
406
he_won.hwang881307a2022-03-15 21:23:52 +0900407 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900408 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900409
Daniel Brightf9e945b2020-06-15 16:10:01 -0700410 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900411 @VisibleForTesting
412 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700413
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900414 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700415 @VisibleForTesting
416 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900417
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900418 @VisibleForTesting
419 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800420 @VisibleForTesting
421 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900422 // True if the cell radio of the device is capable of time-sharing.
423 @VisibleForTesting
424 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900425
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800426 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800427 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800428 private final int mReleasePendingIntentDelayMs;
429
Chalard Jean46bfbf02022-02-02 00:56:25 +0900430 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900431
Motomu Utsumif360aa62023-01-30 17:52:20 +0900432 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700433
Chalard Jean9473c982021-07-29 20:03:04 +0900434 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800435 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700436 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800437 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700438
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900439 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700440
junyulaif2c67e42018-08-07 19:50:45 +0800441 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000442 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
443 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800444 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900445 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800446
Tommy Webb34f81dc2023-02-20 14:10:55 -0500447 /** Map of UID to its bit-packed allowed transports. */
448 private SparseLongArray mUidAllowedTransports = new SparseLongArray();
449
450 /** Allowed UID ranges provided to Netd, tracked based on the netId to which they belong. */
451 @GuardedBy("mNetworkForNetId")
452 private Map<Integer, NativeUidRangeConfig> mNetIdToAllowlist =
453 new HashMap<Integer, NativeUidRangeConfig>();
454
455 /**
456 * UIDs that we wish to be denied access to networks based on certain policies, grouped by the
457 * netId to which they belong. Used to prevent affected UIDs from getting online through a VPN
458 * or from receiving incoming traffic when their active network is denied to them.
459 */
460 @GuardedBy("mNetworkForNetId")
461 private Map<Integer, List<Integer>> mNetIdToDisallowedUids = new HashMap<>();
462
463 private void setUidsAllowedTransports(@NonNull final int[] uids,
464 @NonNull final long[] allowedTransportsPacked) {
465 mHandler.post(() -> handleSetUidsAllowedTransports(uids, allowedTransportsPacked));
466 }
467
468 private void handleSetUidsAllowedTransports(@NonNull final int[] uids,
469 @NonNull final long[] allowedTransportsPacked) {
470 for (int i = 0; i < uids.length; i++) {
471 final int uid = uids[i];
472 final long transportsPacked = allowedTransportsPacked[i];
473 mUidAllowedTransports.put(uid, transportsPacked);
474 }
475 if (DDBG) Log.d(TAG, "setUidsAllowedTransports: Processing " + uids.length + " UIDs...");
476 for (final var nai : mNetworkAgentInfos) {
477 updateDisallowedUidsForNetwork(nai);
478 if (nai.isVPN()) {
479 // VPNs manage their own allowed UID ranges, so we handle them via denylist above.
480 continue;
481 }
482 for (final int uid : uids) {
483 if (nai.networkCapabilities.appliesToUid(uid)) {
484 updateAllowedUidsForNetwork(nai);
485 break;
486 }
487 }
488 }
489 if (DDBG) Log.d(TAG, "setUidsAllowedTransports: Processed " + uids.length + " UIDs.");
490 }
491
492 // The last UID denylist that we supplied to BPF.
493 // To support access across threads, do not modify after assignment.
494 private Set<Integer> mLastDisallowedUidsDenylist = Set.of();
495
496 /**
497 * Computes which policies apply to the given network to determine which UIDs should be
498 * prevented from accessing that network. Then, for each network with disallowed UIDs, checks
499 * whether the network is currently the active network for the UID, and if so, prevents the
500 * UID from accessing networks entirely via a denylist. Without this, UIDs are able to use VPNs
501 * even if their policy disallows it, because the VPN itself manages its allowed UID ranges.
502 * Additionally, this prevents incoming traffic for UIDs whose active network is disallowed.
503 *
504 * NOTE: UIDs with restricted networking permission are never disallowed.
505 */
506 private void updateDisallowedUidsForNetwork(@NonNull final NetworkAgentInfo nai) {
507 ensureRunningOnConnectivityServiceThread();
508
509 final var netId = nai.network.netId;
510 final var ourTag = "updateDisallowedUidsForNetwork(" + netId + "): ";
511 if (DDBG) Log.d(TAG, ourTag + "begin");
512 final var disallowedUids = getUidsDisallowedByPolicyForNetwork(nai);
513 final Set<Integer> prevDenylist;
514 final Set<Integer> newDenylist = new ArraySet<Integer>();
515 synchronized (mNetworkForNetId) {
516 prevDenylist = mLastDisallowedUidsDenylist;
517 if (mNetworkForNetId.contains(netId)) {
518 // Only store the disallowed UIDs if this network still exists.
519 mNetIdToDisallowedUids.put(netId, disallowedUids);
520 }
521 for (final var entry : mNetIdToDisallowedUids.entrySet()) {
522 final var entryNetId = entry.getKey();
523 final var entryDisallowedUids = entry.getValue();
524 entryDisallowedUids.forEach(uid -> {
525 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
526 // Skip denylist for UIDs with restricted networks permission.
527 return;
528 }
529 // Disallowing UIDs is only applicable if the network is the UID's active
530 // network. For us, a VPN that is still connecting should still be considered,
531 // because it is *about* to become the active network, and we are reacting
532 // early. If we do not include connecting VPNs, we get no result.
533 // Also, if we don't know the active network, denying is fine for now.
534 final var activeNetwork = getActiveNetworkOrConnectingVpnForUidInternal(
535 uid, true /* ignoreBlocked */);
536 if (activeNetwork == null || entryNetId == activeNetwork.netId) {
537 newDenylist.add(uid);
538 }
539 });
540 }
541 mLastDisallowedUidsDenylist = Collections.unmodifiableSet(newDenylist);
542 }
543 // NOTE: Setting UID rules individually is exponentially faster than replacing the whole
544 // firewall chain for some reason (<1ms vs 10+ms, even with few UIDs for the latter
545 // and hundreds for the former).
546 final var toAdd = newDenylist.stream().filter(uid -> !prevDenylist.contains(uid))
547 .collect(Collectors.toSet());
548 if (DDBG) {
549 synchronized (mNetworkForNetId) {
550 Log.d(TAG, ourTag + "Disallowed UIDs per netId: " + mNetIdToDisallowedUids);
551 }
552 Log.d(TAG, ourTag + "Prev denylist: " + prevDenylist);
553 Log.d(TAG, ourTag + "New denylist: " + newDenylist);
554 }
555 final var toRemove = prevDenylist.stream().filter(uid -> !newDenylist.contains(uid))
556 .collect(Collectors.toSet());
557 if (DDBG) Log.d(TAG, ourTag + "toAdd: " + toAdd + "; toRemove: " + toRemove);
558 if (toAdd.isEmpty() && toRemove.isEmpty()) {
559 // Nothing to do.
560 return;
561 }
562 boolean anyFailed = false;
563 for (final int uid : toAdd) {
564 try {
565 mBpfNetMaps.setUidRule(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1, uid,
566 FIREWALL_RULE_DENY);
567 } catch (ServiceSpecificException e) {
568 loge(ourTag + "Failed to add uid " + uid, e);
569 anyFailed = true;
570 break;
571 }
572 }
573 if (!anyFailed) {
574 for (final int uid : toRemove) {
575 try {
576 mBpfNetMaps.setUidRule(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1, uid,
577 FIREWALL_RULE_ALLOW);
578 } catch (ServiceSpecificException e) {
579 loge(ourTag + "Failed to remove uid " + uid, e);
580 anyFailed = true;
581 break;
582 }
583 }
584 }
585 if (anyFailed) {
586 // Should never happen, but just in case.
587 replaceFirewallChain(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1,
588 newDenylist.stream().mapToInt(Integer::intValue).toArray());
589 }
590 // Tell NPMS about the changes, primarily so the firewall icon can reflect them.
591 mPolicyManager.notifyDenylistChanged(toAdd.stream().mapToInt(Integer::intValue).toArray(),
592 toRemove.stream().mapToInt(Integer::intValue).toArray());
593 if (DDBG) Log.d(TAG, ourTag + "end");
594 }
595
596
597 /**
598 * Generates an allowlist configuration for Netd that reflects a network's allowed UIDs and
599 * includes a sub priority to allow the network to act as a default network for the UIDs
600 * if it is considered to be the default network overall. This default network handling is
601 * required, or else UIDs that do not make specific network requests will have no connectivity.
602 */
603 private NativeUidRangeConfig getAllowlistedNativeUidRangeConfigForNetwork(
604 @NonNull final NetworkAgentInfo nai) {
605 final int netId = nai.network.netId;
606 final var uidsAllowedByPolicy = getUidRangeParcelsAllowedByPolicyForNetwork(nai);
607 final boolean isDefault = isDefaultNetwork(nai);
608 final int subPriority = isDefault ? PREFERENCE_ORDER_LOWEST_WITH_DEFAULT
609 : PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT;
610 return new NativeUidRangeConfig(netId, uidsAllowedByPolicy, subPriority);
611 }
612
613 /**
614 * Updates our tracked configurations for Netd based on changes to default networks, and
615 * informs Netd if any changes need to be made to ensure that allowed UIDs do or do not utilize
616 * changed networks as their default network. This default network handling is required, or
617 * else UIDs that do not make specific network requests will have no connectivity or will
618 * have their traffic traverse the wrong network.
619 */
620 private void updateUidDefaultNetworkRules(@Nullable final NetworkAgentInfo newDefaultNetwork) {
621 final Integer defaultNetId = newDefaultNetwork == null ? null
622 : newDefaultNetwork.network.netId;
623 final var configs = new ArrayList<Pair<NativeUidRangeConfig, NativeUidRangeConfig>>();
624 final var networksForUpdateDisallowedUids = new ArrayList<NetworkAgentInfo>();
625 synchronized (mNetworkForNetId) {
626 for (final var config : mNetIdToAllowlist.values()) {
627 final var configIsDefault =
628 config.subPriority == PREFERENCE_ORDER_LOWEST_WITH_DEFAULT;
629 final int subPriority;
630 if (configIsDefault && !Objects.equals(config.netId, defaultNetId)) {
631 // Remove and replace any existing rules with a subPriority for default.
632 subPriority = PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT;
633 } else if (!configIsDefault && Objects.equals(config.netId, defaultNetId)) {
634 // Remove and replace any existing rules with a subPriority for default.
635 subPriority = PREFERENCE_ORDER_LOWEST_WITH_DEFAULT;
636 } else {
637 continue;
638 }
639 final var newConfig =
640 new NativeUidRangeConfig(config.netId, config.uidRanges, subPriority);
641 mNetIdToAllowlist.put(newConfig.netId, newConfig);
642 configs.add(new Pair<>(config, newConfig));
643 final var nai = mNetworkForNetId.get(config.netId);
644 if (nai != null) {
645 networksForUpdateDisallowedUids.add(nai);
646 }
647 }
648 }
649 for (final var pair : configs) {
650 try {
651 mNetd.networkAddUidRangesParcel(pair.second);
652 mNetd.networkRemoveUidRangesParcel(pair.first);
653 } catch (RemoteException | ServiceSpecificException e) {
654 loge("updateUidDefaultNetworkRules: Exception while updating", e);
655 }
656 }
657 for (final var nai : networksForUpdateDisallowedUids) {
658 updateDisallowedUidsForNetwork(nai);
659 }
660 }
661
662 /**
663 * Generates and stores an allowlist configuration based on the policies that apply to the
664 * given network, and sends this configuration to Netd. Uses the same methods for adding UID
665 * range-based IP rules as is used by VPNs or by restricted networks which manually specify
666 * their allowed UIDs, ensuring absent UIDs cannot be routed there. {@see updateAllowedUids}
667 */
668 private void updateAllowedUidsForNetwork(@NonNull final NetworkAgentInfo nai) {
669 if (!nai.networkInfo.isConnected()) {
670 // Network is not connected, so we cannot currently update allowed UIDs.
671 // If we try, Netd responds with: "Machine is not on the network (code 64)"
672 return;
673 }
674 final int netId = nai.network.netId;
675 final var ourTag = "updateAllowedUidsForNetwork(" + netId + "): ";
676 if (DDBG) Log.d(TAG, ourTag + "begin");
677 final var config = getAllowlistedNativeUidRangeConfigForNetwork(nai);
678 final NativeUidRangeConfig lastConfig;
679 synchronized (mNetworkForNetId) {
680 lastConfig = mNetIdToAllowlist.get(netId);
681 mNetIdToAllowlist.put(netId, config);
682 }
683 try {
684 if (config.uidRanges != null && config.uidRanges.length > 0) {
685 mNetd.networkAddUidRangesParcel(config);
686 }
687 if (lastConfig != null && lastConfig.uidRanges != null
688 && lastConfig.uidRanges.length > 0) {
689 mNetd.networkRemoveUidRangesParcel(lastConfig);
690 }
691 } catch (Exception e) {
692 loge(ourTag + "Exception encountered", e);
693 }
694 if (DDBG) Log.d(TAG, ourTag + "end");
695 }
696
697 private static final long TRANSPORT_VPN_FLAG = 1 << TRANSPORT_VPN;
698
699 /**
700 * Returns true if all of the provided transports are allowed, or if transports represent
701 * a VPN and VPNs are allowed. Otherwise, returns false.
702 */
703 private static boolean areTransportsAllowed(final long transports,
704 final long allowedTransports) {
705 // TODO: In the future, we may want to provide a way to restrict VPN access based on
706 // its other transports, e.g. to block apps from using mobile data even if that data
707 // is over a VPN. This is possible by removing or extending the check below.
708 if ((transports & TRANSPORT_VPN_FLAG) != 0) {
709 // For a VPN, all that matters is VPN access, nothing else.
710 return (allowedTransports & TRANSPORT_VPN_FLAG) != 0;
711 }
712 return (allowedTransports & transports) == transports;
713 }
714
715 /**
716 * Returns a list of UIDs that are policy-restricted based on the provided network and its
717 * capabilities. Networks that are restricted by the system choose their own allowed UIDs,
718 * so we do not disallow any UIDs for those networks.
719 */
720 private List<Integer> getUidsDisallowedByPolicyForNetwork(
721 @NonNull final NetworkAgentInfo nai) {
722 final var ourTag = "getUidsDisallowedByPolicyForNetwork(" + nai.network.netId + "): ";
723 final var uids = new ArrayList<Integer>();
724 if (!nai.networkInfo.isConnectedOrConnecting()) {
725 // Network is not connected so nothing needs to be disallowed.
726 if (DDBG) Log.d(TAG, ourTag + "not connected, so empty");
727 return uids;
728 }
729 final NetworkCapabilities nc = nai.networkCapabilities;
730 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
731 // We do not want to meddle with networks that are already considered restricted.
732 // These will have their own allowed UIDs.
733 if (DDBG) Log.d(TAG, ourTag + "restricted, so empty");
734 return uids;
735 }
736 final long packedTransports = BitUtils.packBits(nc.getTransportTypes());
737 if (packedTransports == 0L) {
738 // If we are not supplied with transports to check, nothing is allowed.
739 if (DDBG) Log.d(TAG, ourTag + "transports == 0L, so empty");
740 return uids;
741 }
742 final int size = mUidAllowedTransports.size();
743 int lastUid = 0;
744 for (int i = 0; i < size; i++) {
745 int uid = mUidAllowedTransports.keyAt(i);
746 long allowedTransports = mUidAllowedTransports.valueAt(i);
747 if (!nc.appliesToUid(uid)) continue;
748 if (!areTransportsAllowed(packedTransports, allowedTransports)) {
749 uids.add(uid);
750 }
751 }
752 return uids;
753 }
754
755 /**
756 * Returns an array of UidRangeParcel representing all possible UIDs that are not restricted
757 * by policy, based on the provided network and its capabilities.
758 */
759 private UidRangeParcel[] getUidRangeParcelsAllowedByPolicyForNetwork(
760 @NonNull final NetworkAgentInfo nai) {
761 final var uids = getUidsDisallowedByPolicyForNetwork(nai);
762 final var ranges = new ArrayList<UidRangeParcel>();
763 int lastUid = 0;
764 for (final Integer uid : uids) {
765 if (uid != lastUid) {
766 ranges.add(new UidRangeParcel(lastUid, uid - 1));
767 }
768 lastUid = uid + 1;
769 }
770 ranges.add(new UidRangeParcel(lastUid, Integer.MAX_VALUE));
771 return ranges.toArray(new UidRangeParcel[0]);
772 }
773
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900774 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900775 private final ConnectivityResources mResources;
Maciej Żenczykowskif310a142023-06-05 07:29:28 +0000776 private final int mWakeUpMark;
777 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000778 // The Context is created for UserHandle.ALL.
779 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900780 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900781 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700782 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700783 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800784
Chenbo Feng15416292018-11-08 17:36:21 -0800785 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800786 protected IDnsResolver mDnsResolver;
787 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800788 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700789 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900790 private final NetworkStatsManager mStatsManager;
791 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800792 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700793
Benedict Wong493e04b2018-11-09 14:45:34 -0800794 /**
795 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
796 * instances.
797 */
798 @GuardedBy("mTNSLock")
799 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800800 private final CompanionDeviceManagerProxyService mCdmps;
Benedict Wong493e04b2018-11-09 14:45:34 -0800801
802 private final Object mTNSLock = new Object();
803
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700804 private String mCurrentTcpBufferSizes;
805
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900806 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000807 new Class[] {
808 ConnectivityService.class,
809 NetworkAgent.class,
810 NetworkAgentInfo.class,
811 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900812
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500813 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400814 // Tear down networks that have no chance (e.g. even if validated) of becoming
815 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500816 // all networks have been rematched against all NetworkRequests.
817 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400818 // Don't reap networks. This should be passed when some networks have not yet been
819 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500820 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900821 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500822
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900823 private enum UnneededFor {
824 LINGER, // Determine whether this network is unneeded and should be lingered.
825 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
826 }
827
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700828 /**
paulhuaa0743d2021-05-26 21:56:03 +0800829 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800830 * should have priority. The order is passed to netd which will use it together
831 * with UID ranges to generate the corresponding IP rule. This serves to
832 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800833 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800834 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000835 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800836 *
paulhu48291862021-07-14 14:53:57 +0800837 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
838 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800839 */
paulhu48291862021-07-14 14:53:57 +0800840 // Used when sending to netd to code for "no order".
841 static final int PREFERENCE_ORDER_NONE = 0;
842 // Order for requests that don't code for a per-app preference. As it is
843 // out of the valid range, the corresponding order should be
844 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800845 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800846 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800847 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800848 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
849 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800850 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800851 static final int PREFERENCE_ORDER_OEM = 10;
852 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800853 // See {@link #setProfileNetworkPreference}.
854 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800855 static final int PREFERENCE_ORDER_PROFILE = 20;
856 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800857 // better scores are connected.
858 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800859 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800860 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Tommy Webb34f81dc2023-02-20 14:10:55 -0500861 // Lowest subpriority that still adds default network rules.
862 static final int PREFERENCE_ORDER_LOWEST_WITH_DEFAULT = 998;
Chalard Jeane6c95272022-01-25 21:04:21 +0900863 // Preference order that signifies the network shouldn't be set as a default network for
864 // the UIDs, only give them access to it. TODO : replace this with a boolean
865 // in NativeUidRangeConfig
866 @VisibleForTesting
867 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
868 // Bound for the lowest valid preference order.
869 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800870
871 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700872 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700873 * from one net to another. Clear happens when we get a new
874 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
875 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700876 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700877 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700878
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700879 /**
880 * used internally to reload global proxy settings
881 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700882 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700883
Robert Greenwalt34848c02011-03-25 13:09:25 -0700884 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400885 * PAC manager has received new port.
886 */
Aaron Huang25ef1712021-06-08 13:11:45 +0800887 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400888
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700889 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900890 * used internally when registering NetworkProviders
891 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700892 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900893 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700894
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700895 /**
896 * used internally when registering NetworkAgents
897 * obj = Messenger
898 */
899 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
900
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700901 /**
902 * used to add a network request
903 * includes a NetworkRequestInfo
904 */
905 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
906
907 /**
908 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900909 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700910 * cancel it.
911 * includes a NetworkRequestInfo
912 */
913 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
914
915 /**
916 * used to add a network listener - no request
917 * includes a NetworkRequestInfo
918 */
919 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
920
921 /**
922 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400923 * arg1 = UID of caller
924 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700925 */
926 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
927
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700928 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900929 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700930 * obj = Messenger
931 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900932 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700933
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700934 /**
935 * used internally to expire a wakelock when transitioning
936 * from one net to another. Expire happens when we fail to find
937 * a new network (typically after 1 minute) -
938 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
939 * a replacement network.
940 */
941 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
942
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700943 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800944 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400945 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800946 */
947 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
948
949 /**
950 * used to remove a pending intent and its associated network request.
951 * arg1 = UID of caller
952 * obj = PendingIntent
953 */
954 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
955
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900956 /**
957 * used to specify whether a network should be used even if unvalidated.
958 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
959 * arg2 = whether to remember this choice in the future (1 or 0)
960 * obj = network
961 */
962 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
963
964 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700965 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900966 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700967 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900968
Paul Jensenc8873fc2015-06-17 14:15:39 -0400969 /**
970 * used to add a network listener with a pending intent
971 * obj = NetworkRequestInfo
972 */
973 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
974
Hugo Benichid6b510a2017-04-06 17:22:18 +0900975 /**
976 * used to specify whether a network should not be penalized when it becomes unvalidated.
977 */
978 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
979
980 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700981 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900982 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700983 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900984
Erik Kline31b4a9e2018-01-11 21:07:29 +0900985 // Handle changes in Private DNS settings.
986 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
987
dalyk1720e542018-03-05 12:42:22 -0500988 // Handle private DNS validation status updates.
989 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
990
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900991 /**
992 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
993 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800994 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
995 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
996 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900997 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900998 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900999
1000 /**
1001 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
1002 * config was resolved.
1003 * obj = PrivateDnsConfig
1004 * arg2 = netid
1005 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +09001006 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09001007
1008 /**
1009 * Request ConnectivityService display provisioning notification.
1010 * arg1 = Whether to make the notification visible.
1011 * arg2 = NetID.
1012 * obj = Intent to be launched when notification selected by user, null if !arg1.
1013 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +09001014 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09001015
1016 /**
lucaslin2240ef62019-03-12 13:08:03 +08001017 * Used to specify whether a network should be used even if connectivity is partial.
1018 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
1019 * false)
1020 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
1021 * obj = network
1022 */
lucaslin444d43a2020-02-20 16:56:59 +08001023 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +08001024
1025 /**
lucasline117e2e2019-10-22 18:27:33 +08001026 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
1027 * Both of the arguments are bitmasks, and the value of bits come from
1028 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09001029 * arg1 = unused
1030 * arg2 = netId
1031 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +08001032 */
lucaslin444d43a2020-02-20 16:56:59 +08001033 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +08001034
1035 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09001036 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
1037 * arg1 = unused
1038 * arg2 = netId
1039 * obj = captive portal data
1040 */
lucaslin444d43a2020-02-20 16:56:59 +08001041 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09001042
1043 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001044 * Used by setRequireVpnForUids.
1045 * arg1 = whether the specified UID ranges are required to use a VPN.
1046 * obj = Array of UidRange objects.
1047 */
1048 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
1049
1050 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001051 * Used internally when setting the default networks for OemNetworkPreferences.
1052 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -08001053 */
1054 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
1055
1056 /**
lucaslin1193a5d2021-01-21 02:04:15 +08001057 * Used to indicate the system default network becomes active.
1058 */
1059 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
1060
1061 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001062 * Used internally when setting a network preference for a user profile.
1063 * obj = Pair<ProfileNetworkPreference, Listener>
1064 */
1065 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
1066
1067 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00001068 * Event to specify that reasons for why an uid is blocked changed.
1069 * arg1 = uid
1070 * arg2 = blockedReasons
1071 */
1072 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
1073
1074 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +09001075 * Event to register a new network offer
1076 * obj = NetworkOffer
1077 */
1078 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
1079
1080 /**
1081 * Event to unregister an existing network offer
1082 * obj = INetworkOfferCallback
1083 */
1084 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
1085
1086 /**
paulhu51f77dc2021-06-07 02:34:20 +00001087 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
1088 */
1089 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
1090
1091 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08001092 * Event to set temporary allow bad wifi within a limited time to override
1093 * {@code config_networkAvoidBadWifi}.
1094 */
1095 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
1096
1097 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001098 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
1099 */
1100 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
1101
1102 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +09001103 * The initial evaluation period is over for this network.
1104 *
1105 * If no form of connectivity has been found on this network (valid, partial, captive portal)
1106 * then the stack will now consider it to have been determined bad.
1107 */
1108 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
1109
1110 /**
Hansen Kurli55396972022-10-28 03:31:17 +00001111 * Used internally when the user does not want the network from captive portal app.
1112 * obj = Network
1113 */
1114 private static final int EVENT_USER_DOES_NOT_WANT = 58;
1115
1116 /**
lucaslin3ba7cc22022-12-19 02:35:33 +00001117 * Event to set VPN as preferred network for specific apps.
1118 * obj = VpnNetworkPreferenceInfo
1119 */
1120 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
1121
1122 /**
chiachangwange0192a72023-02-06 13:25:01 +00001123 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
1124 */
1125 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
1126
1127 /**
Mark Fasheh7501e762023-05-04 20:23:11 +00001128 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
1129 */
1130 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
1131
1132 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09001133 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
1134 * should be shown.
1135 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +09001136 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09001137
1138 /**
1139 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
1140 * should be hidden.
1141 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +09001142 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09001143
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08001144 /**
1145 * The maximum alive time to allow bad wifi configuration for testing.
1146 */
1147 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
1148
Patrick Rohr2857ac42022-01-21 14:58:16 +01001149 /**
chiachangwange0192a72023-02-06 13:25:01 +00001150 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
1151 * testing.
1152 */
1153 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
1154
1155 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001156 * The priority of the tc police rate limiter -- smaller value is higher priority.
1157 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
1158 */
1159 private static final short TC_PRIO_POLICE = 1;
1160
1161 /**
1162 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
1163 */
1164 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -07001165 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +01001166
Hugo Benichi47011212017-03-30 10:46:05 +09001167 private static String eventName(int what) {
1168 return sMagicDecoderRing.get(what, Integer.toString(what));
1169 }
1170
paulhua10d8212020-11-10 15:32:56 +08001171 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +09001172 final DnsResolverServiceManager dsm = context.getSystemService(
1173 DnsResolverServiceManager.class);
1174 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +08001175 }
1176
Cody Kesting73708bf2019-12-18 10:57:50 -08001177 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001178 @VisibleForTesting
1179 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001180 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07001181 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001182 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -07001183 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -08001184 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
1185 @VisibleForTesting
1186 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
1187
Erik Kline32120082017-12-13 19:40:49 +09001188 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +09001189 @VisibleForTesting
1190 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -07001191
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001192 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -08001193 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04001194
Chalard Jean46bfbf02022-02-02 00:56:25 +09001195 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001196 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001197
Chalard Jean5d70ba42018-06-07 16:44:04 +09001198 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
1199 // the world when it changes.
Aaron Huang58f949a2021-06-08 04:34:24 +08001200 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -04001201
Erik Kline05f2b402015-04-30 12:58:40 +09001202 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07001203
Chalard Jean46bfbf02022-02-02 00:56:25 +09001204 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -04001205
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001206 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +09001207 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001208
Valentin Iftime9fa35092019-09-24 13:32:13 +02001209 private Set<String> mWolSupportedInterfaces;
1210
Roshan Pius08c94fb2020-01-16 12:17:17 -08001211 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08001212 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001213 private final AppOpsManager mAppOpsManager;
1214
1215 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -04001216
chiachangwang3d60bac2023-01-17 14:38:08 +00001217 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +09001218 private final QosCallbackTracker mQosCallbackTracker;
1219 private final NetworkNotificationManager mNotifier;
1220 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09001221
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001222 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +08001223 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001224
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09001225 // Sequence number for NetworkProvider IDs.
1226 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
1227 NetworkProvider.FIRST_PROVIDER_ID);
1228
Erik Klineedf878b2015-07-09 18:24:03 +09001229 // NetworkRequest activity String log entries.
1230 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
1231 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
1232
Hugo Benichid159fdd2016-07-11 11:05:12 +09001233 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +09001234 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +09001235 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
1236
Hugo Benichi47011212017-03-30 10:46:05 +09001237 private static final int MAX_WAKELOCK_LOGS = 20;
1238 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +09001239 private int mTotalWakelockAcquisitions = 0;
1240 private int mTotalWakelockReleases = 0;
1241 private long mTotalWakelockDurationMs = 0;
1242 private long mMaxWakelockDurationMs = 0;
1243 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +09001244
Hugo Benichi208c0102016-07-28 17:53:06 +09001245 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +09001246
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07001247 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +09001248 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07001249
Erik Kline95ecfee2016-10-02 18:02:14 +09001250 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001251 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +09001252
Lorenzo Colitti389a8142018-01-24 17:35:07 +09001253 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -08001254 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
1255 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -08001256
Patrick Rohr2857ac42022-01-21 14:58:16 +01001257 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
1258 // configured via {@link
1259 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
1260 // Only the handler thread is allowed to access this field.
1261 private long mIngressRateLimit = -1;
1262
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001263 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
1264 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +09001265 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001266 @GuardedBy("mSelfCertifiedCapabilityCache")
1267 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
1268 mSelfCertifiedCapabilityCache = new HashMap<>();
1269
Robert Greenwalt802c1102014-06-02 15:32:02 -07001270 /**
1271 * Implements support for the legacy "one network per network type" model.
1272 *
1273 * We used to have a static array of NetworkStateTrackers, one for each
1274 * network type, but that doesn't work any more now that we can have,
1275 * for example, more that one wifi network. This class stores all the
1276 * NetworkAgentInfo objects that support a given type, but the legacy
1277 * API will only see the first one.
1278 *
1279 * It serves two main purposes:
1280 *
1281 * 1. Provide information about "the network for a given type" (since this
1282 * API only supports one).
1283 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
1284 * the first network for a given type changes, or if the default network
1285 * changes.
1286 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001287 @VisibleForTesting
1288 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001289
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09001290 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001291 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001292
Robert Greenwalt802c1102014-06-02 15:32:02 -07001293 /**
1294 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
1295 * Each list holds references to all NetworkAgentInfos that are used to
1296 * satisfy requests for that network type.
1297 *
1298 * This array is built out at startup such that an unsupported network
1299 * doesn't get an ArrayList instance, making this a tristate:
1300 * unsupported, supported but not active and active.
1301 *
1302 * The actual lists are populated when we scan the network types that
1303 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +09001304 *
1305 * Threading model:
1306 * - addSupportedType() is only called in the constructor
1307 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
1308 * They are therefore not thread-safe with respect to each other.
1309 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1310 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001311 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001312 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001313 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001314 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001315 @NonNull
1316 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001317
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001318 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1319 // an entry have no timer (equivalent to -1). Lazily loaded.
1320 @NonNull
1321 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1322
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001323 LegacyTypeTracker(@NonNull ConnectivityService service) {
1324 mService = service;
1325 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001326 }
1327
Chiachang Wang3bc52762021-11-25 14:17:57 +08001328 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1329 // addressed.
1330 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001331 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1332 final PackageManager pm = ctx.getPackageManager();
1333 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1334 addSupportedType(TYPE_WIFI);
1335 }
1336 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1337 addSupportedType(TYPE_WIFI_P2P);
1338 }
1339 if (tm.isDataCapable()) {
1340 // Telephony does not have granular support for these types: they are either all
1341 // supported, or none is supported
1342 addSupportedType(TYPE_MOBILE);
1343 addSupportedType(TYPE_MOBILE_MMS);
1344 addSupportedType(TYPE_MOBILE_SUPL);
1345 addSupportedType(TYPE_MOBILE_DUN);
1346 addSupportedType(TYPE_MOBILE_HIPRI);
1347 addSupportedType(TYPE_MOBILE_FOTA);
1348 addSupportedType(TYPE_MOBILE_IMS);
1349 addSupportedType(TYPE_MOBILE_CBS);
1350 addSupportedType(TYPE_MOBILE_IA);
1351 addSupportedType(TYPE_MOBILE_EMERGENCY);
1352 }
1353 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1354 addSupportedType(TYPE_BLUETOOTH);
1355 }
1356 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1357 // TYPE_PROXY is only used on Wear
1358 addSupportedType(TYPE_PROXY);
1359 }
1360 // Ethernet is often not specified in the configs, although many devices can use it via
1361 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001362 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001363 addSupportedType(TYPE_ETHERNET);
1364 }
1365
1366 // Always add TYPE_VPN as a supported type
1367 addSupportedType(TYPE_VPN);
1368 }
1369
1370 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001371 if (mTypeLists[type] != null) {
1372 throw new IllegalStateException(
1373 "legacy list for type " + type + "already initialized");
1374 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001375 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001376 }
1377
Robert Greenwalt802c1102014-06-02 15:32:02 -07001378 public boolean isTypeSupported(int type) {
1379 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1380 }
1381
1382 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001383 synchronized (mTypeLists) {
1384 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1385 return mTypeLists[type].get(0);
1386 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001387 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001388 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001389 }
1390
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001391 public int getRestoreTimerForType(int type) {
1392 synchronized (mTypeLists) {
1393 if (mRestoreTimers == null) {
1394 mRestoreTimers = loadRestoreTimers();
1395 }
1396 return mRestoreTimers.getOrDefault(type, -1);
1397 }
1398 }
1399
1400 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1401 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001402 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001403 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1404 for (final String config : configs) {
1405 final String[] splits = TextUtils.split(config, ",");
1406 if (splits.length != 2) {
1407 logwtf("Invalid restore timer token count: " + config);
1408 continue;
1409 }
1410 try {
1411 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1412 } catch (NumberFormatException e) {
1413 logwtf("Invalid restore timer number format: " + config, e);
1414 }
1415 }
1416 return ret;
1417 }
1418
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001419 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001420 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001421 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001422 log("Sending " + state
1423 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001424 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001425 }
1426 }
1427
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001428 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1429 // network type, to preserve previous behaviour.
1430 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1431 if (vpnNai != mService.getLegacyLockdownNai()) return;
1432
1433 if (vpnNai.declaredUnderlyingNetworks == null
1434 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1435 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1436 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1437 return;
1438 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001439 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001440 vpnNai.declaredUnderlyingNetworks[0]);
1441 if (underlyingNai == null) return;
1442
1443 final int type = underlyingNai.networkInfo.getType();
1444 final DetailedState state = DetailedState.CONNECTED;
1445 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1446 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1447 }
1448
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001449 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001450 public void add(int type, NetworkAgentInfo nai) {
1451 if (!isTypeSupported(type)) {
1452 return; // Invalid network type.
1453 }
1454 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1455
1456 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1457 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001458 return;
1459 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001460 synchronized (mTypeLists) {
1461 list.add(nai);
1462 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001463
Chalard Jean5b409c72021-02-04 13:12:59 +09001464 // Send a broadcast if this is the first network of its type or if it's the default.
1465 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001466
1467 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1468 // to preserve previous behaviour.
1469 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001470 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001471 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1472 mService.sendLegacyNetworkBroadcast(nai, state, type);
1473 }
1474
1475 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1476 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001477 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001478 }
1479
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001480 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001481 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001482 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1483 if (list == null || list.isEmpty()) {
1484 return;
1485 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001486 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001487
Hugo Benichi389633f2016-06-21 09:48:07 +09001488 synchronized (mTypeLists) {
1489 if (!list.remove(nai)) {
1490 return;
1491 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001492 }
1493
Lorenzo Colitti49767722015-05-01 00:30:10 +09001494 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001495 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1496 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001497 }
1498
1499 if (!list.isEmpty() && wasFirstNetwork) {
1500 if (DBG) log("Other network available for type " + type +
1501 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001502 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001503 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001504 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001505 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001506 }
1507 }
1508
1509 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001510 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1511 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001512 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001513 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001514 }
1515 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001516
Chalard Jean46bfbf02022-02-02 00:56:25 +09001517 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001518 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001519 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001520 final DetailedState state = nai.networkInfo.getDetailedState();
1521 for (int type = 0; type < mTypeLists.length; type++) {
1522 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001523 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001524 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001525 if (isFirst || contains && isDefault) {
1526 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001527 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001528 }
1529 }
1530 }
1531
Robert Greenwalt94e22142014-07-30 16:31:24 -07001532 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001533 pw.println("mLegacyTypeTracker:");
1534 pw.increaseIndent();
1535 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001536 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001537 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001538 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001539 pw.println();
1540 pw.println("Current state:");
1541 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001542 synchronized (mTypeLists) {
1543 for (int type = 0; type < mTypeLists.length; type++) {
1544 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1545 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001546 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001547 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001548 }
1549 }
1550 pw.decreaseIndent();
1551 pw.decreaseIndent();
1552 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001553 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001554 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001555 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001556
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001557 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001558 /**
1559 * Helper class which parses out priority arguments and dumps sections according to their
1560 * priority. If priority arguments are omitted, function calls the legacy dump command.
1561 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001562 private class LocalPriorityDump {
1563 private static final String PRIORITY_ARG = "--dump-priority";
1564 private static final String PRIORITY_ARG_HIGH = "HIGH";
1565 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1566
1567 LocalPriorityDump() {}
1568
1569 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1570 doDump(fd, pw, new String[] {DIAG_ARG});
1571 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001572 }
1573
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001574 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1575 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001576 }
1577
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001578 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1579 if (args == null) {
1580 dumpNormal(fd, pw, args);
1581 return;
1582 }
1583
1584 String priority = null;
1585 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1586 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1587 argIndex++;
1588 priority = args[argIndex];
1589 }
1590 }
1591
1592 if (PRIORITY_ARG_HIGH.equals(priority)) {
1593 dumpHigh(fd, pw);
1594 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1595 dumpNormal(fd, pw, args);
1596 } else {
1597 // ConnectivityService publishes binder service using publishBinderService() with
1598 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001599 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1600 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001601 // TODO: Integrate into signal dump.
1602 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001603 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001604 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001605 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001606
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001607 /**
1608 * Dependencies of ConnectivityService, for injection in tests.
1609 */
1610 @VisibleForTesting
1611 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001612 public int getCallingUid() {
1613 return Binder.getCallingUid();
1614 }
1615
Chalard Jean03552c42023-05-29 17:02:43 +09001616 public boolean isAtLeastS() {
1617 return SdkLevel.isAtLeastS();
1618 }
1619
1620 public boolean isAtLeastT() {
1621 return SdkLevel.isAtLeastT();
1622 }
1623
1624 public boolean isAtLeastU() {
1625 return SdkLevel.isAtLeastU();
1626 }
1627
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001628 /**
1629 * Get system properties to use in ConnectivityService.
1630 */
1631 public MockableSystemProperties getSystemProperties() {
1632 return new MockableSystemProperties();
1633 }
1634
1635 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001636 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1637 */
1638 public ConnectivityResources getResources(@NonNull Context ctx) {
1639 return new ConnectivityResources(ctx);
1640 }
1641
1642 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001643 * Create a HandlerThread to use in ConnectivityService.
1644 */
1645 public HandlerThread makeHandlerThread() {
1646 return new HandlerThread("ConnectivityServiceThread");
1647 }
1648
1649 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001650 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001651 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001652 public NetworkStackClientBase getNetworkStack() {
1653 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001654 }
1655
1656 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001657 * @see ProxyTracker
1658 */
1659 public ProxyTracker makeProxyTracker(@NonNull Context context,
1660 @NonNull Handler connServiceHandler) {
Aaron Huang25ef1712021-06-08 13:11:45 +08001661 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001662 }
1663
1664 /**
1665 * @see NetIdManager
1666 */
1667 public NetIdManager makeNetIdManager() {
1668 return new NetIdManager();
1669 }
1670
1671 /**
1672 * @see NetworkUtils#queryUserAccess(int, int)
1673 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001674 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1675 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001676 }
1677
1678 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001679 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1680 * requires CAP_NET_ADMIN, which the unit tests do not have.
1681 */
1682 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1683 InetSocketAddress remote) {
1684 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1685 }
1686
1687 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001688 * @see MultinetworkPolicyTracker
1689 */
1690 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1691 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1692 return new MultinetworkPolicyTracker(c, h, r);
1693 }
1694
Aaron Huang330a4c02020-10-27 03:36:19 +08001695 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001696 * @see AutomaticOnOffKeepaliveTracker
1697 */
1698 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1699 @NonNull Context c, @NonNull Handler h) {
1700 return new AutomaticOnOffKeepaliveTracker(c, h);
1701 }
1702
1703 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001704 * @see BatteryStatsManager
1705 */
1706 public void reportNetworkInterfaceForTransports(Context context, String iface,
1707 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001708 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001709 context.getSystemService(BatteryStatsManager.class);
1710 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1711 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001712
1713 public boolean getCellular464XlatEnabled() {
1714 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1715 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001716
1717 /**
1718 * @see PendingIntent#intentFilterEquals
1719 */
1720 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1721 return a.intentFilterEquals(b);
1722 }
1723
1724 /**
1725 * @see LocationPermissionChecker
1726 */
1727 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1728 return new LocationPermissionChecker(context);
1729 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001730
1731 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001732 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001733 *
1734 * This method returns null in versions before T, where carrier privilege
1735 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001736 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001737 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001738 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1739 @NonNull final Context context, @NonNull final TelephonyManager tm) {
Chalard Jean03552c42023-05-29 17:02:43 +09001740 if (isAtLeastT()) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09001741 return new CarrierPrivilegeAuthenticator(context, tm);
1742 } else {
1743 return null;
1744 }
1745 }
1746
1747 /**
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001748 * @see DeviceConfigUtils#isFeatureEnabled
1749 */
Motomu Utsumi6f4d8062023-04-21 12:35:22 +09001750 public boolean isFeatureEnabled(Context context, String name) {
1751 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_TETHERING, name,
1752 TETHERING_MODULE_NAME, false /* defaultValue */);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001753 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001754
1755 /**
1756 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001757 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001758 * @return BpfNetMaps implementation.
1759 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001760 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1761 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001762 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001763
1764 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001765 * @see ClatCoordinator
1766 */
1767 public ClatCoordinator getClatCoordinator(INetd netd) {
1768 return new ClatCoordinator(
1769 new ClatCoordinator.Dependencies() {
1770 @NonNull
1771 public INetd getNetd() {
1772 return netd;
1773 }
1774 });
1775 }
1776
1777 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001778 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1779 */
1780 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1781 final InterfaceParams params = InterfaceParams.getByName(iface);
1782 if (params == null) {
1783 // the interface might have disappeared.
1784 logw("Failed to get interface params for interface " + iface);
1785 return;
1786 }
1787 try {
1788 // converting rateInBytesPerSecond from long to int is safe here because the
1789 // setting's range is limited to INT_MAX.
1790 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001791 Log.i(TAG,
1792 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001793 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1794 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1795 } catch (IOException e) {
1796 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1797 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1798 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1799 + ") failure: ", e);
1800 }
1801 }
1802
1803 /**
1804 * Wraps {@link TcUtils#tcFilterDelDev}
1805 */
1806 public void disableIngressRateLimit(String iface) {
1807 final InterfaceParams params = InterfaceParams.getByName(iface);
1808 if (params == null) {
1809 // the interface might have disappeared.
1810 logw("Failed to get interface params for interface " + iface);
1811 return;
1812 }
1813 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001814 Log.i(TAG,
1815 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001816 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1817 } catch (IOException e) {
1818 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1819 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1820 }
1821 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001822
1823 /**
1824 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1825 */
1826 // TODO: when available in all active branches:
1827 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1828 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1829 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1830 return BroadcastOptionsShimImpl.newInstance(options);
1831 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001832
1833 /**
1834 * Wrapper method for
1835 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1836 *
1837 * @param changeId The ID of the compatibility change in question.
1838 * @param packageName The package name of the app in question.
1839 * @param user The user that the operation is done for.
1840 * @return {@code true} if the change is enabled for the specified package.
1841 */
1842 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1843 @NonNull final UserHandle user) {
1844 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1845 }
Motomu Utsumia20f7602023-03-16 17:04:21 +09001846
1847 /**
Chalard Jean03552c42023-05-29 17:02:43 +09001848 * As above but with a UID.
1849 * @see CompatChanges#isChangeEnabled(long, int)
1850 */
1851 public boolean isChangeEnabled(final long changeId, final int uid) {
1852 return CompatChanges.isChangeEnabled(changeId, uid);
1853 }
1854
1855 /**
Motomu Utsumia20f7602023-03-16 17:04:21 +09001856 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1857 *
1858 * @param ranges target uid ranges
1859 * @param exemptUids uids to skip close socket
1860 */
1861 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1862 @NonNull final Set<Integer> exemptUids)
1863 throws SocketException, InterruptedIOException, ErrnoException {
1864 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1865 }
Motomu Utsumied1848c2023-03-28 18:08:12 +09001866
1867 /**
1868 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1869 *
1870 * @param ownerUids target uids to close sockets
1871 */
1872 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1873 throws SocketException, InterruptedIOException, ErrnoException {
1874 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1875 }
Chalard Jean1f2b50f2023-05-15 17:26:13 +09001876
1877 /**
1878 * Schedule the evaluation timeout.
1879 *
1880 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1881 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1882 * of these events happen, this time will run out, after which the network is considered
1883 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1884 * on this network and considers it won't provide connectivity. In particular, that means
1885 * it's when the system prefers it to cell if it's wifi and configuration says it should
1886 * prefer bad wifi to cell.
1887 */
1888 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1889 @NonNull final Network network, final long delayMs) {
1890 handler.sendMessageDelayed(
1891 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1892 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001893 }
1894
junyulaie7c7d2a2021-01-26 15:29:15 +08001895 public ConnectivityService(Context context) {
1896 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001897 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1898 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001899 }
1900
1901 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001902 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1903 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001904 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001905
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001906 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001907 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001908 mSystemProperties = mDeps.getSystemProperties();
1909 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001910 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001911 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001912 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1913 // Pass limit - 1 to maintain backward compatibility.
1914 // TODO: Remove the workaround.
1915 mNetworkRequestCounter =
1916 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1917 mSystemNetworkRequestCounter =
1918 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001919
Hugo Benichi208c0102016-07-28 17:53:06 +09001920 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001921 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1922 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001923 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001924 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001925 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001926 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1927 mDefaultNetworkRequests.add(mDefaultRequest);
1928 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001929
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001930 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001931 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001932
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001933 // The default WiFi request is a background request so that apps using WiFi are
1934 // migrated to a better network (typically ethernet) when one comes up, instead
1935 // of staying on WiFi forever.
1936 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1937 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1938
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001939 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1940 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1941 NetworkRequest.Type.BACKGROUND_REQUEST);
1942
Chalard Jean0702f982021-09-16 21:50:07 +09001943 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1944 // TODO: Consider making the timer customizable.
1945 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1946 mCellularRadioTimesharingCapable =
1947 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1948
Maciej Żenczykowskif310a142023-06-05 07:29:28 +00001949 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1950 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1951
1952 if (SdkLevel.isAtLeastU()) {
1953 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1954 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1955 final int defaultUMarkMask = 0x80000000; // u32
1956
1957 if ((mark == 0) || (mask == 0)) {
1958 // simply treat unset/disabled as the default U value
1959 mark = defaultUMarkMask;
1960 mask = defaultUMarkMask;
1961 }
1962 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1963 // invalid device overlay settings
1964 throw new IllegalArgumentException(
1965 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1966 }
1967 }
1968
1969 mWakeUpMark = mark;
1970 mWakeUpMask = mask;
1971
Paul Hu51f816b2022-08-11 14:43:47 +00001972 mNetd = netd;
1973 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001974 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001975 mPermissionMonitor =
1976 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001977 mHandlerThread.start();
1978 mHandler = new InternalHandler(mHandlerThread.getLooper());
1979 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001980 mConnectivityDiagnosticsHandler =
1981 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001982
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001983 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001984 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001985
junyulaie7c7d2a2021-01-26 15:29:15 +08001986 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001987 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001988 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001989 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001990
Wink Saville32506bc2013-06-29 21:10:57 -07001991 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001992 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001993 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001994 mCarrierPrivilegeAuthenticator =
1995 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001996
Tommy Webb34f81dc2023-02-20 14:10:55 -05001997 // Enable the OEM denylist chain. {@see mNetIdToDisallowedUids}
1998 try {
1999 mBpfNetMaps.setChildChain(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1, true);
2000 } catch (ServiceSpecificException e) {
2001 logwtf("Could not enable fw_oem_deny_1 chain", e);
2002 }
2003
Sudheer Shanka9967d462021-03-18 19:09:25 +00002004 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08002005 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
2006 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00002007 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002008
2009 final PowerManager powerManager = (PowerManager) context.getSystemService(
2010 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002011 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08002012 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07002013
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09002014 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
2015 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09002016 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002017 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09002018 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002019 mProtectedNetworks.add(p);
2020 } else {
2021 if (DBG) loge("Ignoring protectedNetwork " + p);
2022 }
2023 }
2024
soma, kawata29444ae2019-05-23 09:30:40 +09002025 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
2026
James Mattis02220e22021-03-13 19:27:21 -08002027 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09002028 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08002029 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08002030 final IntentFilter userIntentFilter = new IntentFilter();
2031 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
2032 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
2033 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
2034 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08002035
James Mattis02220e22021-03-13 19:27:21 -08002036 // Listen to package add/removes for netd
2037 final IntentFilter packageIntentFilter = new IntentFilter();
2038 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
2039 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2040 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
2041 packageIntentFilter.addDataScheme("package");
2042 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09002043 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08002044
lucaslind5c2d072021-02-20 18:59:47 +08002045 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07002046
Chalard Jean46bfbf02022-02-02 00:56:25 +09002047 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08002048 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002049 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08002050 } catch (RemoteException | ServiceSpecificException e) {
2051 loge("Error registering event listener :" + e);
2052 }
2053
Erik Kline05f2b402015-04-30 12:58:40 +09002054 mSettingsObserver = new SettingsObserver(mContext, mHandler);
2055 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08002056
chiachangwang7c17c282023-02-02 05:58:59 +00002057 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08002058 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07002059 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09002060
2061 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08002062 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09002063 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
2064 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08002065 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09002066 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
2067 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09002068
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09002069 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09002070 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09002071 mNetworkRanker =
2072 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
2073
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09002074 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09002075
Chiachang Wangc1215d32020-10-20 15:38:58 +08002076 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002077 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08002078
Chalard Jean28018572020-12-21 18:36:52 +09002079 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
2080 // request that doesn't allow fallback to the default network. It should never be visible
2081 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
2082 // arguments like the handler or the DnsResolver.
2083 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08002084 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08002085 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08002086 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09002087 new LinkProperties(), new NetworkCapabilities(),
2088 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09002089 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
2090 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07002091
2092 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09002093 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
2094 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
2095 // Even if it could, running on S would at least require mocking out the BPF map,
2096 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
2097 // the bpf syscall. http://aosp/1907693
Chalard Jean03552c42023-05-29 17:02:43 +09002098 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09002099 mDscpPolicyTracker = new DscpPolicyTracker();
2100 }
Tyler Wear72388212021-09-09 14:49:02 -07002101 } catch (ErrnoException e) {
2102 loge("Unable to create DscpPolicyTracker");
2103 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01002104
2105 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
2106 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08002107
Chalard Jean03552c42023-05-29 17:02:43 +09002108 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08002109 mCdmps = new CompanionDeviceManagerProxyService(context);
2110 } else {
2111 mCdmps = null;
2112 }
Mark Fasheh7501e762023-05-04 20:23:11 +00002113
Chalard Jean03552c42023-05-29 17:02:43 +09002114 if (mDeps.isAtLeastU()
Mark Fasheh7501e762023-05-04 20:23:11 +00002115 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION)) {
2116 final UidFrozenStateChangedCallback frozenStateChangedCallback =
2117 new UidFrozenStateChangedCallback() {
2118 @Override
2119 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
2120 if (uids.length != frozenStates.length) {
2121 Log.wtf(TAG, "uids has length " + uids.length
2122 + " but frozenStates has length " + frozenStates.length);
2123 return;
2124 }
2125
2126 final UidFrozenStateChangedArgs args =
2127 new UidFrozenStateChangedArgs(uids, frozenStates);
2128
2129 mHandler.sendMessage(
2130 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
2131 }
2132 };
2133
2134 final ActivityManager activityManager =
2135 mContext.getSystemService(ActivityManager.class);
2136 activityManager.registerUidFrozenStateChangedCallback(
2137 (Runnable r) -> r.run(), frozenStateChangedCallback);
2138 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002139 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07002140
Xiao Ma0a171c02022-01-23 16:14:51 +00002141 /**
2142 * Check whether or not the device supports Ethernet transport.
2143 */
2144 public static boolean deviceSupportsEthernet(final Context context) {
2145 final PackageManager pm = context.getPackageManager();
2146 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
2147 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
2148 }
2149
Chalard Jean46adcf32018-04-18 20:18:38 +09002150 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08002151 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
2152 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09002153 }
2154
Sooraj Sasindran499117f2021-11-29 12:40:09 -08002155 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
2156 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09002157 final NetworkCapabilities netCap = new NetworkCapabilities();
2158 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08002159 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09002160 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08002161 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09002162 return netCap;
2163 }
2164
James Mattis45d81842021-01-10 14:24:24 -08002165 private NetworkRequest createDefaultRequest() {
2166 return createDefaultInternetRequestForTransport(
2167 TYPE_NONE, NetworkRequest.Type.REQUEST);
2168 }
2169
lucaslin3ba7cc22022-12-19 02:35:33 +00002170 private NetworkRequest createVpnRequest() {
2171 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
2172 .withoutDefaultCapabilities()
2173 .addTransportType(TRANSPORT_VPN)
2174 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
2175 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
2176 .build();
2177 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
2178 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
2179 }
2180
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09002181 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09002182 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09002183 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09002184 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08002185 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08002186 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08002187 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09002188 netCap.addTransportType(transportType);
2189 }
James Mattis45d81842021-01-10 14:24:24 -08002190 return createNetworkRequest(type, netCap);
2191 }
2192
2193 private NetworkRequest createNetworkRequest(
2194 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09002195 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09002196 }
2197
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08002198 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
2199 NetworkRequest.Type type) {
2200 final NetworkCapabilities netCap = new NetworkCapabilities();
2201 netCap.clearAll();
2202 netCap.addCapability(capability);
2203 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
2204 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
2205 }
2206
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002207 // Used only for testing.
2208 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07002209 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002210 // changing ContentResolver to make registerContentObserver non-final).
2211 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
2212 // by subclassing SettingsObserver.
2213 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002214 void updateAlwaysOnNetworks() {
2215 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002216 }
2217
Erik Kline9a62f012018-03-21 07:18:33 -07002218 // See FakeSettingsProvider comment above.
2219 @VisibleForTesting
2220 void updatePrivateDnsSettings() {
2221 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
2222 }
2223
paulhu51f77dc2021-06-07 02:34:20 +00002224 @VisibleForTesting
2225 void updateMobileDataPreferredUids() {
2226 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
2227 }
2228
Patrick Rohr2857ac42022-01-21 14:58:16 +01002229 @VisibleForTesting
2230 void updateIngressRateLimit() {
2231 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
2232 }
2233
Aaron Huang58f949a2021-06-08 04:34:24 +08002234 @VisibleForTesting
2235 void simulateUpdateProxyInfo(@Nullable final Network network,
2236 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang25ef1712021-06-08 13:11:45 +08002237 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang58f949a2021-06-08 04:34:24 +08002238 new Pair<>(network, proxyInfo)).sendToTarget();
2239 }
2240
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002241 private void handleAlwaysOnNetworkRequest(
2242 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09002243 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002244 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08002245 handleAlwaysOnNetworkRequest(networkRequest, enable);
2246 }
2247
2248 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002249 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09002250 if (enable == isEnabled) {
2251 return; // Nothing to do.
2252 }
2253
2254 if (enable) {
2255 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09002256 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08002257 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08002258 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09002259 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08002260 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
2261 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09002262 }
2263 }
2264
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002265 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08002266 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
2267 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
2268 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
2269 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09002270 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
2271 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09002272 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002273 }
2274
paulhu51f77dc2021-06-07 02:34:20 +00002275 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08002276 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09002277 private void registerSettingsCallbacks() {
2278 // Watch for global HTTP proxy changes.
2279 mSettingsObserver.observe(
2280 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
2281 EVENT_APPLY_GLOBAL_HTTP_PROXY);
2282
Chalard Jean46bfbf02022-02-02 00:56:25 +09002283 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09002284 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002285 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002286 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
2287
Chalard Jean46bfbf02022-02-02 00:56:25 +09002288 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002289 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002290 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002291 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00002292
2293 // Watch for mobile data preferred uids changes.
2294 mSettingsObserver.observe(
2295 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
2296 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01002297
2298 // Watch for ingress rate limit changes.
2299 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01002300 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01002301 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
2302 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09002303 }
2304
Erik Kline31b4a9e2018-01-11 21:07:29 +09002305 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07002306 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
2307 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002308 }
2309 }
2310
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002311 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08002312 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2313 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002314 return mNextNetworkRequestId++;
2315 }
2316
junyulai74f9a8b2018-06-13 15:00:37 +08002317 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002318 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002319 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002320 if (network == null) {
2321 return null;
2322 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002323 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002324 }
2325
2326 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002327 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002328 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002329 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002330 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002331
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002332 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002333 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002334 private NetworkAgentInfo getVpnForUid(int uid) {
2335 synchronized (mNetworkForNetId) {
2336 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2337 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002338 if (nai.isVPN() && nai.everConnected()
2339 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002340 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002341 }
2342 }
2343 }
2344 return null;
2345 }
2346
Chalard Jean46bfbf02022-02-02 00:56:25 +09002347 @Nullable
Tommy Webb34f81dc2023-02-20 14:10:55 -05002348 private NetworkAgentInfo getConnectedOrConnectingVpnForUid(int uid) {
2349 synchronized (mNetworkForNetId) {
2350 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2351 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
2352 if (nai.isVPN()
2353 && (nai.everConnected() || nai.networkInfo.isConnectedOrConnecting())
2354 && nai.networkCapabilities.appliesToUid(uid)) {
2355 return nai;
2356 }
2357 }
2358 }
2359 return null;
2360 }
2361
2362 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002363 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002364 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002365 final NetworkAgentInfo nai = getVpnForUid(uid);
2366 if (nai != null) return nai.declaredUnderlyingNetworks;
2367 return null;
2368 }
2369
Lorenzo Colittia7574052021-01-19 01:33:05 +09002370 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002371 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002372
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002373 final Network[] networks = getVpnUnderlyingNetworks(uid);
2374 if (networks != null) {
2375 // getUnderlyingNetworks() returns:
2376 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2377 // empty array => the VPN explicitly said "no default network".
2378 // non-empty array => the VPN specified one or more default networks; we use the
2379 // first one.
2380 if (networks.length > 0) {
2381 nai = getNetworkAgentInfoForNetwork(networks[0]);
2382 } else {
2383 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002384 }
2385 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002386 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002387 }
2388
2389 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002390 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002391 */
paulhu7aeba372020-12-30 00:42:19 +08002392 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2393 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002394 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002395 if (ignoreBlocked) {
2396 return false;
2397 }
Tommy Webb34f81dc2023-02-20 14:10:55 -05002398 if (isUidCurrentlyDisallowedByPolicy(uid)) return true;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002399 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002400 final long ident = Binder.clearCallingIdentity();
2401 try {
2402 final boolean metered = nc == null ? true : nc.isMetered();
2403 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2404 } finally {
2405 Binder.restoreCallingIdentity(ident);
2406 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002407 }
2408
Tommy Webb34f81dc2023-02-20 14:10:55 -05002409 /** Check if UID is currently disallowed general network access based on policies. */
2410 private boolean isUidCurrentlyDisallowedByPolicy(int uid) {
2411 return mLastDisallowedUidsDenylist.contains(uid);
2412 }
2413
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002414 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002415 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2416 return;
2417 }
Hugo Benichi47011212017-03-30 10:46:05 +09002418 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002419 synchronized (mBlockedAppUids) {
2420 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002421 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002422 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002423 blocked = false;
2424 } else {
2425 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002426 }
2427 }
Hugo Benichi47011212017-03-30 10:46:05 +09002428 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2429 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2430 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002431 }
2432
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002433 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002434 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2435 return;
2436 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002437 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002438 final int requestId = nri.getActiveRequest() != null
2439 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002440 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002441 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002442 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002443 }
2444
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002445 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002446 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002447 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002448 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002449 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002450 @NonNull
2451 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2452 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002453 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2454 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2455 // but only exists if an app asks about them or requests them. Ensure the requesting app
2456 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002457 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002458 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2459 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2460 null /* extraInfo */);
2461 }
2462 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002463 return filtered;
2464 }
2465
2466 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2467 boolean ignoreBlocked) {
2468 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2469 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002470 }
2471
2472 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002473 * Return NetworkInfo for the active (i.e., connected) network interface.
2474 * It is assumed that at most one network is active at a time. If more
2475 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002476 * @return the info for the active network, or {@code null} if none is
2477 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002478 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002479 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002480 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002481 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002482 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002483 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002484 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2485 if (nai == null) return null;
2486 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2487 maybeLogBlockedNetworkInfo(networkInfo, uid);
2488 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002489 }
2490
Paul Jensen1f567382015-02-13 14:18:39 -05002491 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002492 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002493 public Network getActiveNetwork() {
2494 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002495 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002496 }
2497
2498 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002499 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002500 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002501 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002502 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002503 }
2504
Chalard Jean46bfbf02022-02-02 00:56:25 +09002505 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002506 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Tommy Webb34f81dc2023-02-20 14:10:55 -05002507 return getActiveNetworkForUidInternal(getVpnForUid(uid), uid, ignoreBlocked);
2508 }
2509
2510 private Network getActiveNetworkOrConnectingVpnForUidInternal(final int uid,
2511 boolean ignoreBlocked) {
2512 return getActiveNetworkForUidInternal(
2513 getConnectedOrConnectingVpnForUid(uid), uid, ignoreBlocked);
2514 }
2515
2516 private Network getActiveNetworkForUidInternal(final NetworkAgentInfo vpnNai,
2517 final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002518 if (vpnNai != null) {
2519 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2520 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2521 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002522 }
Paul Jensen1f567382015-02-13 14:18:39 -05002523 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002524
James Mattis2516da32021-01-31 17:06:19 -08002525 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002526 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2527 ignoreBlocked)) {
2528 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002529 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002530 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002531 }
2532
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002533 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002534 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002535 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002536 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002537 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2538 if (nai == null) return null;
2539 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002540 }
2541
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002542 /** Returns a NetworkInfo object for a network that doesn't exist. */
2543 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2544 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2545 getNetworkTypeName(networkType), "" /* subtypeName */);
2546 info.setIsAvailable(true);
2547 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2548 // background data is restricted.
2549 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2550 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2551 ? DetailedState.BLOCKED
2552 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002553 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2554 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002555 return info;
2556 }
2557
Lorenzo Colittia7574052021-01-19 01:33:05 +09002558 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002559 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2560 return null;
2561 }
2562 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002563 if (nai == null) {
2564 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002565 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002566 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2567 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002568 }
2569
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002570 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002571 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002572 public NetworkInfo getNetworkInfo(int networkType) {
2573 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002574 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002575 if (getVpnUnderlyingNetworks(uid) != null) {
2576 // A VPN is active, so we may need to return one of its underlying networks. This
2577 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002578 // getNetworkAgentInfoForUid.
2579 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2580 if (nai == null) return null;
2581 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2582 if (networkInfo.getType() == networkType) {
2583 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002584 }
2585 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002586 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002587 }
2588
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002589 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002590 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002591 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002592 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002593 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002594 if (nai == null) return null;
2595 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002596 }
2597
2598 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002599 public NetworkInfo[] getAllNetworkInfo() {
2600 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002601 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002602 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2603 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002604 NetworkInfo info = getNetworkInfo(networkType);
2605 if (info != null) {
2606 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002607 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002608 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002609 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002610 }
2611
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002612 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002613 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002614 public Network getNetworkForType(int networkType) {
2615 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002616 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2617 return null;
2618 }
2619 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2620 if (nai == null) {
2621 return null;
2622 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002623 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002624 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2625 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002626 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002627 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002628 }
2629
2630 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002631 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002632 public Network[] getAllNetworks() {
2633 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002634 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002635 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002636 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002637 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002638 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002639 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002640 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002641 }
2642
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002643 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002644 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002645 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002646 // The basic principle is: if an app's traffic could possibly go over a
2647 // network, without the app doing anything multinetwork-specific,
2648 // (hence, by "default"), then include that network's capabilities in
2649 // the array.
2650 //
2651 // In the normal case, app traffic only goes over the system's default
2652 // network connection, so that's the only network returned.
2653 //
2654 // With a VPN in force, some app traffic may go into the VPN, and thus
2655 // over whatever underlying networks the VPN specifies, while other app
2656 // traffic may go over the system default network (e.g.: a split-tunnel
2657 // VPN, or an app disallowed by the VPN), so the set of networks
2658 // returned includes the VPN's underlying networks and the system
2659 // default.
2660 enforceAccessPermission();
2661
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002662 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002663
James Mattis2516da32021-01-31 17:06:19 -08002664 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2665 if (!nri.isBeingSatisfied()) {
2666 continue;
2667 }
2668 final NetworkAgentInfo nai = nri.getSatisfier();
2669 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2670 if (null != nc
2671 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2672 && !result.containsKey(nai.network)) {
2673 result.put(
2674 nai.network,
2675 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002676 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002677 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2678 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002679 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002680 }
2681
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002682 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002683 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002684 if (null != networks) {
2685 for (final Network network : networks) {
2686 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2687 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002688 result.put(
2689 network,
2690 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002691 nc,
2692 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002693 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002694 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002695 }
2696 }
2697 }
2698
2699 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2700 out = result.values().toArray(out);
2701 return out;
2702 }
2703
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002704 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002705 public boolean isNetworkSupported(int networkType) {
2706 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002707 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002708 }
2709
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002710 /**
2711 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002712 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002713 * @return the ip properties for the active network, or {@code null} if
2714 * none is active
2715 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002716 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002717 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002718 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002719 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002720 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2721 if (nai == null) return null;
2722 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002723 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002724 }
2725
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002726 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002727 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002728 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002729 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002730 final LinkProperties lp = getLinkProperties(nai);
2731 if (lp == null) return null;
2732 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002733 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002734 }
2735
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002736 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002737 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002738 public LinkProperties getLinkProperties(Network network) {
2739 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002740 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2741 if (lp == null) return null;
2742 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002743 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002744 }
2745
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002746 @Nullable
2747 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002748 if (nai == null) {
2749 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002750 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002751 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002752 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002753 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002754 }
2755
lucaslinc582d502022-01-27 09:07:00 +08002756 @Override
2757 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002758 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002759 @NonNull String packageName, @Nullable String callingAttributionTag) {
2760 Objects.requireNonNull(packageName);
2761 Objects.requireNonNull(lp);
2762 enforceNetworkStackOrSettingsPermission();
2763 if (!checkAccessPermission(-1 /* pid */, uid)) {
2764 return null;
2765 }
2766 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2767 }
2768
Qingxi Lib2748102020-01-08 12:51:49 -08002769 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2770 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2771 }
2772
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002773 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002774 if (nai == null) return null;
2775 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002776 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002777 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002778 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002779 }
2780
2781 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002782 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2783 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002784 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002785 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002786 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002787 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002788 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002789 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002790 }
2791
lucaslinc582d502022-01-27 09:07:00 +08002792 @Override
lucaslind2b06132022-03-02 10:56:57 +08002793 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2794 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2795 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002796 Objects.requireNonNull(nc);
2797 Objects.requireNonNull(packageName);
2798 enforceNetworkStackOrSettingsPermission();
2799 if (!checkAccessPermission(-1 /* pid */, uid)) {
2800 return null;
2801 }
2802 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2803 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2804 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2805 callingAttributionTag);
2806 }
2807
lucaslin69e1aa92022-03-22 18:15:09 +08002808 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2809 if (nc.getUnderlyingNetworks() != null
2810 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2811 nc.setUnderlyingNetworks(null);
2812 }
2813 }
2814
Qingxi Libb8da982020-01-17 17:54:27 -08002815 @VisibleForTesting
2816 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002817 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002818 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2819 // this would be expensive (one more permission check every time any NC callback is
2820 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2821 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2822 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002823 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002824 if (!checkSettingsPermission(callerPid, callerUid)) {
2825 newNc.setUids(null);
2826 newNc.setSSID(null);
2827 }
Etan Cohen107ae952018-12-30 17:59:59 -08002828 if (newNc.getNetworkSpecifier() != null) {
2829 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2830 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002831 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2832 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002833 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2834 newNc.setAdministratorUids(new int[0]);
2835 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002836 if (!checkAnyPermissionOf(mContext,
Benedict Wong53de25f2021-03-24 14:01:51 -07002837 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002838 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002839 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002840 }
lucaslin69e1aa92022-03-22 18:15:09 +08002841 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002842
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002843 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002844 }
2845
Roshan Pius98f59ec2021-02-23 08:47:39 -08002846 /**
2847 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002848 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002849 * NetworkCapabilities.
2850 * Note: This wrapper does not support any sort of invalidation and thus must not be
2851 * persistent or long-lived. It may only be used for the time necessary to
2852 * compute the redactions required by one particular NetworkCallback or
2853 * synchronous call.
2854 */
2855 private class RedactionPermissionChecker {
2856 private final int mCallingPid;
2857 private final int mCallingUid;
2858 @NonNull private final String mCallingPackageName;
2859 @Nullable private final String mCallingAttributionTag;
2860
2861 private Boolean mHasLocationPermission = null;
2862 private Boolean mHasLocalMacAddressPermission = null;
2863 private Boolean mHasSettingsPermission = null;
2864
2865 RedactionPermissionChecker(int callingPid, int callingUid,
2866 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2867 mCallingPid = callingPid;
2868 mCallingUid = callingUid;
2869 mCallingPackageName = callingPackageName;
2870 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002871 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002872
2873 private boolean hasLocationPermissionInternal() {
2874 final long token = Binder.clearCallingIdentity();
2875 try {
2876 return mLocationPermissionChecker.checkLocationPermission(
2877 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2878 null /* message */);
2879 } finally {
2880 Binder.restoreCallingIdentity(token);
2881 }
2882 }
2883
2884 /**
2885 * Returns whether the app holds location permission or not (might return cached result
2886 * if the permission was already checked before).
2887 */
2888 public boolean hasLocationPermission() {
2889 if (mHasLocationPermission == null) {
2890 // If there is no cached result, perform the check now.
2891 mHasLocationPermission = hasLocationPermissionInternal();
2892 }
2893 return mHasLocationPermission;
2894 }
2895
2896 /**
2897 * Returns whether the app holds local mac address permission or not (might return cached
2898 * result if the permission was already checked before).
2899 */
2900 public boolean hasLocalMacAddressPermission() {
2901 if (mHasLocalMacAddressPermission == null) {
2902 // If there is no cached result, perform the check now.
2903 mHasLocalMacAddressPermission =
2904 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2905 }
2906 return mHasLocalMacAddressPermission;
2907 }
2908
2909 /**
2910 * Returns whether the app holds settings permission or not (might return cached
2911 * result if the permission was already checked before).
2912 */
2913 public boolean hasSettingsPermission() {
2914 if (mHasSettingsPermission == null) {
2915 // If there is no cached result, perform the check now.
2916 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2917 }
2918 return mHasSettingsPermission;
2919 }
2920 }
2921
2922 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2923 @NetworkCapabilities.NetCapability long redaction) {
2924 return (redactions & redaction) != 0;
2925 }
2926
2927 /**
2928 * Use the provided |applicableRedactions| to check the receiving app's
2929 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2930 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2931 * before being sent to the corresponding app.
2932 */
2933 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2934 @NetworkCapabilities.RedactionType long applicableRedactions,
2935 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2936 boolean includeLocationSensitiveInfo) {
2937 long redactions = applicableRedactions;
2938 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2939 if (includeLocationSensitiveInfo
2940 && redactionPermissionChecker.hasLocationPermission()) {
2941 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2942 }
2943 }
2944 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2945 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2946 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2947 }
2948 }
2949 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2950 if (redactionPermissionChecker.hasSettingsPermission()) {
2951 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2952 }
2953 }
2954 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002955 }
2956
Qingxi Lib2748102020-01-08 12:51:49 -08002957 @VisibleForTesting
2958 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002959 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002960 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002961 int callingPid, int callingUid, @NonNull String callingPkgName,
2962 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002963 if (nc == null) {
2964 return null;
2965 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002966 // Avoid doing location permission check if the transport info has no location sensitive
2967 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002968 final RedactionPermissionChecker redactionPermissionChecker =
2969 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2970 callingAttributionTag);
2971 final long redactions = retrieveRequiredRedactions(
2972 nc.getApplicableRedactions(), redactionPermissionChecker,
2973 includeLocationSensitiveInfo);
2974 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002975 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002976 // TODO : calling UID is redacted because apps should generally not know what UID is
2977 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002978 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002979 newNc.setOwnerUid(INVALID_UID);
2980 return newNc;
2981 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002982 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2983 if (nc.hasTransport(TRANSPORT_VPN)) {
2984 // Owner UIDs already checked above. No need to re-check.
2985 return newNc;
2986 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002987 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2988 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002989 // compatibility for older apps.
2990 if (!includeLocationSensitiveInfo
2991 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002992 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002993 newNc.setOwnerUid(INVALID_UID);
2994 return newNc;
2995 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002996 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002997 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002998 newNc.setOwnerUid(INVALID_UID);
2999 }
Qingxi Lib2748102020-01-08 12:51:49 -08003000 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08003001 }
3002
lucaslinc582d502022-01-27 09:07:00 +08003003 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09003004 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
3005 LinkProperties lp, int callerPid, int callerUid) {
3006 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08003007 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
3008 // this would be expensive (one more permission check every time any LP callback is
3009 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
3010 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
3011 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09003012
3013 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
3014 final boolean needsSanitization =
3015 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
3016 if (!needsSanitization) {
3017 return new LinkProperties(lp);
3018 }
3019
3020 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09003021 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09003022 }
3023
3024 final LinkProperties newLp = new LinkProperties(lp);
3025 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
3026 // object gets parceled.
3027 newLp.setCaptivePortalApiUrl(null);
3028 newLp.setCaptivePortalData(null);
3029 return newLp;
3030 }
3031
Roshan Pius08c94fb2020-01-16 12:17:17 -08003032 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
3033 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09003034 // There is no need to track the effective UID of the request here. If the caller
3035 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09003036 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09003037 // Unprivileged apps can only pass in null or their own UID.
3038 if (nc.getUids() == null) {
3039 // If the caller passes in null, the callback will also match networks that do not
3040 // apply to its UID, similarly to what it would see if it called getAllNetworks.
3041 // In this case, redact everything in the request immediately. This ensures that the
3042 // app is not able to get any redacted information by filing an unredacted request
3043 // and observing whether the request matches something.
3044 if (nc.getNetworkSpecifier() != null) {
3045 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
3046 }
3047 } else {
3048 nc.setSingleUid(callerUid);
3049 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09003050 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08003051 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07003052 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08003053
3054 // Clear owner UID; this can never come from an app.
3055 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003056 }
3057
Chalard Jean38354d12018-03-20 19:13:57 +09003058 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003059 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09003060 nc.addCapability(NET_CAPABILITY_FOREGROUND);
3061 }
3062 }
3063
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09003064 @Override
3065 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
3066 enforceAccessPermission();
3067 final int callerUid = Binder.getCallingUid();
3068 final long token = Binder.clearCallingIdentity();
3069 try {
3070 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
3071 } finally {
3072 Binder.restoreCallingIdentity(token);
3073 }
3074 }
3075
junyulaiebd15162021-03-03 12:09:05 +08003076 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09003077 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07003078 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08003079 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08003080 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08003081
Serik Beketayev05130302021-01-15 16:47:25 -08003082 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08003083 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08003084 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
3085 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08003086 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08003087 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08003088 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08003089 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
3090 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07003091 }
3092 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09003093 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07003094 }
3095
Jeff Sharkey66fa9682011-08-02 17:22:34 -07003096 @Override
junyulaiebd15162021-03-03 12:09:05 +08003097 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08003098 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08003099 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08003100 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08003101
3102 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
3103 for (Network network : getAllNetworks()) {
3104 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09003105 final boolean includeNetwork = (nai != null) && nai.isCreated();
3106 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08003107 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
3108 // NetworkCapabilities, which may contain UIDs of apps to which the
3109 // network applies. Should the UIDs be cleared so as not to leak or
3110 // interfere ?
3111 result.add(nai.getNetworkStateSnapshot());
3112 }
3113 }
3114 return result;
3115 }
3116
3117 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003118 public boolean isActiveNetworkMetered() {
3119 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003120
Qingxi Lib2748102020-01-08 12:51:49 -08003121 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06003122 if (caps != null) {
3123 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
3124 } else {
3125 // Always return the most conservative value
3126 return true;
3127 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07003128 }
3129
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07003130 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09003131 * Ensures that the system cannot call a particular method.
3132 */
3133 private boolean disallowedBecauseSystemCaller() {
3134 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07003135 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
3136 // for devices launched with Q and above. However, existing devices upgrading to Q and
3137 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003138 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07003139 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003140 log("This method exists only for app backwards compatibility"
3141 + " and must not be called by system services.");
3142 return true;
3143 }
3144 return false;
3145 }
3146
paulhub2c28682021-08-18 18:35:54 +08003147 private int getAppUid(final String app, final UserHandle user) {
3148 final PackageManager pm =
3149 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
3150 final long token = Binder.clearCallingIdentity();
3151 try {
3152 return pm.getPackageUid(app, 0 /* flags */);
3153 } catch (PackageManager.NameNotFoundException e) {
3154 return -1;
3155 } finally {
3156 Binder.restoreCallingIdentity(token);
3157 }
3158 }
3159
3160 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
3161 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
3162 if (getAppUid(packageName, user) != callingUid) {
3163 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
3164 }
3165 }
3166
Lorenzo Colitti23862912018-09-28 11:31:55 +09003167 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08003168 * Ensure that a network route exists to deliver traffic to the specified
3169 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07003170 * @param networkType the type of the network over which traffic to the
3171 * specified host is to be routed
3172 * @param hostAddress the IP address of the host to which the route is
3173 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08003174 * @return {@code true} on success, {@code false} on failure
3175 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09003176 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003177 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
3178 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003179 if (disallowedBecauseSystemCaller()) {
3180 return false;
3181 }
paulhub2c28682021-08-18 18:35:54 +08003182 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003183 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003184 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003185 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003186 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003187
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003188 InetAddress addr;
3189 try {
3190 addr = InetAddress.getByAddress(hostAddress);
3191 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003192 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003193 return false;
3194 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003195
The Android Open Source Project28527d22009-03-03 19:31:44 -08003196 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003197 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003198 return false;
3199 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003200
3201 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
3202 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003203 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003204 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
3205 } else {
3206 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
3207 }
3208 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08003209 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003210
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003211 DetailedState netState;
3212 synchronized (nai) {
3213 netState = nai.networkInfo.getDetailedState();
3214 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003215
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003216 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003217 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003218 log("requestRouteToHostAddress on down network "
3219 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003220 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003221 }
3222 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003223 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003224
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003225 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003226 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003227 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003228 LinkProperties lp;
3229 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003230 synchronized (nai) {
3231 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003232 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003233 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003234 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003235 if (DBG) {
3236 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3237 }
Wink Saville32506bc2013-06-29 21:10:57 -07003238 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003239 } finally {
3240 Binder.restoreCallingIdentity(token);
3241 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003242 }
3243
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003244 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003245 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003246 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003247 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003248 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003249 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003250 if (bestRoute.getGateway().equals(addr)) {
3251 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003252 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003253 } else {
3254 // if we will connect to this through another route, add a direct route
3255 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003256 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003257 }
3258 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003259 if (DBG) log("Adding legacy route " + bestRoute +
3260 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003261
3262 final String dst = bestRoute.getDestinationLinkAddress().toString();
3263 final String nextHop = bestRoute.hasGateway()
3264 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003265 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003266 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3267 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003268 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003269 return false;
3270 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003271 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003272 }
3273
paulhu7c0a2e62021-01-08 00:51:49 +08003274 class DnsResolverUnsolicitedEventCallback extends
3275 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003276 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003277 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003278 try {
3279 mHandler.sendMessage(mHandler.obtainMessage(
3280 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003281 new PrivateDnsValidationUpdate(event.netId,
3282 InetAddresses.parseNumericAddress(event.ipAddress),
3283 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003284 } catch (IllegalArgumentException e) {
3285 loge("Error parsing ip address in validation event");
3286 }
3287 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003288
3289 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003290 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3291 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003292 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3293 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3294 // event callback for certain nai. e.g. cellular. Register here to pass to
3295 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003296 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003297 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3298 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003299 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003300 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003301 }
3302 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003303
3304 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003305 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3306 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3307 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003308 }
dalyk1720e542018-03-05 12:42:22 -05003309
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003310 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003311 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003312 return this.VERSION;
3313 }
3314
3315 @Override
3316 public String getInterfaceHash() {
3317 return this.HASH;
3318 }
paulhu7c0a2e62021-01-08 00:51:49 +08003319 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003320
3321 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003322 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3323 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003324
paulhu7c0a2e62021-01-08 00:51:49 +08003325 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003326 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003327 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003328 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003329 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003330 }
3331 }
3332
Sudheer Shanka9967d462021-03-18 19:09:25 +00003333 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003334 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003335 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003336 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3337 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003338 }
Tommy Webb34f81dc2023-02-20 14:10:55 -05003339
3340 @Override
3341 public void onUidsAllowedTransportsChanged(int[] uids, long[] allowedTransports) {
3342 setUidsAllowedTransports(uids, allowedTransports);
3343 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003344 };
3345
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003346 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003347 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003348 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003349 }
3350
Mark Fasheh7501e762023-05-04 20:23:11 +00003351 static final class UidFrozenStateChangedArgs {
3352 final int[] mUids;
3353 final int[] mFrozenStates;
3354
3355 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3356 mUids = uids;
3357 mFrozenStates = frozenStates;
3358 }
3359 }
3360
3361 private void handleFrozenUids(int[] uids, int[] frozenStates) {
3362 final ArraySet<Range<Integer>> ranges = new ArraySet<>();
3363
3364 for (int i = 0; i < uids.length; i++) {
3365 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
3366 Integer uidAsInteger = Integer.valueOf(uids[i]);
3367 ranges.add(new Range(uidAsInteger, uidAsInteger));
3368 }
3369 }
3370
3371 if (!ranges.isEmpty()) {
3372 final Set<Integer> exemptUids = new ArraySet<>();
3373 try {
3374 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
3375 } catch (Exception e) {
3376 loge("Exception in socket destroy: " + e);
3377 }
3378 }
3379 }
3380
3381 @VisibleForTesting
3382 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
3383
Paul Jensen83f5d572014-08-29 09:54:01 -04003384 private void enforceInternetPermission() {
3385 mContext.enforceCallingOrSelfPermission(
3386 android.Manifest.permission.INTERNET,
3387 "ConnectivityService");
3388 }
3389
The Android Open Source Project28527d22009-03-03 19:31:44 -08003390 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003391 mContext.enforceCallingOrSelfPermission(
3392 android.Manifest.permission.ACCESS_NETWORK_STATE,
3393 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003394 }
3395
lucaslinc582d502022-01-27 09:07:00 +08003396 private boolean checkAccessPermission(int pid, int uid) {
3397 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3398 == PERMISSION_GRANTED;
3399 }
3400
paulhua6ee2122021-02-22 15:40:43 +08003401 /**
3402 * Performs a strict and comprehensive check of whether a calling package is allowed to
3403 * change the state of network, as the condition differs for pre-M, M+, and
3404 * privileged/preinstalled apps. The caller is expected to have either the
3405 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3406 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3407 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3408 * permission and cannot be revoked. See http://b/23597341
3409 *
3410 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3411 * of this app will be updated to the current time.
3412 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003413 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003414 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3415 == PackageManager.PERMISSION_GRANTED) {
3416 return;
3417 }
3418
3419 if (callingPkg == null) {
3420 throw new SecurityException("Calling package name is null.");
3421 }
3422
3423 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3424 final int uid = mDeps.getCallingUid();
3425 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3426 callingPkg, callingAttributionTag, null /* message */);
3427
3428 if (mode == AppOpsManager.MODE_ALLOWED) {
3429 return;
3430 }
3431
3432 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3433 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3434 return;
3435 }
3436
3437 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3438 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3439 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003440 }
3441
Charles He9369e612017-05-15 17:07:18 +01003442 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003443 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003444 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003445 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003446 }
3447
Quang Luong98858d62023-02-11 00:25:24 +00003448 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003449 enforceAnyPermissionOf(mContext,
3450 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003451 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003452 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3453 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3454 }
3455
paulhu8e96a752019-08-12 16:25:11 +08003456 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003457 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003458 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003459 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003460 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003461 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003462 }
3463
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003464 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003465 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003466 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003467 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003468 android.Manifest.permission.NETWORK_SETTINGS,
3469 android.Manifest.permission.NETWORK_FACTORY,
3470 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3471 }
3472
3473 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003474 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003475 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003476 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003477 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3478 android.Manifest.permission.NETWORK_FACTORY,
3479 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3480 }
3481
lucaslin69e1aa92022-03-22 18:15:09 +08003482 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
3483 return PERMISSION_GRANTED == mContext.checkPermission(
3484 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3485 || PERMISSION_GRANTED == mContext.checkPermission(
3486 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3487 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003488 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003489 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003490 }
3491
Chalard Jean9a396cc2018-02-21 18:43:54 +09003492 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003493 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003494 android.Manifest.permission.NETWORK_SETTINGS,
3495 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003496 }
3497
3498 private boolean checkSettingsPermission(int pid, int uid) {
3499 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003500 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3501 || PERMISSION_GRANTED == mContext.checkPermission(
3502 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003503 }
3504
paulhu8e96a752019-08-12 16:25:11 +08003505 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003506 enforceNetworkStackPermissionOr(mContext,
3507 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003508 }
3509
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003510 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003511 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003512 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003513 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003514 }
3515
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003516 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003517 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003518 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3519 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003520 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003521 }
3522
James Mattis8378aec2021-01-26 14:05:36 -08003523 private void enforceOemNetworkPreferencesPermission() {
3524 mContext.enforceCallingOrSelfPermission(
3525 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3526 "ConnectivityService");
3527 }
3528
James Mattisfa270db2021-05-31 17:11:10 -07003529 private void enforceManageTestNetworksPermission() {
3530 mContext.enforceCallingOrSelfPermission(
3531 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3532 "ConnectivityService");
3533 }
3534
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003535 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003536 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003537 android.Manifest.permission.NETWORK_STACK,
3538 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003539 }
3540
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003541 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003542 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003543 android.Manifest.permission.NETWORK_STACK,
3544 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3545 }
3546
paulhu1a407652019-03-22 16:35:06 +08003547 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003548 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003549 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003550 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3551 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003552 }
3553
Paul Hu8fc2a552022-05-04 18:44:42 +08003554 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3555 boolean checkUidsAllowedList) {
3556 if (PermissionUtils.checkAnyPermissionOf(mContext,
3557 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3558 return true;
3559 }
3560
3561 // fallback to ConnectivityInternalPermission
3562 // TODO: Remove this fallback check after all apps have declared
3563 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3564 if (PermissionUtils.checkAnyPermissionOf(mContext,
3565 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3566 return true;
3567 }
3568
3569 // Check whether uid is in allowed on restricted networks list.
3570 if (checkUidsAllowedList
3571 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3572 return true;
3573 }
3574 return false;
3575 }
3576
3577 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3578 final int callingUid = mDeps.getCallingUid();
3579 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3580 throw new SecurityException("ConnectivityService: user " + callingUid
3581 + " has no permission to access restricted network.");
3582 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003583 }
3584
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003585 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003586 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003587 }
3588
Roshan Pius98f59ec2021-02-23 08:47:39 -08003589 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3590 return PERMISSION_GRANTED == mContext.checkPermission(
3591 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3592 }
3593
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003594 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003595 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003596 }
3597
3598 private void sendInetConditionBroadcast(NetworkInfo info) {
3599 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3600 }
3601
Wink Saville4f0de1e2011-08-04 15:01:58 -07003602 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003603 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003604 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003605 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003606 if (info.isFailover()) {
3607 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3608 info.setFailover(false);
3609 }
3610 if (info.getReason() != null) {
3611 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3612 }
3613 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003614 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3615 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003616 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003617 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003618 return intent;
3619 }
3620
3621 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3622 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3623 }
3624
Michael Groover73f69482023-01-27 11:01:25 -06003625 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3626 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003627 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3628 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003629 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003630 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003631 if (!mSystemReady
3632 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003633 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003634 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003635 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003636 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003637 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003638 }
3639
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003640 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003641 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003642 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003643 final NetworkInfo ni = intent.getParcelableExtra(
3644 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003645 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3646 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003647 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003648 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003649 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003650 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003651 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003652 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003653 } finally {
3654 Binder.restoreCallingIdentity(ident);
3655 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003656 }
3657 }
3658
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003659 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3660 NetworkInfo info) {
3661 // Delivery group policy APIs are only available on U+.
Chalard Jean03552c42023-05-29 17:02:43 +09003662 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003663
3664 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3665 try {
3666 // This allows us to discard older broadcasts still waiting to be delivered
3667 // which have the same namespace and key.
3668 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3669 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3670 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003671 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003672 } catch (UnsupportedApiLevelException e) {
3673 Log.wtf(TAG, "Using unsupported API" + e);
3674 }
3675 }
3676
3677 @VisibleForTesting
3678 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3679 final StringBuilder sb = new StringBuilder();
3680 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3681 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3682 sb.append(info.getExtraInfo());
3683 return sb.toString();
3684 }
3685
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003686 /**
Aaron Huang96011892020-06-27 07:18:23 +08003687 * Called by SystemServer through ConnectivityManager when the system is ready.
3688 */
3689 @Override
3690 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003691 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003692 throw new SecurityException("Calling Uid is not system uid.");
3693 }
3694 systemReadyInternal();
3695 }
3696
3697 /**
3698 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003699 */
3700 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003701 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003702 // Load flags after PackageManager is ready to query module version
3703 mFlags.loadFlags(mDeps, mContext);
3704
Aaron Huang9a57acf2020-12-08 10:03:29 +08003705 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3706 // listening network request which is sent by MultipathPolicyTracker won't be added
3707 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3708 // be called after PermissionMonitor#startMonitoring().
3709 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3710 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3711 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003712 final ConditionVariable startMonitoringDone = new ConditionVariable();
3713 mHandler.post(() -> {
3714 mPermissionMonitor.startMonitoring();
3715 startMonitoringDone.open();
3716 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003717 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003718 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003719
Hugo Benichie5220992017-04-26 14:53:28 +09003720 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003721 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003722 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003723 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003724 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003725 }
3726 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003727
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003728 // Create network requests for always-on networks.
3729 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003730
3731 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003732 // Note that updating can be skipped here if the list is empty only because no uid
3733 // rules are applied before system ready. Normally, the empty uid list means to clear
3734 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003735 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3736 updateMobileDataPreferredUids();
3737 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003738
3739 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jean03552c42023-05-29 17:02:43 +09003740 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003741 mBpfNetMaps.setPullAtomCallback(mContext);
3742 }
Paul Hu3c8c8102022-08-25 07:06:16 +00003743 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3744 // have permission problem. While CV#block() is unbounded in time and can in principle block
3745 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3746 // could have blocked forever too.
3747 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003748 }
3749
The Android Open Source Project28527d22009-03-03 19:31:44 -08003750 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003751 * Start listening for default data network activity state changes.
3752 */
3753 @Override
3754 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003755 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003756 }
3757
3758 /**
3759 * Stop listening for default data network activity state changes.
3760 */
3761 @Override
3762 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003763 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003764 }
3765
3766 /**
3767 * Check whether the default network radio is currently active.
3768 */
3769 @Override
3770 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003771 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003772 }
3773
3774 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003775 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003776 * and set it on it's iface.
3777 */
Junyu Lai970963e2022-10-25 15:46:47 +08003778 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003779 final String iface = newLp.getInterfaceName();
3780 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003781 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003782 // Silently ignore unset MTU value.
3783 return;
3784 }
Hansen Kurli04252032022-12-07 11:21:49 +00003785 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3786 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3787 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003788 return;
3789 }
Hansen Kurli04252032022-12-07 11:21:49 +00003790 // Cannot set MTU without interface name
3791 if (TextUtils.isEmpty(iface)) {
3792 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003793 return;
3794 }
sy.yun4aa73922013-09-02 05:24:09 +09003795
Hansen Kurli04252032022-12-07 11:21:49 +00003796 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3797 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003798 return;
3799 }
3800
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003801 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003802 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003803 mNetd.interfaceSetMtu(iface, mtu);
3804 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003805 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003806 }
3807 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003808
Chenbo Feng15416292018-11-08 17:36:21 -08003809 @VisibleForTesting
3810 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003811
Junyu Lai970963e2022-10-25 15:46:47 +08003812 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003813 String[] values = null;
3814 if (tcpBufferSizes != null) {
3815 values = tcpBufferSizes.split(",");
3816 }
3817
3818 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003819 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003820 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3821 values = tcpBufferSizes.split(",");
3822 }
3823
3824 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3825
3826 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003827 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003828
Chenbo Feng15416292018-11-08 17:36:21 -08003829 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3830 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3831 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003832 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003833 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003834 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003835 }
3836 }
3837
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003838 @Override
3839 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003840 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003841 NETWORK_RESTORE_DELAY_PROP_NAME);
3842 if(restoreDefaultNetworkDelayStr != null &&
3843 restoreDefaultNetworkDelayStr.length() != 0) {
3844 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003845 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003846 } catch (NumberFormatException e) {
3847 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003848 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003849 // if the system property isn't set, use the value for the apn type
3850 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3851
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003852 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3853 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003854 }
3855 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003856 }
3857
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003858 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003859 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003860 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003861 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003862 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003863 // Start gathering diagnostic information.
3864 netDiags.add(new NetworkDiagnostics(
3865 nai.network,
3866 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003867 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003868 DIAG_TIME_MS));
3869 }
3870
3871 for (NetworkDiagnostics netDiag : netDiags) {
3872 pw.println();
3873 netDiag.waitForMeasurements();
3874 netDiag.dump(pw);
3875 }
3876 }
3877
The Android Open Source Project28527d22009-03-03 19:31:44 -08003878 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003879 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3880 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003881 if (!checkDumpPermission(mContext, TAG, writer)) return;
3882
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003883 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003884 }
3885
lucaslin99473f62020-12-10 15:10:54 +08003886 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3887 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3888 != PackageManager.PERMISSION_GRANTED) {
3889 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003890 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003891 + " due to missing android.permission.DUMP permission");
3892 return false;
3893 } else {
3894 return true;
3895 }
3896 }
3897
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003898 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003899 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003900
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003901 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003902 dumpNetworkDiagnostics(pw);
3903 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003904 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003905 dumpNetworks(pw);
3906 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003907 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003908 dumpNetworkRequests(pw);
3909 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003910 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3911 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3912 dumpTrafficController(pw, fd, verbose);
3913 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003914 }
Erik Kline9647f382015-06-05 17:47:34 +09003915
Junyu Lai0da479b2022-04-20 15:06:29 +08003916 pw.println("NetworkProviders for:");
3917 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003918 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003919 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003920 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003921 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003922 pw.println();
3923
Chalard Jean5b409c72021-02-04 13:12:59 +09003924 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003925 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003926 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003927 pw.println("none");
3928 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003929 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003930 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003931 pw.println();
3932
James Mattis8b298a02021-06-01 22:34:04 -07003933 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003934 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003935 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003936 pw.decreaseIndent();
3937 pw.println();
3938
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003939 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003940 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003941 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003942 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003943 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003944
junyulaif2c67e42018-08-07 19:50:45 +08003945 pw.println("Status for known UIDs:");
3946 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003947 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003948 for (int i = 0; i < size; i++) {
3949 // Don't crash if the array is modified while dumping in bugreports.
3950 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003951 final int uid = mUidBlockedReasons.keyAt(i);
3952 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3953 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003954 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003955 } catch (ArrayIndexOutOfBoundsException e) {
3956 pw.println(" ArrayIndexOutOfBoundsException");
3957 } catch (ConcurrentModificationException e) {
3958 pw.println(" ConcurrentModificationException");
3959 }
3960 }
3961 pw.println();
3962 pw.decreaseIndent();
3963
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003964 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003965 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003966 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003967 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003968 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003969
Junyu Lai0da479b2022-04-20 15:06:29 +08003970 pw.println("Network Offers:");
3971 pw.increaseIndent();
3972 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3973 pw.println(offerInfo.offer);
3974 }
3975 pw.decreaseIndent();
3976 pw.println();
3977
Robert Greenwalt94e22142014-07-30 16:31:24 -07003978 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003979
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003980 pw.println();
markchien5e866652019-09-30 14:40:57 +08003981 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003982
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003983 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003984 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003985
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003986 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003987
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003988 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003989 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003990 pw.println("mNetworkRequestInfoLogs (most recent first):");
3991 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003992 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003993 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003994
3995 pw.println();
3996 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3997 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003998 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003999 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09004000
4001 pw.println();
4002 pw.println("NetTransition WakeLock activity (most recent first):");
4003 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09004004 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
4005 pw.println("total releases: " + mTotalWakelockReleases);
4006 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
4007 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
4008 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
4009 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4010 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
4011 }
James Mattiscb1e0362021-04-06 17:07:42 -07004012 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004013
4014 pw.println();
4015 pw.println("bandwidth update requests (by uid):");
4016 pw.increaseIndent();
4017 synchronized (mBandwidthRequests) {
4018 for (int i = 0; i < mBandwidthRequests.size(); i++) {
4019 pw.println("[" + mBandwidthRequests.keyAt(i)
4020 + "]: " + mBandwidthRequests.valueAt(i));
4021 }
4022 }
4023 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004024 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004025
James Mattiscb1e0362021-04-06 17:07:42 -07004026 pw.println();
4027 pw.println("mOemNetworkPreferencesLogs (most recent first):");
4028 pw.increaseIndent();
4029 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09004030 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07004031 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09004032
4033 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00004034
4035 pw.println();
4036 pw.println("Permission Monitor:");
4037 pw.increaseIndent();
4038 mPermissionMonitor.dump(pw);
4039 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08004040
4041 pw.println();
4042 pw.println("Legacy network activity:");
4043 pw.increaseIndent();
4044 mNetworkActivityTracker.dump(pw);
4045 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08004046 }
4047
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004048 private void dumpNetworks(IndentingPrintWriter pw) {
4049 for (NetworkAgentInfo nai : networksSortedById()) {
4050 pw.println(nai.toString());
4051 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08004052 pw.println("Nat464Xlat:");
4053 pw.increaseIndent();
4054 nai.dumpNat464Xlat(pw);
4055 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004056 pw.println(String.format(
4057 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
4058 nai.numForegroundNetworkRequests(),
4059 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
4060 nai.numBackgroundNetworkRequests(),
4061 nai.numNetworkRequests()));
4062 pw.increaseIndent();
4063 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4064 pw.println(nai.requestAt(i).toString());
4065 }
4066 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004067 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004068 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004069 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004070 pw.decreaseIndent();
4071 pw.decreaseIndent();
4072 }
4073 }
4074
James Mattis8b298a02021-06-01 22:34:04 -07004075 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
4076 if (!mProfileNetworkPreferences.isEmpty()) {
4077 pw.println("Profile preferences:");
4078 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09004079 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07004080 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08004081 }
James Mattis8b298a02021-06-01 22:34:04 -07004082 if (!mOemNetworkPreferences.isEmpty()) {
4083 pw.println("OEM preferences:");
4084 pw.increaseIndent();
4085 pw.println(mOemNetworkPreferences);
4086 pw.decreaseIndent();
4087 }
4088 if (!mMobileDataPreferredUids.isEmpty()) {
4089 pw.println("Mobile data preferred UIDs:");
4090 pw.increaseIndent();
4091 pw.println(mMobileDataPreferredUids);
4092 pw.decreaseIndent();
4093 }
James Mattis45d81842021-01-10 14:24:24 -08004094
James Mattis8b298a02021-06-01 22:34:04 -07004095 pw.println("Default requests:");
4096 pw.increaseIndent();
4097 dumpPerAppDefaultRequests(pw);
4098 pw.decreaseIndent();
4099 }
4100
4101 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08004102 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
4103 if (mDefaultRequest == defaultRequest) {
4104 continue;
4105 }
4106
James Mattis8b298a02021-06-01 22:34:04 -07004107 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
4108 final String networkOutput;
4109 if (null == satisfier) {
4110 networkOutput = "null";
4111 } else if (mNoServiceNetwork.equals(satisfier)) {
4112 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08004113 } else {
James Mattis8b298a02021-06-01 22:34:04 -07004114 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08004115 }
James Mattis8b298a02021-06-01 22:34:04 -07004116 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
4117 ? "" : " asUid: " + defaultRequest.mAsUid;
4118 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
4119 + defaultRequest.mPid + asUidString + "]";
4120 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
4121 + " Preference order: " + defaultRequest.mPreferenceOrder
4122 + " Tracked UIDs: " + defaultRequest.getUids();
4123 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08004124 }
4125 }
4126
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004127 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08004128 NetworkRequestInfo[] infos = null;
4129 while (infos == null) {
4130 try {
4131 infos = requestsSortedById();
4132 } catch (ConcurrentModificationException e) {
4133 // mNetworkRequests should only be accessed from handler thread, except dump().
4134 // As dump() is never called in normal usage, it would be needlessly expensive
4135 // to lock the collection only for its benefit. Instead, retry getting the
4136 // requests if ConcurrentModificationException is thrown during dump().
4137 }
4138 }
4139 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004140 pw.println(nri.toString());
4141 }
4142 }
4143
Ken Chene6d511f2022-01-25 11:10:42 +08004144 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4145 boolean verbose) {
4146 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004147 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004148 } catch (ServiceSpecificException e) {
4149 pw.println(e.getMessage());
4150 } catch (IOException e) {
4151 loge("Dump BPF maps failed, " + e);
4152 }
4153 }
4154
Chalard Jean524f0b12021-10-25 21:11:56 +09004155 private void dumpAllRequestInfoLogsToLogcat() {
4156 try (PrintWriter logPw = new PrintWriter(new Writer() {
4157 @Override
4158 public void write(final char[] cbuf, final int off, final int len) {
4159 // This method is called with 0-length and 1-length arrays for empty strings
4160 // or strings containing only the DEL character.
4161 if (len <= 1) return;
4162 Log.e(TAG, new String(cbuf, off, len));
4163 }
4164 @Override public void flush() {}
4165 @Override public void close() {}
4166 })) {
4167 mNetworkRequestInfoLogs.dump(logPw);
4168 }
4169 }
4170
Hugo Benichia480ba52018-09-03 08:19:02 +09004171 /**
4172 * Return an array of all current NetworkAgentInfos sorted by network id.
4173 */
4174 private NetworkAgentInfo[] networksSortedById() {
4175 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004176 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004177 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004178 return networks;
4179 }
4180
4181 /**
4182 * Return an array of all current NetworkRequest sorted by request id.
4183 */
James Mattis258ea3c2020-11-15 15:04:40 -08004184 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004185 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004186 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004187 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004188 // Sort the array based off the NRI containing the min requestId in its requests.
4189 Arrays.sort(requests,
4190 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4191 Comparator.comparingInt(req -> req.requestId)).requestId
4192 )
4193 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004194 return requests;
4195 }
4196
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004197 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004198 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004199 if (officialNai != null && officialNai.equals(nai)) return true;
4200 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004201 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004202 " - " + nai);
4203 }
4204 return false;
4205 }
4206
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004207 private boolean isDisconnectRequest(Message msg) {
4208 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4209 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4210 return info.getState() == NetworkInfo.State.DISCONNECTED;
4211 }
4212
Robert Greenwalt2034b912009-08-12 16:08:25 -07004213 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004214 private class NetworkStateTrackerHandler extends Handler {
4215 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004216 super(looper);
4217 }
4218
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004219 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004220 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4221 final NetworkAgentInfo nai = arg.first;
4222 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004223 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004224 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004225 }
4226 return;
4227 }
4228
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004229 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004230 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004231 return;
4232 }
4233
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004234 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004235 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09004236 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
4237 final NetworkCapabilities sanitized =
4238 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004239 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004240 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004241 break;
4242 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004243 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004244 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004245 processLinkPropertiesFromAgent(nai, newLp);
4246 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004247 break;
4248 }
4249 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004250 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004251 updateNetworkInfo(nai, info);
4252 break;
4253 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004254 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004255 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004256 break;
4257 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004258 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004259 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004260 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004261 // Note that if the NAI had been connected, this would affect the
4262 // score, and therefore would require re-mixing the score and performing
4263 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004264 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004265 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4266 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004267 // Mark the network as temporarily accepting partial connectivity so that it
4268 // will be validated (and possibly become default) even if it only provides
4269 // partial internet access. Note that if user connects to partial connectivity
4270 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4271 // out of wifi coverage) and if the same wifi is available again, the device
4272 // will auto connect to this wifi even though the wifi has "no internet".
4273 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004274 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004275 break;
4276 }
junyulai011b1f12019-01-03 18:50:15 +08004277 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004278 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004279 break;
4280 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004281 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004282 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004283 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004284
4285 if (isLegacyLockdownNai(nai)
4286 && (underlying == null || underlying.size() != 1)) {
4287 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4288 + " must have exactly one underlying network: " + underlying);
4289 }
4290
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004291 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4292 nai.declaredUnderlyingNetworks = (underlying != null)
4293 ? underlying.toArray(new Network[0]) : null;
4294
4295 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4296 if (DBG) {
4297 log(nai.toShortString() + " changed underlying networks to "
4298 + Arrays.toString(nai.declaredUnderlyingNetworks));
4299 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004300 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004301 notifyIfacesChangedForNetworkStats();
4302 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004303 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004304 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004305 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4306 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4307 nai.teardownDelayMs = msg.arg1;
4308 } else {
4309 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4310 }
Chalard Jean550b5212021-03-05 23:07:53 +09004311 break;
4312 }
4313 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4314 nai.setLingerDuration((int) arg.second);
4315 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004316 }
Tyler Wear72388212021-09-09 14:49:02 -07004317 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4318 DscpPolicy policy = (DscpPolicy) arg.second;
4319 if (mDscpPolicyTracker != null) {
4320 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4321 }
4322 break;
4323 }
4324 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4325 if (mDscpPolicyTracker != null) {
4326 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4327 }
4328 break;
4329 }
4330 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4331 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004332 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004333 }
4334 break;
4335 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004336 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09004337 if (!nai.everConnected()) {
4338 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4339 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004340 teardownUnneededNetwork(nai);
4341 break;
4342 }
4343
4344 if (nai.isDestroyed()) {
4345 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4346 + ", ignoring");
4347 break;
4348 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004349
4350 final int timeoutMs = (int) arg.second;
4351 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4352 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4353 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4354 }
4355
4356 // Marking a network awaiting replacement is used to ensure that any requests
4357 // satisfied by the network do not switch to another network until a
4358 // replacement is available or the wait for a replacement times out.
4359 // If the network is inactive (i.e., nascent or lingering), then there are no
4360 // such requests, and there is no point keeping it. Just tear it down.
4361 // Note that setLingerDuration(0) cannot be used to do this because the network
4362 // could be nascent.
4363 nai.clearInactivityState();
4364 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4365 Log.d(TAG, nai.toShortString()
4366 + " marked awaiting replacement is unneeded, tearing down instead");
4367 teardownUnneededNetwork(nai);
4368 break;
4369 }
4370
4371 Log.d(TAG, "Marking " + nai.toShortString()
4372 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4373 destroyNativeNetwork(nai);
4374
4375 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4376 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4377 // consider the fact that the network could already have disconnected or been
4378 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4379 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4380 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4381 mKeepaliveTracker.handleStopAllKeepalives(nai,
4382 SocketKeepalive.ERROR_INVALID_NETWORK);
4383
4384 nai.updateScoreForNetworkAgentUpdate();
4385 // This rematch is almost certainly not going to result in any changes, because
4386 // the destroyed flag is only just above the "current satisfier wins"
4387 // tie-breaker. But technically anything that affects scoring should rematch.
4388 rematchAllNetworksAndRequests();
Jean Chalard01a7d322023-06-27 08:54:23 +00004389 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004390 break;
4391 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004392 }
4393 }
4394
4395 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004396 final int netId = msg.arg2;
4397 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004398 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004399 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004400 switch (msg.what) {
4401 default:
4402 return false;
lucasline117e2e2019-10-22 18:27:33 +08004403 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004404 if (nai == null) {
4405 break;
4406 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004407 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4408 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004409 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004410 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004411 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004412 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004413 if (probePrivateDnsCompleted) {
4414 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4415 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004416 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004417 }
4418 // Only show the notification when the private DNS is broken and the
4419 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004420 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004421 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4422 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004423 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004424 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4425 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4426 // private DNS is broken, it means this network is being reevaluated.
4427 // Either probing private DNS is not necessary any more or it hasn't been
4428 // done yet. In either case, the networkCapabilities should be updated to
4429 // reflect the new status.
4430 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004431 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004432 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004433 }
4434 break;
4435 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004436 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004437 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4438
Erik Kline31b4a9e2018-01-11 21:07:29 +09004439 if (nai == null) break;
4440
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004441 handleNetworkTested(nai, results.mTestResult,
4442 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004443 break;
4444 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004445 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004446 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004447 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004448 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004449 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004450 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004451 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4452 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004453 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004454 if (nai == null) {
4455 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4456 break;
4457 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004458 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004459 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004460 (PendingIntent) msg.obj,
4461 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004462 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004463 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004464 break;
4465 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004466 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004467 if (nai == null) break;
4468
Erik Kline9a62f012018-03-21 07:18:33 -07004469 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004470 break;
4471 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004472 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004473 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004474 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004475 break;
4476 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004477 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004478 return true;
4479 }
4480
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004481 private void handleNetworkTested(
4482 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004483 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4484 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004485 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004486
4487 // If there is any kind of working networking, then the NAI has been evaluated
4488 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4489 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004490 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004491 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004492 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4493 // any callback that receives onAvailable for that rematch receives an extra caps
4494 // callback. To prevent that, update the score in the agent so the updates below won't
4495 // see an update to both caps and score at the same time.
4496 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004497 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4498
he_won.hwang881307a2022-03-15 21:23:52 +09004499 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4500 // Assume the validation failure is due to a temporary failure after roaming
4501 // and ignore it. NetworkMonitor will continue to retry validation. If it
4502 // continues to fail after the block timeout expires, the network will be
4503 // marked unvalidated. If it succeeds, then validation state will not change.
4504 return;
4505 }
4506
Chalard Jean254bd162022-08-25 13:04:51 +09004507 final boolean wasValidated = nai.isValidated();
4508 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004509 final boolean wasPortal = nai.captivePortalDetected();
4510 nai.setPartialConnectivity(partial);
4511 nai.setCaptivePortalDetected(portal);
4512 nai.updateScoreForNetworkAgentUpdate();
4513 final boolean partialConnectivityChanged = (wasPartial != partial);
4514 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004515
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004516 if (DBG) {
4517 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4518 ? " with redirect to " + redirectUrl
4519 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004520 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004521 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004522 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004523 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004524 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004525 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004526 if (valid) {
4527 handleFreshlyValidatedNetwork(nai);
4528 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4529 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004530 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004531 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004532 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004533 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004534 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004535 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004536 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004537 NotificationType.PRIVATE_DNS_BROKEN);
4538 // If network becomes valid, the hasShownBroken should be reset for
4539 // that network so that the notification will be fired when the private
4540 // DNS is broken again.
4541 nai.networkAgentConfig.hasShownBroken = false;
4542 }
4543 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004544 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004545 } else if (portalChanged) {
4546 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
4547 == getCaptivePortalMode()) {
4548 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4549 nai.onPreventAutomaticReconnect();
4550 teardownUnneededNetwork(nai);
4551 return;
4552 } else {
4553 updateCapabilitiesForNetwork(nai);
4554 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004555 } else if (becameEvaluated) {
4556 // If valid or partial connectivity changed, updateCapabilities* has
4557 // done the rematch.
4558 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004559 }
4560 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004561
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004562 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004563 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004564 nai.onValidationStatusChanged(
4565 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4566 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004567
4568 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004569 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004570 // immediately. Re-notify partial connectivity silently if no internet
4571 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004572 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004573 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004574 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4575 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004576 }
4577
Chalard Jean254bd162022-08-25 13:04:51 +09004578 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004579 handleNetworkUnvalidated(nai);
4580 }
4581 }
4582
Calvin Ondada1452016-10-11 15:10:46 -07004583 private int getCaptivePortalMode() {
4584 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004585 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4586 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004587 }
4588
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004589 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4590 switch (msg.what) {
4591 default:
4592 return false;
4593 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4594 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4595 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4596 handleLingerComplete(nai);
4597 }
4598 break;
4599 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004600 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4601 handleNetworkAgentRegistered(msg);
4602 break;
4603 }
4604 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4605 handleNetworkAgentDisconnected(msg);
4606 break;
4607 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004608 }
4609 return true;
4610 }
4611
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004612 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004613 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004614 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004615 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004616 maybeHandleNetworkAgentMessage(msg);
4617 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004618 }
4619 }
4620
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004621 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004622 private final int mNetId;
4623 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004624
4625 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004626 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004627 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004628 }
4629
4630 @Override
4631 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4632 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004633 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004634 }
4635
4636 @Override
4637 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004638 // Legacy version of notifyNetworkTestedWithExtras.
4639 // Would only be called if the system has a NetworkStack module older than the
4640 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004641 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004642 }
4643
4644 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004645 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004646 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4647 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004648 final Message msg = mTrackerHandler.obtainMessage(
4649 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004650 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004651 new NetworkTestedResults(
4652 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004653 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004654
4655 // Invoke ConnectivityReport generation for this Network test event.
4656 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4657 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004658
Cody Kestingf1120be2020-08-03 18:01:40 -07004659 // NetworkMonitor reports the network validation result as a bitmask while
4660 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4661 // logical value for ConnectivityDiagnostics.
4662 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4663 p.result);
4664
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004665 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004666 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004667 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4668 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4669
Aaron Huang959d3642021-01-21 15:47:41 +08004670 ConnectivityReportEvent reportEvent =
4671 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4672 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004673 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004674 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004675 }
4676
4677 @Override
4678 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4679 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4680 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004681 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004682 }
4683
4684 @Override
lucasline117e2e2019-10-22 18:27:33 +08004685 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4686 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4687 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004688 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004689 }
4690
4691 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004692 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4693 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4694 EVENT_CAPPORT_DATA_CHANGED,
4695 0, mNetId, data));
4696 }
4697
4698 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004699 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004700 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004701 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004702
4703 final PendingIntent pendingIntent;
4704 // Only the system server can register notifications with package "android"
4705 final long token = Binder.clearCallingIdentity();
4706 try {
paulhu7746e4e2020-06-09 19:07:03 +08004707 pendingIntent = PendingIntent.getBroadcast(
4708 mContext,
4709 0 /* requestCode */,
4710 intent,
4711 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004712 } finally {
4713 Binder.restoreCallingIdentity(token);
4714 }
4715 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4716 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004717 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004718 }
4719
4720 @Override
4721 public void hideProvisioningNotification() {
4722 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004723 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004724 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004725
4726 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004727 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004728 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004729 }
4730
4731 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004732 public int getInterfaceVersion() {
4733 return this.VERSION;
4734 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004735
4736 @Override
4737 public String getInterfaceHash() {
4738 return this.HASH;
4739 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004740 }
4741
Cody Kestingf1120be2020-08-03 18:01:40 -07004742 /**
4743 * Converts the given NetworkMonitor-specific validation result bitmask to a
4744 * ConnectivityDiagnostics-specific validation result int.
4745 */
4746 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4747 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4748 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4749 }
4750 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4751 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4752 }
4753 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4754 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4755 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4756 }
4757
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004758 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004759 log("Data stall detected with methods: " + p.detectionMethod);
4760
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004761 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004762 int detectionMethod = 0;
4763 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4764 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4765 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4766 }
4767 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4768 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4769 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4770 p.tcpMetricsCollectionPeriodMillis);
4771 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004772 }
4773
Cody Kestingf53a0752020-04-15 12:33:28 -07004774 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004775 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004776 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004777
4778 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4779 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4780 // the cost of going through two handlers.
4781 mConnectivityDiagnosticsHandler.sendMessage(msg);
4782 }
4783
Cody Kestingb37958e2020-05-15 10:36:01 -07004784 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4785 return (p.detectionMethod & detectionMethod) != 0;
4786 }
4787
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004788 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4789 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004790 }
4791
Erik Klinea73af002018-06-26 18:53:43 +09004792 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4793 if (nai == null) return;
4794 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4795 // in order to restart a validation pass from within netd.
4796 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4797 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004798 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004799 }
4800 }
4801
Erik Kline31b4a9e2018-01-11 21:07:29 +09004802 private void handlePrivateDnsSettingsChanged() {
4803 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4804
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004805 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004806 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004807 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004808 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4809 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004810 }
4811 }
4812
Erik Kline9a62f012018-03-21 07:18:33 -07004813 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4814 // Private DNS only ever applies to networks that might provide
4815 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004816 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004817
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004818 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004819 // schedule DNS resolutions. If a DNS resolution is required the
4820 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004821 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004822
4823 // With Private DNS bypass support, we can proceed to update the
4824 // Private DNS config immediately, even if we're in strict mode
4825 // and have not yet resolved the provider name into a set of IPs.
4826 updatePrivateDns(nai, cfg);
4827 }
4828
4829 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4830 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004831 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004832 }
4833
dalyk1720e542018-03-05 12:42:22 -05004834 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4835 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4836 if (nai == null) {
4837 return;
4838 }
4839 mDnsManager.updatePrivateDnsValidation(update);
4840 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4841 }
4842
paulhu7c0a2e62021-01-08 00:51:49 +08004843 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004844 int prefixLength) {
4845 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4846 if (nai == null) return;
4847
paulhu7c0a2e62021-01-08 00:51:49 +08004848 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4849 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004850
4851 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004852 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004853 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004854 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004855 prefixLength);
4856 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004857 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004858 return;
4859 }
4860 }
4861
Lorenzo Colittid523d142020-04-01 20:16:30 +09004862 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004863 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4864 }
4865
Hai Shalome58bdc62021-01-11 18:45:34 -08004866 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004867 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004868 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004869 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4870 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4871 }
4872
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004873 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004874 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004875 * @param nai the agent info to update
4876 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004877 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004878 */
junyulai2b6f0c22021-02-03 20:15:30 +08004879 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4880 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4881 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004882 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004883 // one lingered request, set inactive.
4884 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004885 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004886 if (DBG) log("Unsetting inactive " + nai.toShortString());
4887 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004888 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004889 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004890 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004891 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4892 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004893 }
junyulai2b6f0c22021-02-03 20:15:30 +08004894 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004895 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004896 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004897 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004898 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004899 }
4900
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004901 private void handleNetworkAgentRegistered(Message msg) {
4902 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4903 if (!mNetworkAgentInfos.contains(nai)) {
4904 return;
4905 }
4906
4907 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4908 if (VDBG) log("NetworkAgent registered");
4909 } else {
4910 loge("Error connecting NetworkAgent");
4911 mNetworkAgentInfos.remove(nai);
4912 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004913 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004914 synchronized (mNetworkForNetId) {
4915 mNetworkForNetId.remove(nai.network.getNetId());
Tommy Webb34f81dc2023-02-20 14:10:55 -05004916 mNetIdToAllowlist.remove(nai.network.getNetId());
4917 mNetIdToDisallowedUids.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004918 }
Tommy Webb34f81dc2023-02-20 14:10:55 -05004919 updateDisallowedUidsForNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004920 mNetIdManager.releaseNetId(nai.network.getNetId());
4921 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004922 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004923 }
4924 }
4925 }
Paul Jensend5f53392014-11-25 15:26:53 -05004926
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09004927 @VisibleForTesting
4928 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jean2e50cc92023-06-27 19:16:00 +09004929 // The feature of creating the networks immediately was slated for U, but race conditions
4930 // detected late required this was flagged off.
4931 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
4932 // in NetworkAgentTest.
4933 return false;
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09004934 }
4935
4936 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
4937 @NonNull NetworkInfo.State state) {
4938 if (nai.isCreated()) return false;
4939 if (state == NetworkInfo.State.CONNECTED) return true;
4940 if (state != NetworkInfo.State.CONNECTING) {
4941 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti38560562023-06-07 11:34:05 +09004942 if (shouldCreateNetworksImmediately()) {
4943 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
4944 }
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09004945 return false;
4946 }
4947 return nai.isVPN() || shouldCreateNetworksImmediately();
4948 }
4949
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004950 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004951 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004952 }
4953
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004954 @VisibleForTesting
4955 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004956 // T+ devices should use unregisterAfterReplacement.
Chalard Jean03552c42023-05-29 17:02:43 +09004957 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004958
4959 // If the network never roamed, return false. The check below is not sufficient if time
4960 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4961 if (nai.lastRoamTime == 0) return false;
4962
he_won.hwang881307a2022-03-15 21:23:52 +09004963 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4964 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004965 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004966 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004967 final long currentTimeMs = SystemClock.elapsedRealtime();
4968 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004969 if (timeSinceLastRoam <= blockTimeOut) {
4970 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4971 return true;
4972 }
4973 }
4974 return false;
4975 }
4976
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004977 private void handleNetworkAgentDisconnected(Message msg) {
4978 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004979 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004980 }
4981
Chalard Jeand9fffc32018-05-11 20:19:20 +09004982 // Destroys a network, remove references to it from the internal state managed by
4983 // ConnectivityService, free its interfaces and clean up.
4984 // Must be called on the Handler thread.
4985 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004986 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004987
4988 if (!mNetworkAgentInfos.contains(nai)) return;
4989
Chalard Jeand9fffc32018-05-11 20:19:20 +09004990 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004991 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004992 }
lucaslinb25c9a62019-02-12 15:30:13 +08004993 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004994 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004995 // A network agent has disconnected.
4996 // TODO - if we move the logic to the network agent (have them disconnect
4997 // because they lost all their requests or because their score isn't good)
4998 // then they would disconnect organically, report their new state and then
4999 // disconnect the channel.
wangshengrjxtjcb9b5334d2023-05-09 09:51:06 +08005000 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005001 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
5002 null, null);
5003 }
Chalard Jean5b409c72021-02-04 13:12:59 +09005004 final boolean wasDefault = isDefaultNetwork(nai);
5005 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005006 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09005007 }
5008 notifyIfacesChangedForNetworkStats();
5009 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
5010 // by other networks that are already connected. Perhaps that can be done by
5011 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
5012 // of rematchAllNetworksAndRequests
5013 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08005014 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07005015
5016 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005017 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
5018 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08005019 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005020 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005021 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005022 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09005023 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005024 synchronized (mNetworkForNetId) {
5025 // Remove the NetworkAgent, but don't mark the netId as
5026 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005027 mNetworkForNetId.remove(nai.network.getNetId());
Tommy Webb34f81dc2023-02-20 14:10:55 -05005028 mNetIdToAllowlist.remove(nai.network.getNetId());
5029 mNetIdToDisallowedUids.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005030 }
Tommy Webb34f81dc2023-02-20 14:10:55 -05005031 updateDisallowedUidsForNetwork(nai);
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09005032 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08005033 // Update allowed network lists in netd. This should be called after removing nai
5034 // from mNetworkAgentInfos.
5035 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005036 // Remove all previously satisfied requests.
5037 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005038 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09005039 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08005040 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08005041 if (currentNetwork != null
5042 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005043 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09005044 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
5045 // rematch not to keep disconnected agents instead of setting it here ; this
5046 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08005047 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09005048 for (final NetworkOfferInfo noi : mNetworkOffers) {
5049 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08005050 }
James Mattise3ef1912020-12-20 11:09:58 -08005051
Chalard Jean5b409c72021-02-04 13:12:59 +09005052 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08005053 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09005054 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08005055 // network, because while incorrect this is the closest to the old (also
5056 // incorrect) behavior.
5057 mNetworkActivityTracker.updateDataActivityTracking(
5058 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08005059 ensureNetworkTransitionWakelock(nai.toShortString());
5060 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005061 }
5062 }
junyulai2b6f0c22021-02-03 20:15:30 +08005063 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08005064 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09005065 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08005066 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09005067 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005068 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005069 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005070
Aaron Huang25ef1712021-06-08 13:11:45 +08005071 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
5072 // The obvious place to do this would be in makeDefault(), however makeDefault() is
5073 // not called by the rematch in this case. This is because the code above unset
5074 // this network from the default request's satisfier, and that is what the rematch
5075 // is using as its source data to know what the old satisfier was. So as far as the
5076 // rematch above is concerned, the old default network was null.
5077 // Therefore if there is no new default, the default network was null and is still
5078 // null, thus there was no change so makeDefault() is not called. So if the old
5079 // network had a proxy and there is no new default, the proxy tracker should be told
5080 // that there is no longer a default proxy.
5081 // Strictly speaking this is not essential because having a proxy setting when
5082 // there is no network is harmless, but it's still counter-intuitive so reset to null.
5083 mProxyTracker.setDefaultProxy(null);
5084 }
5085
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005086 // Immediate teardown.
5087 if (nai.teardownDelayMs == 0) {
5088 destroyNetwork(nai);
5089 return;
5090 }
5091
5092 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09005093 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05305094 try {
5095 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
5096 } catch (RemoteException e) {
5097 Log.d(TAG, "Error marking network restricted during teardown: ", e);
5098 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005099 }
5100 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
5101 }
5102
5103 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005104 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005105 // Tell netd to clean up the configuration for this network
5106 // (routing rules, DNS, etc).
5107 // This may be slow as it requires a lot of netd shelling out to ip and
5108 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09005109 // after we've rematched networks with requests (which might change the default
5110 // network or service a new request from an app), so network traffic isn't interrupted
5111 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08005112 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005113 }
Chalard Jean03552c42023-05-29 17:02:43 +09005114 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005115 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
5116 // This can never run if the code above runs because shouldDestroyNativeNetwork is
5117 // false if the network was never created.
5118 // TODO: delete when S is no longer supported.
5119 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005120 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08005121 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005122 }
5123
Ken Chen6df7a902021-04-09 15:08:42 +08005124 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08005125 try {
5126 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08005127 final NativeNetworkConfig config;
5128 if (nai.isVPN()) {
5129 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08005130 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08005131 return false;
5132 }
5133 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
5134 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005135 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08005136 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08005137 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08005138 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005139 getNetworkPermission(nai.networkCapabilities),
5140 false /* secure */,
5141 VpnManager.TYPE_VPN_NONE,
5142 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005143 }
Ken Chen6df7a902021-04-09 15:08:42 +08005144 mNetd.networkCreate(config);
5145 mDnsResolver.createNetworkCache(nai.network.getNetId());
5146 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
5147 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08005148 return true;
5149 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005150 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005151 return false;
5152 }
5153 }
5154
Ken Chen6df7a902021-04-09 15:08:42 +08005155 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005156 if (mDscpPolicyTracker != null) {
5157 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5158 }
Luke Huangfdd11f82019-04-09 18:41:49 +08005159 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005160 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005161 } catch (RemoteException | ServiceSpecificException e) {
5162 loge("Exception destroying network(networkDestroy): " + e);
5163 }
5164 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005165 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005166 } catch (RemoteException | ServiceSpecificException e) {
5167 loge("Exception destroying network: " + e);
5168 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005169 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5170 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5171 // gets created, could add data to DnsManager data structures that will never get deleted.
5172 mDnsManager.removeNetwork(nai.network);
5173
5174 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005175 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005176 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5177 }
5178
Chalard Jean254bd162022-08-25 13:04:51 +09005179 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005180 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005181 }
5182
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005183 // If this method proves to be too slow then we can maintain a separate
5184 // pendingIntent => NetworkRequestInfo map.
5185 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5186 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005187 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5188 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5189 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005190 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005191 return entry.getValue();
5192 }
5193 }
5194 return null;
5195 }
5196
Chalard Jean524f0b12021-10-25 21:11:56 +09005197 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jean03552c42023-05-29 17:02:43 +09005198 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005199 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5200 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5201 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5202 // bug is fixed.
5203 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005204 throw new IllegalStateException("This NRI is already registered. New : " + nri
5205 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005206 }
5207 }
5208 }
5209 }
5210
Chalard Jeanac9ace02022-01-26 16:54:05 +09005211 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5212 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005213 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09005214 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
5215 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005216 }
5217 return false;
5218 }
5219
James Mattisf7027322020-12-13 16:28:14 -08005220 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005221 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005222 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5223 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5224 final NetworkRequestInfo existingRequest =
5225 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005226 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005227 if (DBG) {
5228 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5229 + nri.mRequests.get(0) + " because their intents matched.");
5230 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005231 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005232 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005233 }
Erik Kline05f2b402015-04-30 12:58:40 +09005234 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005235 }
5236
James Mattisf7027322020-12-13 16:28:14 -08005237 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005238 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005239 }
5240
James Mattis3ce3d3c2021-02-09 18:18:28 -08005241 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005242 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005243 for (final NetworkRequestInfo nri : nris) {
5244 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005245 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005246 for (final NetworkRequest req : nri.mRequests) {
5247 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005248 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005249 if (req.isListen()) {
5250 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5251 if (req.networkCapabilities.hasSignalStrength()
5252 && network.satisfiesImmutableCapabilitiesOf(req)) {
5253 updateSignalStrengthThresholds(network, "REGISTER", req);
5254 }
James Mattisf7027322020-12-13 16:28:14 -08005255 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005256 }
5257 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005258
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005259 // If this NRI has a satisfier already, it is replacing an older request that
5260 // has been removed. Track it.
5261 final NetworkRequest activeRequest = nri.getActiveRequest();
5262 if (null != activeRequest) {
5263 // If there is an active request, then for sure there is a satisfier.
5264 nri.getSatisfier().addRequest(activeRequest);
5265 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005266 }
James Mattisf7027322020-12-13 16:28:14 -08005267
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005268 if (mFlags.noRematchAllRequestsOnRegister()) {
5269 rematchNetworksAndRequests(nris);
5270 } else {
5271 rematchAllNetworksAndRequests();
5272 }
James Mattis45d81842021-01-10 14:24:24 -08005273
Chalard Jean0354d8c2021-01-12 10:58:56 +09005274 // Requests that have not been matched to a network will not have been sent to the
5275 // providers, because the old satisfier and the new satisfier are the same (null in this
5276 // case). Send these requests to the providers.
5277 for (final NetworkRequestInfo nri : nris) {
5278 for (final NetworkOfferInfo noi : mNetworkOffers) {
5279 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005280 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005281 }
5282 }
5283
James Mattisf7027322020-12-13 16:28:14 -08005284 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5285 final int callingUid) {
5286 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005287 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005288 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5289 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5290 handleReleaseNetworkRequest(
5291 nri.mRequests.get(0),
5292 callingUid,
5293 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005294 }
5295 }
5296
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005297 // Determines whether the network is the best (or could become the best, if it validated), for
5298 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5299 // on the value of reason:
5300 //
5301 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5302 // then it should be torn down.
5303 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5304 // then it should be lingered.
5305 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005306 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005307
Chalard Jean254bd162022-08-25 13:04:51 +09005308 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005309 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5310 return false;
5311 }
5312
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005313 final int numRequests;
5314 switch (reason) {
5315 case TEARDOWN:
5316 numRequests = nai.numRequestNetworkRequests();
5317 break;
5318 case LINGER:
5319 numRequests = nai.numForegroundNetworkRequests();
5320 break;
5321 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005322 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005323 return true;
5324 }
5325
Chalard Jean947acd42021-03-08 22:29:27 +09005326 if (numRequests > 0) return false;
5327
Paul Jensende49eb12015-06-25 15:30:08 -04005328 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005329 if (reason == UnneededFor.LINGER
5330 && !nri.isMultilayerRequest()
5331 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005332 // Background requests don't affect lingering.
5333 continue;
5334 }
5335
James Mattis3d229892020-11-16 16:46:28 -08005336 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005337 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005338 }
5339 }
Paul Jensende49eb12015-06-25 15:30:08 -04005340 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005341 }
5342
James Mattis3d229892020-11-16 16:46:28 -08005343 private boolean isNetworkPotentialSatisfier(
5344 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
5345 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005346 // request, return immediately. For multilayer requests, check to see if any of the
5347 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005348 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5349 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005350 return false;
5351 }
5352 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005353 // This multilayer listen request is satisfied therefore no further requests need to be
5354 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005355 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005356 return false;
5357 }
James Mattis3d229892020-11-16 16:46:28 -08005358 // As non-multilayer listen requests have already returned, the below would only happen
5359 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005360 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005361 continue;
5362 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09005363 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08005364 // there is hope for it to become one if it validated, then it is needed.
5365 if (candidate.satisfies(req)) {
5366 // As soon as a network is found that satisfies a request, return. Specifically for
5367 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5368 // is important so as to not evaluate lower priority requests further in
5369 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005370 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5371 ? nri.getSatisfier() : null;
5372 // Note that this catches two important cases:
5373 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5374 // is currently satisfying the request. This is desirable when
5375 // cellular ends up validating but WiFi does not.
5376 // 2. Unvalidated WiFi will not be reaped when validated cellular
5377 // is currently satisfying the request. This is desirable when
5378 // WiFi ends up validating and out scoring cellular.
5379 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005380 }
5381 }
5382
5383 return false;
5384 }
5385
Erik Kline0c04b742016-07-07 16:50:58 +09005386 private NetworkRequestInfo getNriForAppRequest(
5387 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005388 // Looking up the app passed param request in mRequests isn't possible since it may return
5389 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5390 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005391 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5392 // to avoid potential race conditions when validating a package->uid mapping when sending
5393 // the callback on the very low-chance that an application shuts down prior to the callback
5394 // being sent.
5395 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5396 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005397
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005398 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005399 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005400 log(String.format("UID %d attempted to %s for unowned request %s",
5401 callingUid, requestedOperation, nri));
5402 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005403 }
Erik Kline0c04b742016-07-07 16:50:58 +09005404 }
5405
5406 return nri;
5407 }
5408
James Mattisf7027322020-12-13 16:28:14 -08005409 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5410 final String callingMethod) {
5411 if (nri.isMultilayerRequest()) {
5412 throw new IllegalStateException(
5413 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005414 }
5415 }
5416
James Mattisf7027322020-12-13 16:28:14 -08005417 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005418 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005419 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5420 // single NetworkRequest and thus does not apply to multilayer requests.
5421 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5422 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005423 return;
5424 }
James Mattis2516da32021-01-31 17:06:19 -08005425 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005426 return;
5427 }
James Mattisf7027322020-12-13 16:28:14 -08005428 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5429 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005430 }
5431 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005432 callCallbackForRequest(
5433 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005434 }
5435
James Mattisf7027322020-12-13 16:28:14 -08005436 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5437 final int callingUid,
5438 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005439 final NetworkRequestInfo nri =
5440 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5441 if (nri == null) {
5442 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005443 }
James Mattisf7027322020-12-13 16:28:14 -08005444 if (VDBG || (DBG && request.isRequest())) {
5445 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005446 }
5447 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005448 if (callOnUnavailable) {
5449 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5450 }
Erik Kline155a59a2015-11-25 12:49:38 +09005451 }
Erik Kline0c04b742016-07-07 16:50:58 +09005452
James Mattisa076c532020-12-02 14:12:41 -08005453 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005454 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005455 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005456 if (null == mNetworkRequests.remove(req)) {
5457 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5458 continue;
5459 }
James Mattisa076c532020-12-02 14:12:41 -08005460 if (req.isListen()) {
5461 removeListenRequestFromNetworks(req);
5462 }
5463 }
James Mattis8f036802021-06-20 16:26:01 -07005464 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005465 if (mDefaultNetworkRequests.remove(nri)) {
5466 // If this request was one of the defaults, then the UID rules need to be updated
5467 // WARNING : if the app(s) for which this network request is the default are doing
5468 // traffic, this will kill their connected sockets, even if an equivalent request
5469 // is going to be reinstated right away ; unconnected traffic will go on the default
5470 // until the new default is set, which will happen very soon.
5471 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5472 // remove ranges for those requests that won't have a replacement
5473 final NetworkAgentInfo satisfier = nri.getSatisfier();
5474 if (null != satisfier) {
5475 try {
paulhu0e79d952021-06-09 16:11:35 +08005476 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5477 satisfier.network.getNetId(),
5478 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005479 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005480 } catch (RemoteException e) {
5481 loge("Exception setting network preference default network", e);
5482 }
5483 }
5484 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005485
Junyu Lai00d92df2022-07-05 11:01:52 +08005486 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005487 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005488 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005489
5490 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005491 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005492 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005493 }
5494 }
5495
Chalard Jean0354d8c2021-01-12 10:58:56 +09005496 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5497 // needed for this offer.
5498 for (final NetworkOfferInfo noi : mNetworkOffers) {
5499 for (final NetworkRequest req : nri.mRequests) {
5500 if (req.isRequest() && noi.offer.neededFor(req)) {
5501 noi.offer.onNetworkUnneeded(req);
5502 }
5503 }
5504 }
James Mattisa076c532020-12-02 14:12:41 -08005505 }
5506
James Mattis3ce3d3c2021-02-09 18:18:28 -08005507 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5508 for (final NetworkRequestInfo nri : nris) {
5509 if (mDefaultRequest == nri) {
5510 // Make sure we never remove the default request.
5511 continue;
5512 }
5513 handleRemoveNetworkRequest(nri);
5514 }
5515 }
5516
James Mattisa076c532020-12-02 14:12:41 -08005517 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5518 // listens don't have a singular affected Network. Check all networks to see
5519 // if this listen request applies and remove it.
5520 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5521 nai.removeRequest(req.requestId);
5522 if (req.networkCapabilities.hasSignalStrength()
5523 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5524 updateSignalStrengthThresholds(nai, "RELEASE", req);
5525 }
5526 }
5527 }
5528
5529 /**
5530 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5531 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5532 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5533 */
5534 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5535 boolean wasKept = false;
5536 final NetworkAgentInfo nai = nri.getSatisfier();
5537 if (nai != null) {
5538 final int requestLegacyType = nri.getActiveRequest().legacyType;
5539 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5540 nai.removeRequest(nri.getActiveRequest().requestId);
5541 if (VDBG || DDBG) {
5542 log(" Removing from current network " + nai.toShortString()
5543 + ", leaving " + nai.numNetworkRequests() + " requests.");
5544 }
5545 // If there are still lingered requests on this network, don't tear it down,
5546 // but resume lingering instead.
5547 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005548 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005549 notifyNetworkLosing(nai, now);
5550 }
5551 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5552 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5553 teardownUnneededNetwork(nai);
5554 } else {
5555 wasKept = true;
5556 }
James Mattisa076c532020-12-02 14:12:41 -08005557 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5558 // Went from foreground to background.
5559 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005560 }
5561
Erik Kline0c04b742016-07-07 16:50:58 +09005562 // Maintain the illusion. When this request arrived, we might have pretended
5563 // that a network connected to serve it, even though the network was already
5564 // connected. Now that this request has gone away, we might have to pretend
5565 // that the network disconnected. LegacyTypeTracker will generate that
5566 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005567 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005568 boolean doRemove = true;
5569 if (wasKept) {
5570 // check if any of the remaining requests for this network are for the
5571 // same legacy type - if so, don't remove the nai
5572 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5573 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005574 if (otherRequest.legacyType == requestLegacyType
5575 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005576 if (DBG) log(" still have other legacy request - leaving");
5577 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005578 }
5579 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005580 }
5581
Erik Kline0c04b742016-07-07 16:50:58 +09005582 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005583 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005584 }
5585 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005586 }
5587 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005588
Junyu Lai00d92df2022-07-05 11:01:52 +08005589 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005590 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005591 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5592 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5593 }
5594
Lorenzo Colittid6459092016-07-04 12:55:44 +09005595 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005596 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005597 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005598 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005599 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005600 }
5601
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005602 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005603 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5604 enforceNetworkStackSettingsOrSetup();
5605 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5606 encodeBool(accept), encodeBool(always), network));
5607 }
5608
5609 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005610 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005611 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005612 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5613 }
5614
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005615 @Override
5616 public void setTestAllowBadWifiUntil(long timeMs) {
5617 enforceSettingsPermission();
5618 if (!Build.isDebuggable()) {
5619 throw new IllegalStateException("Does not support in non-debuggable build");
5620 }
5621
5622 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5623 throw new IllegalArgumentException("It should not exceed "
5624 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5625 }
5626
5627 mHandler.sendMessage(
5628 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5629 }
5630
chiachangwange0192a72023-02-06 13:25:01 +00005631 @Override
5632 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5633 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005634
5635 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5636 throw new IllegalArgumentException("Argument should not exceed "
5637 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5638 }
5639
5640 mHandler.sendMessage(
5641 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5642 }
5643
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005644 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5645 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5646 " accept=" + accept + " always=" + always);
5647
5648 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5649 if (nai == null) {
5650 // Nothing to do.
5651 return;
5652 }
5653
Chalard Jean254bd162022-08-25 13:04:51 +09005654 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005655 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005656 return;
5657 }
5658
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005659 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005660 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005661 }
5662
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005663 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5664 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005665 // If network becomes partial connectivity and user already accepted to use this
5666 // network, we should respect the user's option and don't need to popup the
5667 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005668 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005669 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005670 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005671 }
5672
5673 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005674 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005675 }
5676
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005677 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005678 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005679 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005680 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005681 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005682 }
5683
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005684 }
5685
lucaslin2240ef62019-03-12 13:08:03 +08005686 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5687 boolean always) {
5688 if (DBG) {
5689 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5690 + " always=" + always);
5691 }
5692
5693 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5694 if (nai == null) {
5695 // Nothing to do.
5696 return;
5697 }
5698
Chalard Jean254bd162022-08-25 13:04:51 +09005699 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005700 // The network validated while the dialog box was up. Take no action.
5701 return;
5702 }
5703
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005704 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5705 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005706 }
5707
5708 // TODO: Use the current design or save the user choice into IpMemoryStore.
5709 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005710 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005711 }
5712
5713 if (!accept) {
5714 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005715 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005716 // Tear down the network.
5717 teardownUnneededNetwork(nai);
5718 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005719 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5720 // result in a partial connectivity result which will be processed by
5721 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005722 //
5723 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5724 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005725 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005726 }
5727 }
5728
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005729 private void handleSetAvoidUnvalidated(Network network) {
5730 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005731 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005732 // Nothing to do. The network either disconnected or revalidated.
5733 return;
5734 }
Chalard Jean254bd162022-08-25 13:04:51 +09005735 if (0L == nai.getAvoidUnvalidated()) {
5736 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005737 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005738 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005739 }
5740 }
5741
Chalard Jean5fb43c72022-09-08 19:03:14 +09005742 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005743 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005744 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean1f2b50f2023-05-15 17:26:13 +09005745 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005746 }
5747
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005748 @Override
5749 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005750 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005751 mHandler.post(() -> {
5752 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5753 if (nai == null) return;
5754 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005755 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005756 });
5757 }
5758
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005759 /**
5760 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5761 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005762 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005763 * @param appExtras Bundle to use as intent extras for the captive portal application.
5764 * Must be treated as opaque to avoid preventing the captive portal app to
5765 * update its arguments.
5766 */
5767 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005768 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005769 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5770 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005771
5772 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5773 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005774 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5775 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005776 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5777
lucaslin75ff7022020-12-17 04:14:35 +08005778 final long token = Binder.clearCallingIdentity();
5779 try {
5780 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5781 } finally {
5782 Binder.restoreCallingIdentity(token);
5783 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005784 }
5785
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005786 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5787 private final Network mNetwork;
5788
5789 private CaptivePortalImpl(Network network) {
5790 mNetwork = network;
5791 }
5792
5793 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005794 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005795 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5796 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005797 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5798 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5799 // Since the network will be disconnected, skip notifying NetworkMonitor
5800 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005801 }
5802
Chiachang Wang938bfba2020-01-09 13:50:55 +08005803 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005804 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005805 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005806 }
5807
5808 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005809 public void appRequest(final int request) {
5810 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5811 if (nm == null) return;
5812
5813 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005814 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005815 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005816 }
5817 }
5818
5819 @Nullable
5820 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5821 // getNetworkAgentInfoForNetwork is thread-safe
5822 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5823 if (nai == null) return null;
5824
5825 // nai.networkMonitor() is thread-safe
5826 return nai.networkMonitor();
5827 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005828 }
5829
Hugo Benichic9048bc2016-09-14 23:23:08 +00005830 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005831 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005832 }
5833
Chalard Jean020b93a2022-09-01 13:20:14 +09005834 private boolean activelyPreferBadWifi() {
5835 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5836 }
5837
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005838 /**
5839 * Return whether the device should maintain continuous, working connectivity by switching away
5840 * from WiFi networks having no connectivity.
5841 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5842 */
5843 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005844 if (!checkNetworkStackPermission()) {
5845 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5846 }
5847 return avoidBadWifi();
5848 }
5849
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005850 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005851 ensureRunningOnConnectivityServiceThread();
5852 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005853 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005854 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005855 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005856 if (avoidBadWifi) {
5857 // If the device is now avoiding bad wifi, remove notifications that might have
5858 // been put up when the device didn't.
5859 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5860 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005861 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005862 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5863 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5864 for (final NetworkOfferInfo noi : offersToUpdate) {
5865 updateOfferScore(noi.offer);
5866 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005867 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005868 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005869 }
5870
Erik Kline95ecfee2016-10-02 18:02:14 +09005871 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005872 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005873 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005874 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005875 if (!configRestrict) {
5876 pw.println("Bad Wi-Fi avoidance: unrestricted");
5877 return;
5878 }
5879
5880 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5881 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005882 pw.println("Config restrict: " + configRestrict);
5883 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005884
Chalard Jeane0fdea32022-09-14 21:44:22 +09005885 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005886 String description;
5887 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005888 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005889 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005890 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005891 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005892 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005893 description = "avoid";
5894 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005895 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005896 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005897 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005898
5899 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5900 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005901 if (null == configValue) {
5902 description = "unset";
5903 } else if (configValue) {
5904 description = "force true";
5905 } else {
5906 description = "force false";
5907 }
5908 pw.println("Actively prefer bad wifi conf: " + description);
5909 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005910 pw.println("Network overrides:");
5911 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005912 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005913 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005914 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005915 }
5916 }
5917 pw.decreaseIndent();
5918 pw.decreaseIndent();
5919 }
5920
paulhu7746e4e2020-06-09 19:07:03 +08005921 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5922 // unify the method.
5923 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5924 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5925 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5926 return settingsComponent != null
5927 ? settingsComponent.getPackageName() : "com.android.settings";
5928 }
5929
lucaslinb1e8e382019-01-24 15:55:30 +08005930 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005931 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005932 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005933 switch (type) {
5934 case NO_INTERNET:
5935 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005936 // High priority because it is only displayed for explicitly selected networks.
5937 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005938 break;
lucasline117e2e2019-10-22 18:27:33 +08005939 case PRIVATE_DNS_BROKEN:
5940 action = Settings.ACTION_WIRELESS_SETTINGS;
5941 // High priority because we should let user know why there is no internet.
5942 highPriority = true;
5943 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005944 case LOST_INTERNET:
5945 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005946 // High priority because it could help the user avoid unexpected data usage.
5947 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005948 break;
lucaslin2240ef62019-03-12 13:08:03 +08005949 case PARTIAL_CONNECTIVITY:
5950 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005951 // Don't bother the user with a high-priority notification if the network was not
5952 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005953 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005954 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005955 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005956 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005957 return;
5958 }
5959
5960 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005961 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005962 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005963 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005964 // Some OEMs have their own Settings package. Thus, need to get the current using
5965 // Settings package name instead of just use default name "com.android.settings".
5966 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5967 intent.setClassName(settingsPkgName,
5968 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005969 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005970
paulhu2af50222020-10-11 22:52:27 +08005971 PendingIntent pendingIntent = PendingIntent.getActivity(
5972 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005973 0 /* requestCode */,
5974 intent,
paulhu2af50222020-10-11 22:52:27 +08005975 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005976
Serik Beketayevec8ad212020-12-07 22:43:07 -08005977 mNotifier.showNotification(
5978 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005979 }
5980
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005981 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5982 // Don't prompt if the network is validated, and don't prompt on captive portals
5983 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005984 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005985 return false;
5986 }
5987
5988 // If a network has partial connectivity, always prompt unless the user has already accepted
5989 // partial connectivity and selected don't ask again. This ensures that if the device
5990 // automatically connects to a network that has partial Internet access, the user will
5991 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005992 // because we have prompted them.
5993 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005994 return true;
5995 }
5996
5997 // If a network has no Internet access, only prompt if the network was explicitly selected
5998 // and if the user has not already told us to use the network regardless of whether it
5999 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006000 if (nai.networkAgentConfig.explicitlySelected
6001 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006002 return true;
6003 }
6004
6005 return false;
6006 }
6007
Chalard Jean5fb43c72022-09-08 19:03:14 +09006008 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
6009 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006010
Chalard Jean5fb43c72022-09-08 19:03:14 +09006011 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6012 if (null == nai) return;
6013
6014 if (nai.setEvaluated()) {
6015 // If setEvaluated() returned true, the network never had any form of connectivity.
6016 // This may have an impact on request matching if bad WiFi avoidance is off and the
6017 // network was found not to have Internet access.
6018 nai.updateScoreForNetworkAgentUpdate();
6019 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09006020
6021 // Also, if this is WiFi and it should be preferred actively, now is the time to
6022 // prompt the user that they walked past and connected to a bad WiFi.
6023 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
6024 && !avoidBadWifi()
6025 && activelyPreferBadWifi()) {
6026 // The notification will be removed if the network validates or disconnects.
6027 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
6028 return;
6029 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006030 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006031
Chalard Jean5fb43c72022-09-08 19:03:14 +09006032 if (!shouldPromptUnvalidated(nai)) return;
6033
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006034 // Stop automatically reconnecting to this network in the future. Automatically connecting
6035 // to a network that provides no or limited connectivity is not useful, because the user
6036 // cannot use that network except through the notification shown by this method, and the
6037 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006038 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006039
Chalard Jean254bd162022-08-25 13:04:51 +09006040 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08006041 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08006042 } else {
6043 showNetworkNotification(nai, NotificationType.NO_INTERNET);
6044 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006045 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006046
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006047 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
6048 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09006049 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07006050
lucaslin2240ef62019-03-12 13:08:03 +08006051 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6052 return;
6053 }
6054
6055 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08006056 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006057 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006058 }
6059
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006060 @Override
6061 public int getMultipathPreference(Network network) {
6062 enforceAccessPermission();
6063
6064 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06006065 if (nai != null && nai.networkCapabilities
6066 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006067 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
6068 }
6069
Aaron Huang9a57acf2020-12-08 10:03:29 +08006070 final NetworkPolicyManager netPolicyManager =
6071 mContext.getSystemService(NetworkPolicyManager.class);
6072
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09006073 final long token = Binder.clearCallingIdentity();
6074 final int networkPreference;
6075 try {
6076 networkPreference = netPolicyManager.getMultipathPreference(network);
6077 } finally {
6078 Binder.restoreCallingIdentity(token);
6079 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08006080 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09006081 return networkPreference;
6082 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006083 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
6084 }
6085
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006086 @Override
6087 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09006088 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006089 }
6090
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006091 private class InternalHandler extends Handler {
6092 public InternalHandler(Looper looper) {
6093 super(looper);
6094 }
6095
6096 @Override
6097 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006098 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07006099 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006100 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006101 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07006102 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006103 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006104 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09006105 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07006106 break;
6107 }
Aaron Huang25ef1712021-06-08 13:11:45 +08006108 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08006109 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang25ef1712021-06-08 13:11:45 +08006110 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04006111 break;
6112 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006113 case EVENT_REGISTER_NETWORK_PROVIDER: {
6114 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006115 break;
6116 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006117 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
6118 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006119 break;
6120 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006121 case EVENT_REGISTER_NETWORK_OFFER: {
6122 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
6123 break;
6124 }
6125 case EVENT_UNREGISTER_NETWORK_OFFER: {
6126 final NetworkOfferInfo offer =
6127 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
6128 if (null != offer) {
6129 handleUnregisterNetworkOffer(offer);
6130 }
6131 break;
6132 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006133 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006134 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
6135 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
6136 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006137 break;
6138 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006139 case EVENT_REGISTER_NETWORK_REQUEST:
6140 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09006141 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006142 break;
6143 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006144 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6145 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006146 handleRegisterNetworkRequestWithIntent(msg);
6147 break;
6148 }
Erik Kline155a59a2015-11-25 12:49:38 +09006149 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6150 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6151 handleTimedOutNetworkRequest(nri);
6152 break;
6153 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006154 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6155 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6156 break;
6157 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006158 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006159 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6160 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006161 break;
6162 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006163 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006164 Network network = (Network) msg.obj;
6165 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006166 break;
6167 }
lucaslin2240ef62019-03-12 13:08:03 +08006168 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6169 Network network = (Network) msg.obj;
6170 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6171 toBool(msg.arg2));
6172 break;
6173 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006174 case EVENT_SET_AVOID_UNVALIDATED: {
6175 handleSetAvoidUnvalidated((Network) msg.obj);
6176 break;
6177 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006178 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6179 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006180 break;
6181 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006182 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6183 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006184 break;
6185 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006186 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6187 // handler thread.
6188 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006189 mKeepaliveTracker.handleStartKeepalive(msg);
6190 break;
6191 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006192 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006193 final AutomaticOnOffKeepalive ki =
6194 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6195 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006196
chiachangwang676c84e2023-02-14 09:22:05 +00006197 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006198 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006199 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006200 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006201 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6202 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006203 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6204 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006205 }
6206 }
6207
6208 // If the network no longer exists, then the keepalive should have been
6209 // cleaned up already. There is no point trying to resume keepalives.
6210 if (!networkFound) return;
6211
chiachangwang676c84e2023-02-14 09:22:05 +00006212 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006213 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
chiachangwang676c84e2023-02-14 09:22:05 +00006214 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006215 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006216 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006217 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006218 }
6219 break;
6220 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006221 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006222 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006223 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6224 (IBinder) msg.obj);
6225 if (ki == null) {
6226 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006227 return;
6228 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006229 final int reason = msg.arg2;
6230 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006231 break;
6232 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006233 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6234 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6235 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006236 break;
6237 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006238 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6239 handlePrivateDnsSettingsChanged();
6240 break;
dalyk1720e542018-03-05 12:42:22 -05006241 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6242 handlePrivateDnsValidationUpdate(
6243 (PrivateDnsValidationUpdate) msg.obj);
6244 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006245 case EVENT_UID_BLOCKED_REASON_CHANGED:
6246 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006247 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006248 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6249 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6250 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006251 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006252 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6253 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006254 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006255 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006256 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006257 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006258 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6259 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006260 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006261 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006262 }
lucaslin1193a5d2021-01-21 02:04:15 +08006263 case EVENT_REPORT_NETWORK_ACTIVITY:
6264 mNetworkActivityTracker.handleReportNetworkActivity();
6265 break;
paulhu51f77dc2021-06-07 02:34:20 +00006266 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6267 handleMobileDataPreferredUidsChanged();
6268 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006269 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6270 final long timeMs = ((Long) msg.obj).longValue();
6271 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6272 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006273 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6274 handleIngressRateLimitChanged();
6275 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006276 case EVENT_USER_DOES_NOT_WANT:
6277 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6278 if (nai == null) break;
6279 nai.onPreventAutomaticReconnect();
Jean Chalard01a7d322023-06-27 08:54:23 +00006280 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006281 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006282 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6283 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6284 break;
chiachangwange0192a72023-02-06 13:25:01 +00006285 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6286 final long time = ((Long) msg.obj).longValue();
6287 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6288 break;
6289 }
Mark Fasheh7501e762023-05-04 20:23:11 +00006290 case EVENT_UID_FROZEN_STATE_CHANGED:
6291 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6292 handleFrozenUids(args.mUids, args.mFrozenStates);
6293 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006294 }
6295 }
6296 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006297
Lorenzo Colittid6459092016-07-04 12:55:44 +09006298 @Override
markchien5776f962019-12-16 20:15:20 +08006299 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006300 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006301 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006302 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6303 Context.TETHERING_SERVICE);
6304 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006305 }
6306
Lorenzo Colittid6459092016-07-04 12:55:44 +09006307 @Override
markchien5776f962019-12-16 20:15:20 +08006308 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006309 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006310 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006311 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6312 Context.TETHERING_SERVICE);
6313 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006314 }
6315
Lorenzo Colittid6459092016-07-04 12:55:44 +09006316 @Override
markchien5776f962019-12-16 20:15:20 +08006317 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006318 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006319 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006320 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6321 Context.TETHERING_SERVICE);
6322 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006323 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006324
markchien5776f962019-12-16 20:15:20 +08006325
Lorenzo Colittid6459092016-07-04 12:55:44 +09006326 @Override
markchien5776f962019-12-16 20:15:20 +08006327 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006328 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006329 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006330 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6331 Context.TETHERING_SERVICE);
6332
6333 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006334 }
6335
Lorenzo Colittid6459092016-07-04 12:55:44 +09006336 @Override
markchien5776f962019-12-16 20:15:20 +08006337 @Deprecated
6338 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006339 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006340 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6341 Context.TETHERING_SERVICE);
6342
6343 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006344 }
6345
Udam Saini8f7d6a72017-06-07 12:06:28 -07006346 @Override
markchien5776f962019-12-16 20:15:20 +08006347 @Deprecated
6348 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006349 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006350 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6351 Context.TETHERING_SERVICE);
6352 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006353 }
6354
Robert Greenwalte0b00512014-07-02 09:59:16 -07006355 // Called when we lose the default network and have no replacement yet.
6356 // This will automatically be cleared after X seconds or a new default network
6357 // becomes CONNECTED, whichever happens first. The timer is started by the
6358 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006359 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006360 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006361 if (mNetTransitionWakeLock.isHeld()) {
6362 return;
6363 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006364 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006365 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6366 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006367 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006368 mWakelockLogs.log("ACQUIRE for " + forWhom);
6369 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006370 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006371 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006372 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006373 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006374
Hugo Benichi471b62a2017-03-30 23:18:10 +09006375 // Called when we gain a new default network to release the network transition wakelock in a
6376 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6377 // message is cancelled.
6378 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006379 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006380 if (!mNetTransitionWakeLock.isHeld()) {
6381 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006382 }
6383 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006384 // Cancel self timeout on wakelock hold.
6385 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6386 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6387 mHandler.sendMessageDelayed(msg, 1000);
6388 }
6389
6390 // Called when either message of ensureNetworkTransitionWakelock or
6391 // scheduleReleaseNetworkTransitionWakelock is processed.
6392 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6393 String event = eventName(eventId);
6394 synchronized (this) {
6395 if (!mNetTransitionWakeLock.isHeld()) {
6396 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006397 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006398 return;
6399 }
6400 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006401 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6402 mTotalWakelockDurationMs += lockDuration;
6403 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6404 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006405 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006406 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006407 }
6408
Robert Greenwalt986c7412010-09-08 15:24:47 -07006409 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006410 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006411 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006412 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006413 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006414 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006415 }
6416
Lorenzo Colittid6459092016-07-04 12:55:44 +09006417 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006418 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006419 enforceAccessPermission();
6420 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006421 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006422 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006423
6424 final NetworkAgentInfo nai;
6425 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006426 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006427 } else {
6428 nai = getNetworkAgentInfoForNetwork(network);
6429 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006430
6431 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006432 mHandler.obtainMessage(
6433 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006434 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006435
Hugo Benichid6b510a2017-04-06 17:22:18 +09006436 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006437 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006438 if (nai == null
6439 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006440 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006441 return;
6442 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006443 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006444 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006445 mConnectivityDiagnosticsHandler.sendMessage(
6446 mConnectivityDiagnosticsHandler.obtainMessage(
6447 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6448 new ReportedNetworkConnectivityInfo(
6449 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006450 return;
6451 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006452 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006453 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006454 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006455 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006456 // Validating a network that has not yet connected could result in a call to
6457 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006458 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006459 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006460 }
paulhu7aeba372020-12-30 00:42:19 +08006461 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6462 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006463 return;
6464 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006465
6466 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6467 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6468 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6469 // completed.
6470 mConnectivityDiagnosticsHandler.sendMessage(
6471 mConnectivityDiagnosticsHandler.obtainMessage(
6472 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6473 new ReportedNetworkConnectivityInfo(
6474 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006475 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006476 }
6477
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006478 // TODO: call into netd.
6479 private boolean queryUserAccess(int uid, Network network) {
6480 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6481 if (nai == null) return false;
6482
6483 // Any UID can use its default network.
6484 if (nai == getDefaultNetworkForUid(uid)) return true;
6485
6486 // Privileged apps can use any network.
6487 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6488 return true;
6489 }
6490
6491 // An unprivileged UID can use a VPN iff the VPN applies to it.
6492 if (nai.isVPN()) {
6493 return nai.networkCapabilities.appliesToUid(uid);
6494 }
6495
6496 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6497 // sockets, i.e., if it is the owner.
6498 final NetworkAgentInfo vpn = getVpnForUid(uid);
6499 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6500 && uid != vpn.networkCapabilities.getOwnerUid()) {
6501 return false;
6502 }
6503
6504 // The UID's permission must be at least sufficient for the network. Since the restricted
6505 // permission was already checked above, that just leaves background networks.
6506 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6507 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6508 }
6509
6510 // Unrestricted network. Anyone gets to use it.
6511 return true;
6512 }
6513
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006514 /**
6515 * Returns information about the proxy a certain network is using. If given a null network, it
6516 * it will return the proxy for the bound network for the caller app or the default proxy if
6517 * none.
6518 *
6519 * @param network the network we want to get the proxy information for.
6520 * @return Proxy information if a network has a proxy configured, or otherwise null.
6521 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006522 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006523 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006524 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006525 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006526 if (network == null) {
6527 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006528 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006529 true);
6530 if (activeNetwork == null) {
6531 return null;
6532 }
6533 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006534 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006535 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6536 // caller may not have.
6537 return getLinkPropertiesProxyInfo(network);
6538 }
6539 // No proxy info available if the calling UID does not have network access.
6540 return null;
6541 }
6542
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006543
6544 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006545 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6546 if (nai == null) return null;
6547 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006548 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6549 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006550 }
6551 }
6552
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006553 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006554 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006555 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006556 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006557 }
6558
Chalard Jean777e2e52018-06-07 18:02:37 +09006559 @Override
6560 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006561 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006562 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006563 }
6564
Aaron Huang25ef1712021-06-08 13:11:45 +08006565 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006566 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang25ef1712021-06-08 13:11:45 +08006567 final NetworkAgentInfo nai = getDefaultNetwork();
6568 // TODO : this method should check that net == nai.network, unfortunately at this point
6569 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6570 // is only ever installed on the default network so in practice this is okay.
6571 if (null == nai) return;
6572 // PAC proxies only work on the default network. Therefore, only the default network
6573 // should have its link properties fixed up for PAC proxies.
6574 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6575 if (nai.everConnected()) {
6576 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6577 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006578 }
6579
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006580 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6581 // when any network changes proxy.
6582 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6583 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006584 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6585 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006586 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6587
Chalard Jean7d97afc2018-06-07 17:41:29 +09006588 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006589 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006590 }
6591 }
6592
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006593 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006594 final private HashMap<Uri, Integer> mUriEventMap;
6595 final private Context mContext;
6596 final private Handler mHandler;
6597
6598 SettingsObserver(Context context, Handler handler) {
6599 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006600 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006601 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006602 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006603 }
6604
Erik Kline05f2b402015-04-30 12:58:40 +09006605 void observe(Uri uri, int what) {
6606 mUriEventMap.put(uri, what);
6607 final ContentResolver resolver = mContext.getContentResolver();
6608 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006609 }
6610
6611 @Override
6612 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006613 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006614 }
6615
6616 @Override
6617 public void onChange(boolean selfChange, Uri uri) {
6618 final Integer what = mUriEventMap.get(uri);
6619 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006620 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006621 } else {
6622 loge("No matching event to send for URI=" + uri);
6623 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006624 }
6625 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006626
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006627 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006628 Log.d(TAG, s);
6629 }
6630
6631 private static void logw(String s) {
6632 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006633 }
6634
Daniel Brightf9e945b2020-06-15 16:10:01 -07006635 private static void logwtf(String s) {
6636 Log.wtf(TAG, s);
6637 }
6638
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006639 private static void logwtf(String s, Throwable t) {
6640 Log.wtf(TAG, s, t);
6641 }
6642
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006643 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006644 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006645 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006646
Hugo Benichi39621362017-02-11 17:04:43 +09006647 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006648 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006649 }
6650
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006651 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006652 * Return the information of all ongoing VPNs.
6653 *
6654 * <p>This method is used to update NetworkStatsService.
6655 *
6656 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006657 */
junyulai2050bed2021-01-23 09:46:34 +08006658 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006659 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006660 if (mLockdownEnabled) {
6661 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006662 }
junyulai2050bed2021-01-23 09:46:34 +08006663 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006664 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006665 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006666 if (info != null) {
6667 infoList.add(info);
6668 }
6669 }
junyulai2050bed2021-01-23 09:46:34 +08006670 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006671 }
6672
6673 /**
6674 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006675 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006676 */
junyulai2050bed2021-01-23 09:46:34 +08006677 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006678 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006679 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6680 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006681 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6682 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6683 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006684 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6685 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006686 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006687 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006688 }
6689 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006690
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006691 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006692
6693 List<String> interfaces = new ArrayList<>();
6694 for (Network network : underlyingNetworks) {
6695 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6696 if (underlyingNai == null) continue;
6697 LinkProperties lp = underlyingNai.linkProperties;
6698 for (String iface : lp.getAllInterfaceNames()) {
6699 if (!TextUtils.isEmpty(iface)) {
6700 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006701 }
6702 }
Benedict Wong34857f82019-06-12 17:46:15 +00006703 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006704
6705 if (interfaces.isEmpty()) return null;
6706
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006707 // Must be non-null or NetworkStatsService will crash.
6708 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6709 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006710 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006711 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006712
junyulai2050bed2021-01-23 09:46:34 +08006713 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6714 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006715 }
6716
James Mattisd31bdfa2020-12-23 16:37:26 -08006717 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006718 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6719 Network[] underlyingNetworks) {
6720 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006721 if (underlyingNetworks == null && defaultNetwork != null) {
6722 // null underlying networks means to track the default.
6723 underlyingNetworks = new Network[] { defaultNetwork };
6724 }
6725 return underlyingNetworks;
6726 }
6727
6728 // Returns true iff |network| is an underlying network of |nai|.
6729 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6730 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6731 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006732 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006733 final Network[] underlying = underlyingNetworksOrDefault(
6734 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006735 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006736 }
6737
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006738 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006739 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006740 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006741 * When underlying networks change, such networks may have to update capabilities to reflect
6742 * things like the metered bit, their transports, and so on. The capabilities are calculated
6743 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006744 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006745 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006746 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006747 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006748 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006749 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006750 }
6751 }
6752 }
6753
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006754 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6755 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6756 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6757 // a VPN is not up.
6758 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6759 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6760 for (UidRange range : blockedUidRanges) {
6761 if (range.contains(uid)) return true;
6762 }
6763 return false;
6764 }
6765
6766 @Override
6767 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006768 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006769 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6770 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6771 }
6772
6773 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6774 if (DBG) {
6775 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6776 + Arrays.toString(ranges));
6777 }
6778 // Cannot use a Set since the list of UID ranges might contain duplicates.
6779 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6780 for (int i = 0; i < ranges.length; i++) {
6781 if (requireVpn) {
6782 newVpnBlockedUidRanges.add(ranges[i]);
6783 } else {
6784 newVpnBlockedUidRanges.remove(ranges[i]);
6785 }
6786 }
6787
6788 try {
6789 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6790 } catch (RemoteException | ServiceSpecificException e) {
6791 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6792 + Arrays.toString(ranges) + "): netd command failed: " + e);
6793 }
6794
Chalard Jean03552c42023-05-29 17:02:43 +09006795 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006796 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6797 }
6798
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006799 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6800 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006801 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6802 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Oliver Scottb825c6f2022-10-27 23:52:45 +00006803
6804 if (nai.isVPN()) {
6805 updateVpnFiltering(nai.linkProperties, nai.linkProperties, nai, true /* force */);
6806 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006807 }
6808
6809 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6810 }
6811
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006812 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006813 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006814 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006815 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006816 }
6817
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006818 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6819 return mLockdownEnabled
6820 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6821 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006822 }
6823
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006824 private NetworkAgentInfo getLegacyLockdownNai() {
6825 if (!mLockdownEnabled) {
6826 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006827 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006828 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006829 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6830 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006831
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006832 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006833 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6834 // a local variable. There is no need to make a copy because its contents cannot change.
6835 final Network[] underlying = nai.declaredUnderlyingNetworks;
6836 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006837 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006838 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006839
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006840 // The legacy lockdown VPN always uses the default network.
6841 // If the VPN's underlying network is no longer the current default network, it means that
6842 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006843 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6844 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006845 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006846 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006847 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006848 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006849
6850 return nai;
6851 };
6852
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006853 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6854 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6855 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006856 private DetailedState getLegacyLockdownState(DetailedState origState) {
6857 if (origState != DetailedState.CONNECTED) {
6858 return origState;
6859 }
6860 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6861 ? DetailedState.CONNECTING
6862 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006863 }
6864
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006865 private void filterForLegacyLockdown(NetworkInfo ni) {
6866 if (!mLockdownEnabled || !ni.isConnected()) return;
6867 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6868 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6869 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6870 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6871 // network, this time with a state of CONNECTED.
6872 //
6873 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6874 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6875 // is not too far off the truth, since an always-on VPN, when not connected, is always
6876 // trying to reconnect.
6877 if (getLegacyLockdownNai() == null) {
6878 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6879 }
6880 }
6881
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006882 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006883 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006884 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006885 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006886 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6887 return;
6888 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006889 final long ident = Binder.clearCallingIdentity();
6890 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006891 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006892 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006893 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006894 } finally {
6895 Binder.restoreCallingIdentity(ident);
6896 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006897 }
Wink Savillecb117d32013-08-29 14:57:08 -07006898
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006899 @Override
6900 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006901 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006902 final long ident = Binder.clearCallingIdentity();
6903 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006904 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006905 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006906 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6907 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006908 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006909 } finally {
6910 Binder.restoreCallingIdentity(ident);
6911 }
6912 }
6913
James Mattis02220e22021-03-13 19:27:21 -08006914 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006915 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6916 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6917 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006918 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006919 }
6920
James Mattis02220e22021-03-13 19:27:21 -08006921 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006922 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006923 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006924 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6925 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006926 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006927 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6928 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6929 }
junyulaid91e7052020-08-28 13:44:33 +08006930 }
6931
James Mattis02220e22021-03-13 19:27:21 -08006932 private void onPackageChanged(@NonNull final String packageName) {
6933 // This is necessary in case a package is added or removed, but also when it's replaced to
6934 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6935 // as one in the preferences, then it should follow the same routing as that other package,
6936 // which means updating the rules is never to be needed in this case (whether it joins or
6937 // leaves a UID with a preference).
6938 if (isMappedInOemNetworkPreference(packageName)) {
6939 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6940 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09006941
6942 // Invalidates cache entry when the package is updated.
6943 synchronized (mSelfCertifiedCapabilityCache) {
6944 mSelfCertifiedCapabilityCache.remove(packageName);
6945 }
James Mattis02220e22021-03-13 19:27:21 -08006946 }
6947
6948 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006949 @Override
6950 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006951 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006952 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006953 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006954
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006955 // User should be filled for below intents, check the existence.
6956 if (user == null) {
6957 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6958 return;
6959 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006960
Lorenzo Colitticd675292021-02-04 17:32:07 +09006961 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006962 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006963 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006964 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006965 } else {
junyulaid91e7052020-08-28 13:44:33 +08006966 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006967 }
6968 }
6969 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006970
James Mattis02220e22021-03-13 19:27:21 -08006971 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6972 @Override
6973 public void onReceive(Context context, Intent intent) {
6974 ensureRunningOnConnectivityServiceThread();
6975 switch (intent.getAction()) {
6976 case Intent.ACTION_PACKAGE_ADDED:
6977 case Intent.ACTION_PACKAGE_REMOVED:
6978 case Intent.ACTION_PACKAGE_REPLACED:
6979 onPackageChanged(intent.getData().getSchemeSpecificPart());
6980 break;
6981 default:
6982 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6983 }
6984 }
6985 };
6986
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006987 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006988 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006989
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006990 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006991 public final String name;
6992 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006993 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006994 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006995
lifraf3a3492021-03-10 13:58:14 +08006996 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6997 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006998 this.name = name;
6999 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007000 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007001 mDeathRecipient = deathRecipient;
7002
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007003 if (mDeathRecipient == null) {
7004 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007005 }
7006 }
7007
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007008 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007009 try {
7010 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
7011 } catch (RemoteException e) {
7012 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007013 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007014 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007015 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007016
James Mattis4fce5d12020-11-12 15:53:42 -08007017 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
7018 for (int i = 0; i < requests.size(); i++) {
7019 ensureNetworkRequestHasType(requests.get(i));
7020 }
7021 }
7022
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007023 private void ensureNetworkRequestHasType(NetworkRequest request) {
7024 if (request.type == NetworkRequest.Type.NONE) {
7025 throw new IllegalArgumentException(
7026 "All NetworkRequests in ConnectivityService must have a type");
7027 }
7028 }
7029
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007030 /**
7031 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08007032 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007033 */
James Mattis258ea3c2020-11-15 15:04:40 -08007034 @VisibleForTesting
7035 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08007036 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
7037 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08007038 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08007039
James Mattisa076c532020-12-02 14:12:41 -08007040 // mSatisfier and mActiveRequest rely on one another therefore set them together.
7041 void setSatisfier(
7042 @Nullable final NetworkAgentInfo satisfier,
7043 @Nullable final NetworkRequest activeRequest) {
7044 mSatisfier = satisfier;
7045 mActiveRequest = activeRequest;
7046 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007047
James Mattisd31bdfa2020-12-23 16:37:26 -08007048 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007049 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09007050 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08007051 private NetworkAgentInfo mSatisfier;
7052 NetworkAgentInfo getSatisfier() {
7053 return mSatisfier;
7054 }
7055
7056 // The request in mRequests assigned to a network agent. This is null if none of the
7057 // requests in mRequests can be satisfied. This member has the constraint of only being
7058 // accessible on the handler thread.
7059 @Nullable
7060 private NetworkRequest mActiveRequest;
7061 NetworkRequest getActiveRequest() {
7062 return mActiveRequest;
7063 }
7064
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007065 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007066 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08007067 @Nullable
7068 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007069
7070 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08007071 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007072 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007073 final int mPid;
7074 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08007075 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007076 @Nullable
7077 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007078
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007079 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08007080 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007081
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007082 // Effective UID of this request. This is different from mUid when a privileged process
7083 // files a request on behalf of another UID. This UID is used to determine blocked status,
7084 // UID matching, and so on. mUid above is used for permission checks and to enforce the
7085 // maximum limit of registered callbacks per UID.
7086 final int mAsUid;
7087
paulhu48291862021-07-14 14:53:57 +08007088 // Preference order of this request.
7089 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08007090
James Mattis3ce3d3c2021-02-09 18:18:28 -08007091 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
7092 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
7093 // maintained for keying off of. This is only a concern when the original nri
7094 // mNetworkRequests changes which happens currently for apps that register callbacks to
7095 // track the default network. In those cases, the nri is updated to have mNetworkRequests
7096 // that match the per-app default nri that currently tracks the calling app's uid so that
7097 // callbacks are fired at the appropriate time. When the callbacks fire,
7098 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
7099 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
7100 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7101 @NonNull
7102 private final NetworkRequest mNetworkRequestForCallback;
7103 NetworkRequest getNetworkRequestForCallback() {
7104 return mNetworkRequestForCallback;
7105 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007106
James Mattisd31bdfa2020-12-23 16:37:26 -08007107 /**
7108 * Get the list of UIDs this nri applies to.
7109 */
7110 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00007111 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08007112 // networkCapabilities.getUids() returns a defensive copy.
7113 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007114 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
7115 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08007116 }
7117
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007118 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
7119 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08007120 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08007121 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007122 }
7123
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007124 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007125 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08007126 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007127 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007128 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007129 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007130 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08007131 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007132 mBinder = null;
7133 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007134 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007135 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007136 mPerUidCounter = getRequestCounter(this);
7137 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007138 /**
7139 * Location sensitive data not included in pending intent. Only included in
7140 * {@link NetworkCallback}.
7141 */
7142 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007143 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007144 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007145 }
7146
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007147 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007148 @Nullable final IBinder binder,
7149 @NetworkCallback.Flag int callbackFlags,
7150 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007151 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7152 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007153 }
7154
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007155 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007156 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007157 @Nullable final IBinder binder,
7158 @NetworkCallback.Flag int callbackFlags,
7159 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007160 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007161 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007162 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007163 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007164 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007165 mBinder = binder;
7166 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007167 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007168 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007169 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007170 mPerUidCounter = getRequestCounter(this);
7171 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007172 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007173 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007174 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007175 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007176 }
7177
James Mattis3ce3d3c2021-02-09 18:18:28 -08007178 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7179 @NonNull final List<NetworkRequest> r) {
7180 super();
7181 ensureAllNetworkRequestsHaveType(r);
7182 mRequests = initializeRequests(r);
7183 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007184 final NetworkAgentInfo satisfier = nri.getSatisfier();
7185 if (null != satisfier) {
7186 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7187 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007188 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007189 // As this code creates a new NRI with a new set of requests, figure out which of
7190 // the list of requests should be the active request. It is always the first
7191 // request of the list that can be satisfied by the satisfier since the order of
7192 // requests is a priority order.
7193 // Note even in the presence of a satisfier there may not be an active request,
7194 // when the satisfier is the no-service network.
7195 NetworkRequest activeRequest = null;
7196 for (final NetworkRequest candidate : r) {
7197 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7198 activeRequest = candidate;
7199 break;
7200 }
7201 }
7202 setSatisfier(satisfier, activeRequest);
7203 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007204 mMessenger = nri.mMessenger;
7205 mBinder = nri.mBinder;
7206 mPid = nri.mPid;
7207 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007208 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007209 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007210 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007211 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007212 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007213 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007214 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007215 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007216 }
7217
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007218 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007219 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007220 }
7221
paulhue9913722021-05-26 15:19:20 +08007222 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007223 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007224 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007225 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007226 }
7227
James Mattis2516da32021-01-31 17:06:19 -08007228 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7229 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7230 // false.
7231 boolean isBeingSatisfied() {
7232 return (null != mSatisfier && null != mActiveRequest);
7233 }
7234
James Mattis3d229892020-11-16 16:46:28 -08007235 boolean isMultilayerRequest() {
7236 return mRequests.size() > 1;
7237 }
7238
James Mattis45d81842021-01-10 14:24:24 -08007239 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7240 // Creating a defensive copy to prevent the sender from modifying the list being
7241 // reflected in the return value of this method.
7242 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007243 return Collections.unmodifiableList(tempRequests);
7244 }
7245
James Mattisb1392002021-03-31 13:57:52 -07007246 void linkDeathRecipient() {
7247 if (null != mBinder) {
7248 try {
7249 mBinder.linkToDeath(this, 0);
7250 } catch (RemoteException e) {
7251 binderDied();
7252 }
7253 }
7254 }
7255
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007256 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007257 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007258 try {
7259 mBinder.unlinkToDeath(this, 0);
7260 } catch (NoSuchElementException e) {
7261 // Temporary workaround for b/194394697 pending analysis of additional logs
7262 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7263 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007264 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007265 }
7266
paulhu48291862021-07-14 14:53:57 +08007267 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7268 // Compare two preference orders.
7269 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007270 }
7271
paulhu48291862021-07-14 14:53:57 +08007272 int getPreferenceOrderForNetd() {
7273 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7274 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7275 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007276 }
paulhu48291862021-07-14 14:53:57 +08007277 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007278 }
7279
James Mattis4fce5d12020-11-12 15:53:42 -08007280 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007281 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007282 // As an immutable collection, mRequests cannot change by the time the
7283 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7284 // is acceptable. Use handleReleaseNetworkRequest and not directly
7285 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7286 // the app already unregistered the request.
7287 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7288 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007289 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007290
James Mattis4fce5d12020-11-12 15:53:42 -08007291 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007292 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007293 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7294 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007295 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007296 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007297 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007298 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007299 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007300 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007301 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007302 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007303 }
7304
Junyu Lai00d92df2022-07-05 11:01:52 +08007305 // Keep backward compatibility since the ServiceSpecificException is used by
7306 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7307 public static class RequestInfoPerUidCounter extends PerUidCounter {
7308 RequestInfoPerUidCounter(int maxCountPerUid) {
7309 super(maxCountPerUid);
7310 }
7311
7312 @Override
7313 public synchronized void incrementCountOrThrow(int uid) {
7314 try {
7315 super.incrementCountOrThrow(uid);
7316 } catch (IllegalStateException e) {
7317 throw new ServiceSpecificException(
7318 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7319 "Uid " + uid + " exceeded its allotted requests limit");
7320 }
7321 }
7322
7323 @Override
7324 public synchronized void decrementCountOrThrow(int uid) {
7325 throw new UnsupportedOperationException("Use decrementCount instead.");
7326 }
7327
7328 public synchronized void decrementCount(int uid) {
7329 try {
7330 super.decrementCountOrThrow(uid);
7331 } catch (IllegalStateException e) {
7332 logwtf("Exception when decrement per uid request count: ", e);
7333 }
7334 }
7335 }
7336
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007337 // This checks that the passed capabilities either do not request a
7338 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007339 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007340 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09007341 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007342 throw new SecurityException("Insufficient permissions to request a specific SSID");
7343 }
paulhu1a407652019-03-22 16:35:06 +08007344
7345 if (nc.hasSignalStrength()
7346 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
7347 throw new SecurityException(
7348 "Insufficient permissions to request a specific signal strength");
7349 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007350 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007351
junyulai2217bec2021-04-14 23:33:31 +08007352 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07007353 enforceNetworkFactoryPermission();
7354 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007355 }
7356
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007357 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007358 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007359 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007360 // mNetworkRequests may contain the same value multiple times in case of
7361 // multilayer requests. It won't matter in this case because the thresholds
7362 // will then be the same and be deduplicated as they enter the `thresholds` set.
7363 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007364 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7365 for (final NetworkRequest req : nri.mRequests) {
7366 if (req.networkCapabilities.hasSignalStrength()
7367 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7368 thresholds.add(req.networkCapabilities.getSignalStrength());
7369 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007370 }
7371 }
7372 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007373 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007374 }
7375
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007376 private void updateSignalStrengthThresholds(
7377 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007378 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007379
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007380 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007381 String detail;
7382 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7383 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7384 } else {
7385 detail = reason;
7386 }
7387 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007388 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007389 }
7390
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007391 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007392 }
7393
Chalard Jeandd421992021-12-16 23:16:02 +09007394 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007395 if (nc == null) {
7396 return;
7397 }
7398 NetworkSpecifier ns = nc.getNetworkSpecifier();
7399 if (ns == null) {
7400 return;
7401 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007402 if (ns instanceof MatchAllNetworkSpecifier) {
7403 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7404 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007405 }
7406
Chalard Jeandd421992021-12-16 23:16:02 +09007407 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007408 ensureValidNetworkSpecifier(nc);
7409 if (nc.isPrivateDnsBroken()) {
7410 throw new IllegalArgumentException("Can't request broken private DNS");
7411 }
Chalard Jeande665262022-02-25 16:12:12 +09007412 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007413 throw new IllegalArgumentException("Can't request access UIDs");
7414 }
lucasline117e2e2019-10-22 18:27:33 +08007415 }
7416
Chalard Jeandd421992021-12-16 23:16:02 +09007417 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7418 ensureListenableCapabilities(nc);
7419 final String badCapability = nc.describeFirstNonRequestableCapability();
7420 if (badCapability != null) {
7421 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7422 }
7423 }
7424
Chiachang Wang3bc52762021-11-25 14:17:57 +08007425 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7426 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007427 private boolean isTargetSdkAtleast(int version, int callingUid,
7428 @NonNull String callingPackageName) {
7429 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007430 final PackageManager pm =
7431 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007432 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007433 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007434 if (callingVersion < version) return false;
7435 } catch (PackageManager.NameNotFoundException e) { }
7436 return true;
7437 }
7438
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007439 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007440 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007441 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007442 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007443 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08007444 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007445 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7446 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007447 throw new SecurityException("Insufficient permissions to specify legacy type");
7448 }
markchienfac84a22020-03-18 21:16:15 +08007449 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007450 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007451 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007452 // Privileged callers can track the default network of another UID by passing in a UID.
7453 if (asUid != Process.INVALID_UID) {
7454 enforceSettingsPermission();
7455 } else {
7456 asUid = callingUid;
7457 }
junyulaiad010792021-01-11 16:53:38 +08007458 final NetworkRequest.Type reqType;
7459 try {
7460 reqType = NetworkRequest.Type.values()[reqTypeInt];
7461 } catch (ArrayIndexOutOfBoundsException e) {
7462 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7463 }
7464 switch (reqType) {
7465 case TRACK_DEFAULT:
7466 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007467 // is unused and will be replaced by ones appropriate for the UID (usually, the
7468 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007469 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007470 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007471 enforceAccessPermission();
7472 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007473 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007474 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007475 networkCapabilities = new NetworkCapabilities(defaultNc);
7476 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007477 case BACKGROUND_REQUEST:
7478 enforceNetworkStackOrSettingsPermission();
7479 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007480 case REQUEST:
7481 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7482 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007483 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007484 // TODO: this is incorrect. We mark the request as metered or not depending on
7485 // the state of the app when the request is filed, but we never change the
7486 // request if the app changes network state. http://b/29964605
7487 enforceMeteredApnPolicy(networkCapabilities);
7488 break;
junyulai1b1c8742021-03-12 20:05:08 +08007489 case LISTEN_FOR_BEST:
7490 enforceAccessPermission();
7491 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7492 break;
junyulaiad010792021-01-11 16:53:38 +08007493 default:
7494 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007495 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007496 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007497 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007498 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007499
junyulai1b1c8742021-03-12 20:05:08 +08007500 // Enforce FOREGROUND if the caller does not have permission to use background network.
7501 if (reqType == LISTEN_FOR_BEST) {
7502 restrictBackgroundRequestForCaller(networkCapabilities);
7503 }
7504
7505 // Set the UID range for this request to the single UID of the requester, unless the
7506 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007507 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7508 // are no visible methods to set the UIDs, an app could use reflection to try and get
7509 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007510 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007511 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7512 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007513
Etan Cohen85000162017-02-05 10:42:27 -08007514 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007515 throw new IllegalArgumentException("Bad timeout specified");
7516 }
Etan Cohen9786d922015-11-18 10:56:15 -08007517
James Mattis3ce3d3c2021-02-09 18:18:28 -08007518 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007519 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007520 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007521 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007522 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007523 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007524
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007525 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7526 // copied from the default request above. (This is necessary to ensure, for example, that
7527 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7528 // changes don't alter request matching.
7529 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7530 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007531 throw new IllegalStateException(
7532 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007533 + networkCapabilities + " vs. " + defaultNc);
7534 }
7535
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007536 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007537 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007538 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007539 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007540 }
7541 return networkRequest;
7542 }
7543
James Mattis3ce3d3c2021-02-09 18:18:28 -08007544 /**
7545 * Return the nri to be used when registering a network request. Specifically, this is used with
7546 * requests registered to track the default request. If there is currently a per-app default
7547 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7548 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007549 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7550 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007551 * @param nr the network request for the nri.
7552 * @param msgr the messenger for the nri.
7553 * @param binder the binder for the nri.
7554 * @param callingAttributionTag the calling attribution tag for the nri.
7555 * @return the nri to register.
7556 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007557 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007558 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007559 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007560 @Nullable String callingAttributionTag) {
7561 final List<NetworkRequest> requests;
7562 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7563 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007564 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007565 } else {
7566 requests = Collections.singletonList(nr);
7567 }
Roshan Pius951c0032020-12-22 15:10:42 -08007568 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007569 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007570 }
7571
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007572 private boolean shouldCheckCapabilitiesDeclaration(
7573 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7574 @NonNull final String callingPackageName) {
7575 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7576 // Only run the check if the change is enabled.
7577 if (!mDeps.isChangeEnabled(
7578 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7579 callingPackageName, user)) {
7580 return false;
7581 }
7582
7583 return networkCapabilities.hasCapability(
7584 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7585 || networkCapabilities.hasCapability(
7586 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7587 }
7588
7589 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
7590 @NonNull final NetworkCapabilities networkCapabilities) {
7591 // This check is added to fix the linter error for "current min is 30", which is not going
7592 // to happen because Connectivity service always run in S+.
Chalard Jean03552c42023-05-29 17:02:43 +09007593 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007594 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7595 return;
7596 }
7597 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007598 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007599 try {
7600 synchronized (mSelfCertifiedCapabilityCache) {
7601 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7602 callerPackageName);
7603 if (applicationNetworkCapabilities == null) {
7604 final PackageManager packageManager = mContext.getPackageManager();
7605 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7606 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7607 callerPackageName
7608 );
7609 final XmlResourceParser parser = packageManager
7610 .getResourcesForApplication(callerPackageName)
7611 .getXml(networkSliceProperty.getResourceId());
7612 applicationNetworkCapabilities =
7613 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7614 mSelfCertifiedCapabilityCache.put(callerPackageName,
7615 applicationNetworkCapabilities);
7616 }
7617
7618 }
7619 } catch (PackageManager.NameNotFoundException ne) {
7620 throw new SecurityException(
7621 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7622 + " property");
7623 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7624 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007625 } finally {
7626 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007627 }
7628
7629 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7630 networkCapabilities);
7631 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007632 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007633 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007634 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7635 callingPackageName)) {
7636 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities);
7637 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007638 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007639 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7640 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7641 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7642 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007643 }
junyulai96bd9fe2022-03-08 17:36:42 +08007644 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007645 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007646 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007647 }
7648 }
7649
fenglu3f357402015-03-20 11:29:56 -07007650 @Override
fenglub00f4882015-04-21 17:12:05 -07007651 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007652 enforceAccessPermission();
7653 NetworkAgentInfo nai = null;
7654 if (network == null) {
7655 return false;
7656 }
7657 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007658 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007659 }
7660 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007661 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007662 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007663 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007664 Integer uidReqs = mBandwidthRequests.get(uid);
7665 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007666 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007667 }
7668 mBandwidthRequests.put(uid, ++uidReqs);
7669 }
fenglu3f357402015-03-20 11:29:56 -07007670 return true;
7671 }
7672 return false;
7673 }
7674
Felipe Leme0a5ae422016-06-20 16:36:29 -07007675 private boolean isSystem(int uid) {
7676 return uid < Process.FIRST_APPLICATION_UID;
7677 }
fenglu3f357402015-03-20 11:29:56 -07007678
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007679 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007680 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007681 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007682 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007683 return;
7684 }
Hugo Benichi39621362017-02-11 17:04:43 +09007685 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7686 // Policy already enforced.
7687 return;
7688 }
paulhuaf50d7d2020-12-24 19:47:34 +08007689 final long ident = Binder.clearCallingIdentity();
7690 try {
7691 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7692 // If UID is restricted, don't allow them to bring up metered APNs.
7693 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7694 }
7695 } finally {
7696 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007697 }
7698 }
7699
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007700 @Override
7701 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007702 PendingIntent operation, @NonNull String callingPackageName,
7703 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007704 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007705 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007706 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007707 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007708 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007709 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007710 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007711 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007712 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007713 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7714 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007715
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007716 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007717 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007718 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7719 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007720 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007721 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7722 nri));
7723 return networkRequest;
7724 }
7725
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007726 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7727 mHandler.sendMessageDelayed(
7728 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007729 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007730 }
7731
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007732 @Override
7733 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007734 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007735 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007736 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007737 }
7738
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007739 // In order to implement the compatibility measure for pre-M apps that call
7740 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7741 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7742 // This ensures it has permission to do so.
7743 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7744 if (nc == null) {
7745 return false;
7746 }
7747 int[] transportTypes = nc.getTransportTypes();
7748 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7749 return false;
7750 }
7751 try {
7752 mContext.enforceCallingOrSelfPermission(
7753 android.Manifest.permission.ACCESS_WIFI_STATE,
7754 "ConnectivityService");
7755 } catch (SecurityException e) {
7756 return false;
7757 }
7758 return true;
7759 }
7760
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007761 @Override
7762 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007763 Messenger messenger, IBinder binder,
7764 @NetworkCallback.Flag int callbackFlags,
7765 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007766 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007767 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7768 enforceAccessPermission();
7769 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007770
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007771 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007772 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007773 Binder.getCallingPid(), callingUid, callingPackageName);
7774 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007775 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7776 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7777 // onLost and onAvailable callbacks when networks move in and out of the background.
7778 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7779 // can't request networks.
7780 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007781 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007782
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007783 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007784 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007785 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007786 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007787 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007788 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007789
7790 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7791 return networkRequest;
7792 }
7793
7794 @Override
7795 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007796 PendingIntent operation, @NonNull String callingPackageName,
7797 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007798 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007799 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007800 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7801 enforceAccessPermission();
7802 }
Chalard Jeandd421992021-12-16 23:16:02 +09007803 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007804 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007805 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007806 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007807 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007808
7809 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007810 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007811 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7812 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007813 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007814
WeiZhang1cc3f172021-06-03 19:02:04 -05007815 mHandler.sendMessage(mHandler.obtainMessage(
7816 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007817 }
7818
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007819 /** Returns the next Network provider ID. */
7820 public final int nextNetworkProviderId() {
7821 return mNextNetworkProviderId.getAndIncrement();
7822 }
7823
Erik Kline0c04b742016-07-07 16:50:58 +09007824 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007825 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007826 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007827 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007828 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007829 }
7830
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007831 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7832 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007833 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7834 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7835 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007836 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007837 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007838 return;
7839 }
7840
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007841 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7842 mNetworkProviderInfos.put(npi.messenger, npi);
7843 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007844 }
7845
7846 @Override
7847 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007848 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007849 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007850 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007851 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007852 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7853 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007854 }
7855
7856 @Override
7857 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007858 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007859 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007860 }
7861
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007862 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007863 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007864 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7865 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007866 Objects.requireNonNull(score);
7867 Objects.requireNonNull(caps);
7868 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007869 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007870 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007871 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7872 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007873 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7874 }
7875
Chalard Jeanbb902a52021-08-18 01:35:19 +09007876 private void updateOfferScore(final NetworkOffer offer) {
7877 final boolean yieldToBadWiFi =
7878 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7879 final NetworkOffer newOffer = new NetworkOffer(
7880 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7881 offer.caps, offer.callback, offer.providerId);
7882 if (offer.equals(newOffer)) return;
7883 handleRegisterNetworkOffer(newOffer);
7884 }
7885
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007886 @Override
7887 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007888 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007889 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7890 }
7891
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007892 private void handleUnregisterNetworkProvider(Messenger messenger) {
7893 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7894 if (npi == null) {
7895 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007896 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007897 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007898 // Unregister all the offers from this provider
7899 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7900 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007901 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007902 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7903 toRemove.add(noi);
7904 }
7905 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007906 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007907 handleUnregisterNetworkOffer(noi);
7908 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007909 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007910 }
7911
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007912 @Override
James Mattisf7027322020-12-13 16:28:14 -08007913 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007914 if (request.hasTransport(TRANSPORT_TEST)) {
7915 enforceNetworkFactoryOrTestNetworksPermission();
7916 } else {
7917 enforceNetworkFactoryPermission();
7918 }
James Mattisf7027322020-12-13 16:28:14 -08007919 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7920 if (nri != null) {
7921 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7922 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7923 mHandler.post(() -> handleReleaseNetworkRequest(
7924 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7925 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007926 }
7927
Paul Jensen1f567382015-02-13 14:18:39 -05007928 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7929 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007930 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007931 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007932 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007933 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007934 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007935
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007936 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007937 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007938 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007939
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007940 // UID ranges for users that are currently blocked by VPNs.
7941 // This array is accessed and iterated on multiple threads without holding locks, so its
7942 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7943 // (on the handler thread).
7944 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7945
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007946 // Must only be accessed on the handler thread
7947 @NonNull
7948 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7949
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007950 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007951 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007952
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007953 // Current OEM network preferences. This object must only be written to on the handler thread.
7954 // Since it is immutable and always non-null, other threads may read it if they only care
7955 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007956 @NonNull
7957 private OemNetworkPreferences mOemNetworkPreferences =
7958 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007959 // Current per-profile network preferences. This object follows the same threading rules as
7960 // the OEM network preferences above.
7961 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007962 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7963 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007964
lucaslin3ba7cc22022-12-19 02:35:33 +00007965 // Current VPN network preferences. This object follows the same threading rules as the OEM
7966 // network preferences above.
7967 @NonNull
7968 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7969 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7970
paulhu51f77dc2021-06-07 02:34:20 +00007971 // A set of UIDs that should use mobile data preferentially if available. This object follows
7972 // the same threading rules as the OEM network preferences above.
7973 @NonNull
7974 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7975
James Mattiscb1e0362021-04-06 17:07:42 -07007976 // OemNetworkPreferences activity String log entries.
7977 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7978 @NonNull
7979 private final LocalLog mOemNetworkPreferencesLogs =
7980 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7981
James Mattis02220e22021-03-13 19:27:21 -08007982 /**
7983 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7984 * @param packageName the package name to check existence of a mapping for.
7985 * @return true if a mapping exists, false otherwise
7986 */
7987 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7988 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7989 }
7990
James Mattise3ef1912020-12-20 11:09:58 -08007991 // The always-on request for an Internet-capable network that apps without a specific default
7992 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007993 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007994 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007995 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007996 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007997 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007998 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007999 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09008000
James Mattisd31bdfa2020-12-23 16:37:26 -08008001 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
8002 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
8003 }
8004
8005 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08008006 * Return the default network request currently tracking the given uid.
8007 * @param uid the uid to check.
8008 * @return the NetworkRequestInfo tracking the given uid.
8009 */
8010 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08008011 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008012 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008013 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008014 // Checking the first request is sufficient as only multilayer requests will have more
8015 // than one request and for multilayer, all requests will track the same uids.
8016 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08008017 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08008018 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008019 highestPriorityNri = nri;
8020 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08008021 }
8022 }
paulhuaa0743d2021-05-26 21:56:03 +08008023 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008024 }
8025
8026 /**
8027 * Get a copy of the network requests of the default request that is currently tracking the
8028 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008029 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8030 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008031 * @param requestorUid the uid to check the default for.
8032 * @param requestorPackageName the requestor's package name.
8033 * @return a copy of the default's NetworkRequest that is tracking the given uid.
8034 */
8035 @NonNull
8036 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008037 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008038 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008039 getDefaultRequestTrackingUid(asUid).mRequests,
8040 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008041 }
8042
8043 /**
8044 * Copy the given nri's NetworkRequest collection.
8045 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008046 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8047 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008048 * @param requestorUid the uid to set on the copied collection.
8049 * @param requestorPackageName the package name to set on the copied collection.
8050 * @return the copied NetworkRequest collection.
8051 */
8052 @NonNull
8053 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008054 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
8055 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008056 final List<NetworkRequest> requests = new ArrayList<>();
8057 for (final NetworkRequest nr : requestsToCopy) {
8058 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008059 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08008060 nr.legacyType, nextNetworkRequestId(), nr.type));
8061 }
8062 return requests;
8063 }
8064
8065 @NonNull
8066 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008067 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
8068 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09008069 // These capabilities are for a TRACK_DEFAULT callback, so:
8070 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
8071 // mDefaultRequest and a per-UID default request.
8072 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008073 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09008074 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008075 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
8076 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008077 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008078 restrictRequestUidsForCallerAndSetRequestorInfo(
8079 netCap, requestorUid, requestorPackageName);
8080 return netCap;
8081 }
8082
8083 /**
8084 * Get the nri that is currently being tracked for callbacks by per-app defaults.
8085 * @param nr the network request to check for equality against.
8086 * @return the nri if one exists, null otherwise.
8087 */
8088 @Nullable
8089 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
8090 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8091 if (nri.getNetworkRequestForCallback().equals(nr)) {
8092 return nri;
8093 }
8094 }
8095 return null;
8096 }
8097
8098 /**
8099 * Check if an nri is currently being managed by per-app default networking.
8100 * @param nri the nri to check.
8101 * @return true if this nri is currently being managed by per-app default networking.
8102 */
8103 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
8104 // nri.mRequests.get(0) is only different from the original request filed in
8105 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
8106 // functionality therefore if these two don't match, it means this particular nri is
8107 // currently being managed by a per-app default.
8108 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
8109 }
8110
8111 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08008112 * Determine if an nri is a managed default request that disallows default networking.
8113 * @param nri the request to evaluate
8114 * @return true if device-default networking is disallowed
8115 */
8116 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
8117 // Check if this nri is a managed default that supports the default network at its
8118 // lowest priority request.
8119 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
8120 final NetworkCapabilities lowestPriorityNetCap =
8121 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
8122 return isPerAppDefaultRequest(nri)
8123 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
8124 lowestPriorityNetCap));
8125 }
8126
Erik Kline05f2b402015-04-30 12:58:40 +09008127 // Request used to optionally keep mobile data active even when higher
8128 // priority networks like Wi-Fi are active.
8129 private final NetworkRequest mDefaultMobileDataRequest;
8130
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07008131 // Request used to optionally keep wifi data active even when higher
8132 // priority networks like ethernet are active.
8133 private final NetworkRequest mDefaultWifiRequest;
8134
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08008135 // Request used to optionally keep vehicle internal network always active
8136 private final NetworkRequest mDefaultVehicleRequest;
8137
James Mattisd31bdfa2020-12-23 16:37:26 -08008138 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8139 // network with no service. This NAI should never be matched against, nor should any public API
8140 // ever return the associated network. For this reason, this NAI is not in the list of available
8141 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8142 // default requests that don't support using the device default network which will ultimately
8143 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8144 @VisibleForTesting
8145 final NetworkAgentInfo mNoServiceNetwork;
8146
Chalard Jean5b409c72021-02-04 13:12:59 +09008147 // The NetworkAgentInfo currently satisfying the default request, if any.
8148 private NetworkAgentInfo getDefaultNetwork() {
8149 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008150 }
8151
James Mattis2516da32021-01-31 17:06:19 -08008152 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008153 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008154 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8155 // Currently, all network requests will have the same uids therefore checking the first
8156 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008157 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008158 if (null == uids) {
8159 continue;
8160 }
8161 for (final UidRange range : uids) {
8162 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008163 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008164 highestPriorityNri = nri;
8165 }
James Mattis2516da32021-01-31 17:06:19 -08008166 }
8167 }
8168 }
paulhuaa0743d2021-05-26 21:56:03 +08008169 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008170 }
8171
Varun Ananddf569952019-02-06 10:13:38 -08008172 @Nullable
8173 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8174 return nai != null ? nai.network : null;
8175 }
8176
8177 private void ensureRunningOnConnectivityServiceThread() {
8178 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8179 throw new IllegalStateException(
8180 "Not running on ConnectivityService thread: "
8181 + Thread.currentThread().getName());
8182 }
8183 }
8184
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008185 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008186 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8187 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008188 }
8189
Chalard Jean29d06db2018-05-02 21:14:54 +09008190 /**
8191 * Register a new agent with ConnectivityService to handle a network.
8192 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008193 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008194 * @param networkInfo the initial info associated with this network. It can be updated later :
8195 * see {@link #updateNetworkInfo}.
8196 * @param linkProperties the initial link properties of this network. They can be updated
8197 * later : see {@link #updateLinkProperties}.
8198 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008199 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008200 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008201 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008202 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008203 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008204 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008205 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09008206 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09008207 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
8208 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008209 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8210 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8211 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008212 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008213 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008214 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008215 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008216 } else {
8217 enforceNetworkFactoryPermission();
8218 }
8219
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008220 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008221 final long token = Binder.clearCallingIdentity();
8222 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008223 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09008224 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008225 } finally {
8226 Binder.restoreCallingIdentity(token);
8227 }
8228 }
8229
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008230 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008231 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09008232 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
8233 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008234
Chalard Jeandbc46952022-02-02 00:14:18 +09008235 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8236 // and mutate them at any time.
8237 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8238 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8239 final LinkProperties lpCopy = new LinkProperties(linkProperties);
8240
Chalard Jean366c5252022-01-25 18:27:53 +09008241 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008242 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008243 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8244 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008245 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008246 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09008247 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09008248 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
8249 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008250
Chalard Jeandbc46952022-02-02 00:14:18 +09008251 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008252 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008253 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008254 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008255 mDeps.getNetworkStack().makeNetworkMonitor(
8256 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008257 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8258 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008259 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008260 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008261 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008262 }
8263
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008264 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008265 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008266 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008267 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008268 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008269 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8270 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8271 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008272
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008273 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008274
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008275 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008276 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008277 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008278 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008279
8280 try {
8281 networkMonitor.start();
8282 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008283 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008284 }
Chalard Jean366c5252022-01-25 18:27:53 +09008285
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008286 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008287 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008288 updateNetworkInfo(nai, networkInfo);
Tommy Webb34f81dc2023-02-20 14:10:55 -05008289 updateDisallowedUidsForNetwork(nai);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008290 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008291 }
8292
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008293 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8294 @NonNull public final NetworkOffer offer;
8295
8296 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8297 this.offer = offer;
8298 }
8299
8300 @Override
8301 public void binderDied() {
8302 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8303 }
8304 }
8305
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008306 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8307 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8308 if (npi.providerId == providerId) return true;
8309 }
8310 return false;
8311 }
8312
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008313 /**
8314 * Register or update a network offer.
8315 * @param newOffer The new offer. If the callback member is the same as an existing
8316 * offer, it is an update of that offer.
8317 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008318 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008319 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8320 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008321 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008322 // This may actually happen if a provider updates its score or registers and then
8323 // immediately unregisters. The offer would still be in the handler queue, but the
8324 // provider would have been removed.
8325 if (DBG) log("Received offer from an unregistered provider");
8326 return;
8327 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008328 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8329 if (null != existingOffer) {
8330 handleUnregisterNetworkOffer(existingOffer);
8331 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008332 if (DBG) {
8333 // handleUnregisterNetworkOffer has already logged the old offer
8334 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8335 }
8336 } else {
8337 if (DBG) {
8338 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8339 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008340 }
8341 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8342 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008343 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008344 } catch (RemoteException e) {
8345 noi.binderDied();
8346 return;
8347 }
8348 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008349 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008350 }
8351
8352 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8353 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008354 if (DBG) {
8355 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8356 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008357
8358 // If the provider removes the offer and dies immediately afterwards this
8359 // function may be called twice in a row, but the array will no longer contain
8360 // the offer.
8361 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008362 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008363 }
8364
8365 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8366 @NonNull final INetworkOfferCallback callback) {
8367 ensureRunningOnConnectivityServiceThread();
8368 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008369 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008370 }
8371 return null;
8372 }
8373
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008374 /**
8375 * Called when receiving LinkProperties directly from a NetworkAgent.
8376 * Stores into |nai| any data coming from the agent that might also be written to the network's
8377 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8378 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008379 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008380 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008381 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8382 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008383 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008384 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008385 }
8386
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008387 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008388 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008389 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008390
Lorenzo Colittid523d142020-04-01 20:16:30 +09008391 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8392 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8393 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008394 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008395
Oliver Scottb825c6f2022-10-27 23:52:45 +00008396 final boolean anyIfaceChanges =
8397 updateInterfaces(newLp, oldLp, netId, networkAgent);
8398
8399 // If any interface names changed, ensure VPN filtering is updated so that ingress filtering
8400 // uses the most up-to-date allowed interface.
8401 final boolean shouldForceUpdateVpnFiltering = networkAgent.isVPN() && anyIfaceChanges;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008402
8403 // update filtering rules, need to happen after the interface update so netd knows about the
8404 // new interface (the interface name -> index map becomes initialized)
Oliver Scottb825c6f2022-10-27 23:52:45 +00008405 updateVpnFiltering(newLp, oldLp, networkAgent, shouldForceUpdateVpnFiltering);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008406
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008407 updateMtu(newLp, oldLp);
8408 // TODO - figure out what to do for clat
8409// for (LinkProperties lp : newLp.getStackedLinks()) {
8410// updateMtu(lp, null);
8411// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008412 if (isDefaultNetwork(networkAgent)) {
Aaron Huang25ef1712021-06-08 13:11:45 +08008413 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008414 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8415 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008416
Erik Klineb9888902016-04-05 13:30:49 +09008417 updateRoutes(newLp, oldLp, netId);
8418 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008419 // Make sure LinkProperties represents the latest private DNS status.
8420 // This does not need to be done before updateDnses because the
8421 // LinkProperties are not the source of the private DNS configuration.
8422 // updateDnses will fetch the private DNS configuration from DnsManager.
8423 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008424
Chalard Jean5b409c72021-02-04 13:12:59 +09008425 if (isDefaultNetwork(networkAgent)) {
Aaron Huang25ef1712021-06-08 13:11:45 +08008426 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09008427 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008428 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008429 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008430
8431 updateWakeOnLan(newLp);
8432
Hai Shalome58bdc62021-01-11 18:45:34 -08008433 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8434 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8435 // does, it needs to be merged here.
8436 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8437 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008438
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008439 // TODO - move this check to cover the whole function
8440 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008441 synchronized (networkAgent) {
8442 networkAgent.linkProperties = newLp;
8443 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008444 // Start or stop DNS64 detection and 464xlat according to network state.
8445 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008446 // Notify NSS when relevant events happened. Currently, NSS only cares about
8447 // interface changed to update clat interfaces accounting.
8448 final boolean interfacesChanged = oldLp == null
8449 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8450 if (interfacesChanged) {
8451 notifyIfacesChangedForNetworkStats();
8452 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008453 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8454 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008455 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008456 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008457
8458 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008459 }
8460
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09008461 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8462 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8463 }
8464
Hai Shalome58bdc62021-01-11 18:45:34 -08008465 /**
8466 * @param naData captive portal data from NetworkAgent
8467 * @param apiData captive portal data from capport API
8468 */
8469 @Nullable
8470 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8471 CaptivePortalData apiData) {
8472 if (naData == null || apiData == null) {
8473 return naData == null ? apiData : naData;
8474 }
8475 final CaptivePortalData.Builder captivePortalBuilder =
8476 new CaptivePortalData.Builder(naData);
8477
8478 if (apiData.isCaptive()) {
8479 captivePortalBuilder.setCaptive(true);
8480 }
8481 if (apiData.isSessionExtendable()) {
8482 captivePortalBuilder.setSessionExtendable(true);
8483 }
8484 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8485 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8486 // otherwise data would be inconsistent. Prefer the capport API info if present,
8487 // as it can generally be refreshed more often.
8488 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8489 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8490 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8491 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8492 // No source has time / bytes remaining information: surface the newest refresh time
8493 // for other fields
8494 captivePortalBuilder.setRefreshTime(
8495 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8496 }
8497
Hai Shalom7c6ab402021-02-04 19:34:06 -08008498 // Prioritize the user portal URL from the network agent if the source is authenticated.
8499 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8500 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8501 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8502 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008503 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008504 // Prioritize the venue information URL from the network agent if the source is
8505 // authenticated.
8506 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8507 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8508 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8509 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008510 }
8511 return captivePortalBuilder.build();
8512 }
8513
Suprabh Shukla619549f2023-04-26 18:47:36 -07008514 @VisibleForTesting
8515 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008516 // This needs to be kept in sync and backwards compatible with the decoding logic in
8517 // NetdEventListenerService, which is non-mainline code.
8518 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8519 }
8520
Suprabh Shukla63e59342023-04-25 23:15:43 -07008521 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8522 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8523 return true;
8524 }
8525 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8526 return true;
8527 }
8528 return false;
8529 }
8530
Suprabh Shukla1e312032023-01-24 03:36:37 -08008531 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008532 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008533 // marks on unsupported interfaces is harmless.
Suprabh Shukla63e59342023-04-25 23:15:43 -07008534 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008535 return;
8536 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008537
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008538 // Mask/mark of zero will not detect anything interesting.
8539 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskif310a142023-06-05 07:29:28 +00008540 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008541 return;
8542 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008543
Suprabh Shukla1e312032023-01-24 03:36:37 -08008544 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008545 try {
8546 if (add) {
Maciej Żenczykowskif310a142023-06-05 07:29:28 +00008547 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008548 } else {
Maciej Żenczykowskif310a142023-06-05 07:29:28 +00008549 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008550 }
8551 } catch (Exception e) {
8552 loge("Exception modifying wakeup packet monitoring: " + e);
8553 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008554 }
8555
Oliver Scottb825c6f2022-10-27 23:52:45 +00008556 /** Return whether there were any added or removed interface names. */
8557 private boolean updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008558 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008559 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008560 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008561 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008562 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008563 for (final String iface : interfaceDiff.added) {
8564 try {
8565 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008566 mNetd.networkAddInterface(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008567 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008568 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008569 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008570 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008571 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008572 }
Paul Jensenbff73492014-04-28 10:33:11 -04008573 }
8574 }
Chalard Jean9589e722019-11-19 19:03:53 +09008575 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008576 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008577 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008578 wakeupModifyInterface(iface, nai, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008579 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008580 } catch (Exception e) {
8581 loge("Exception removing interface: " + e);
8582 }
8583 }
Oliver Scottb825c6f2022-10-27 23:52:45 +00008584 return !(interfaceDiff.added.isEmpty() && interfaceDiff.removed.isEmpty());
Paul Jensenbff73492014-04-28 10:33:11 -04008585 }
8586
Tyler Weare4314862019-12-05 14:55:30 -08008587 // TODO: move to frameworks/libs/net.
8588 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
8589 final String nextHop;
8590
8591 switch (route.getType()) {
8592 case RouteInfo.RTN_UNICAST:
8593 if (route.hasGateway()) {
8594 nextHop = route.getGateway().getHostAddress();
8595 } else {
8596 nextHop = INetd.NEXTHOP_NONE;
8597 }
8598 break;
8599 case RouteInfo.RTN_UNREACHABLE:
8600 nextHop = INetd.NEXTHOP_UNREACHABLE;
8601 break;
8602 case RouteInfo.RTN_THROW:
8603 nextHop = INetd.NEXTHOP_THROW;
8604 break;
8605 default:
8606 nextHop = INetd.NEXTHOP_NONE;
8607 break;
8608 }
8609
8610 final RouteInfoParcel rip = new RouteInfoParcel();
8611 rip.ifName = route.getInterface();
8612 rip.destination = route.getDestination().toString();
8613 rip.nextHop = nextHop;
8614 rip.mtu = route.getMtu();
8615
8616 return rip;
8617 }
8618
Paul Jensene0fd4a82014-08-06 15:51:33 -04008619 /**
8620 * Have netd update routes from oldLp to newLp.
8621 * @return true if routes changed between oldLp and newLp
8622 */
Junyu Lai970963e2022-10-25 15:46:47 +08008623 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8624 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008625 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008626 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8627 new CompareOrUpdateResult<>(
8628 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008629 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008630 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008631
8632 // add routes before removing old in case it helps with continuous connectivity
8633
Chalard Jean9dd11612018-06-04 16:52:49 +09008634 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008635 for (RouteInfo route : routeDiff.added) {
8636 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008637 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008638 try {
Tyler Weare4314862019-12-05 14:55:30 -08008639 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008640 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008641 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008642 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008643 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008644 }
8645 }
8646 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008647 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008648 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008649 try {
Tyler Weare4314862019-12-05 14:55:30 -08008650 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008651 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008652 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008653 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008654 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008655 }
8656 }
8657
8658 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008659 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008660 try {
Tyler Weare4314862019-12-05 14:55:30 -08008661 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008662 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08008663 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008664 }
8665 }
Tyler Weare4314862019-12-05 14:55:30 -08008666
8667 for (RouteInfo route : routeDiff.updated) {
8668 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8669 try {
8670 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
8671 } catch (Exception e) {
8672 loge("Exception in networkUpdateRouteParcel: " + e);
8673 }
8674 }
8675 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8676 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008677 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008678
Junyu Lai970963e2022-10-25 15:46:47 +08008679 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8680 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008681 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8682 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008683 }
Erik Klineb9888902016-04-05 13:30:49 +09008684
Erik Kline31b4a9e2018-01-11 21:07:29 +09008685 if (DBG) {
8686 final Collection<InetAddress> dnses = newLp.getDnsServers();
8687 log("Setting DNS servers for network " + netId + " to " + dnses);
8688 }
Erik Klineb9888902016-04-05 13:30:49 +09008689 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008690 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008691 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008692 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008693 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008694 }
Erik Kline54e35c02017-04-07 15:29:29 +09008695 }
8696
Junyu Lai970963e2022-10-25 15:46:47 +08008697 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
Oliver Scottb825c6f2022-10-27 23:52:45 +00008698 @NonNull NetworkAgentInfo nai, boolean force) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008699 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8700 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008701 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8702 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008703
8704 if (!wasFiltering && !needsFiltering) {
8705 // Nothing to do.
8706 return;
8707 }
8708
Oliver Scottb825c6f2022-10-27 23:52:45 +00008709 if (!force && Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008710 // Nothing changed.
8711 return;
8712 }
8713
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008714 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008715 if (ranges == null || ranges.isEmpty()) {
8716 return;
8717 }
8718
Qingxi Libb8da982020-01-17 17:54:27 -08008719 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008720 // TODO: this create a window of opportunity for apps to receive traffic between the time
8721 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008722 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008723 // old rules are being removed.
8724 if (wasFiltering) {
8725 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
Oliver Scottb825c6f2022-10-27 23:52:45 +00008726 mPermissionMonitor.updateVpnLockdownUidInterfaceRules(oldLp.getInterfaceName(), ranges,
8727 vpnAppUid, false /* add */);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008728 }
8729 if (needsFiltering) {
8730 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
Oliver Scottb825c6f2022-10-27 23:52:45 +00008731 mPermissionMonitor.updateVpnLockdownUidInterfaceRules(newLp.getInterfaceName(), ranges,
8732 vpnAppUid, true /* add */);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008733 }
8734 }
8735
Valentin Iftime9fa35092019-09-24 13:32:13 +02008736 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008737 if (mWolSupportedInterfaces == null) {
8738 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008739 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008740 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008741 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8742 }
8743
Luke Huangb913c812018-08-24 20:33:16 +08008744 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008745 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008746 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008747 }
8748 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008749 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008750 }
Luke Huangb913c812018-08-24 20:33:16 +08008751 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008752 }
8753
Chalard Jean62edfd82019-12-02 18:39:29 +09008754 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8755 @NonNull final NetworkCapabilities newNc) {
8756 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8757 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008758 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008759 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008760 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008761 } catch (RemoteException | ServiceSpecificException e) {
8762 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008763 }
8764 }
8765 }
8766
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008767 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008768 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008769 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008770 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008771 underlyingNetworks = underlyingNetworksOrDefault(
8772 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008773 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008774 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8775 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008776 // metered if any underlying is metered, or originally declared metered by the agent.
8777 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008778 boolean roaming = false; // roaming if any underlying is roaming
8779 boolean congested = false; // congested if any underlying is congested
8780 boolean suspended = true; // suspended if all underlying are suspended
8781
8782 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008783 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008784 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008785 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008786 for (Network underlyingNetwork : underlyingNetworks) {
8787 final NetworkAgentInfo underlying =
8788 getNetworkAgentInfoForNetwork(underlyingNetwork);
8789 if (underlying == null) continue;
8790
8791 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8792 hadUnderlyingNetworks = true;
8793 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008794 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008795 }
8796
8797 // Merge capabilities of this underlying network. For bandwidth, assume the
8798 // worst case.
8799 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8800 underlyingCaps.getLinkDownstreamBandwidthKbps());
8801 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8802 underlyingCaps.getLinkUpstreamBandwidthKbps());
8803 // If this underlying network is metered, the VPN is metered (it may cost money
8804 // to send packets on this network).
8805 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8806 // If this underlying network is roaming, the VPN is roaming (the billing structure
8807 // is different than the usual, local one).
8808 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8809 // If this underlying network is congested, the VPN is congested (the current
8810 // condition of the network affects the performance of this network).
8811 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8812 // If this network is not suspended, the VPN is not suspended (the VPN
8813 // is able to transfer some data).
8814 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008815 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008816 }
8817 }
8818 if (!hadUnderlyingNetworks) {
8819 // No idea what the underlying networks are; assume reasonable defaults
8820 metered = true;
8821 roaming = false;
8822 congested = false;
8823 suspended = false;
8824 }
8825
Chalard Jean1d420b32022-10-12 16:39:37 +09008826 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008827 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8828 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8829 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8830 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8831 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8832 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008833 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008834 }
8835
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008836 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008837 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8838 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8839 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008840 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008841 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008842 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008843 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008844 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8845 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008846 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008847 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008848 if (nai.everConnected()
8849 && !nai.isVPN()
8850 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008851 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008852 // does not cause any request (that is not a listen) currently matching that agent to
8853 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008854 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008855 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008856 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008857 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008858 }
8859
Paul Jensen53f08952015-06-16 14:27:36 -04008860 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008861 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008862 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008863 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008864 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008865 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008866 }
Chalard Jean254bd162022-08-25 13:04:51 +09008867 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008868 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008869 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008870 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008871 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008872 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008873 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008874 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008875 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008876 }
Chalard Jean254bd162022-08-25 13:04:51 +09008877 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008878 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8879 } else {
8880 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8881 }
lucasline117e2e2019-10-22 18:27:33 +08008882 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008883
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008884 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008885 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8886 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008887 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008888 }
8889
Lorenzo Colittibd079452021-07-02 11:47:57 +09008890 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008891 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008892 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008893 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008894 }
8895
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008896 return newNc;
8897 }
8898
Lorenzo Colitti44840702021-01-11 22:27:57 +09008899 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8900 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8901 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8902 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8903 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8904 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8905 if (prevSuspended != suspended) {
8906 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8907 // onResumed have been removed.
8908 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8909 : ConnectivityManager.CALLBACK_RESUMED);
8910 }
8911 if (prevSuspended != suspended || prevRoaming != roaming) {
8912 // updateNetworkInfo will mix in the suspended info from the capabilities and
8913 // take appropriate action for the network having possibly changed state.
8914 updateNetworkInfo(nai, nai.networkInfo);
8915 }
8916 }
8917
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008918 /**
8919 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8920 *
8921 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8922 * capabilities we manage and store in {@code nai}, such as validated status and captive
8923 * portal status)
8924 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8925 * potentially triggers rematches.
8926 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8927 * change.)
8928 *
8929 * @param oldScore score of the network before any of the changes that prompted us
8930 * to call this function.
8931 * @param nai the network having its capabilities updated.
8932 * @param nc the new network capabilities.
8933 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008934 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008935 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008936 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008937 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008938 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8939 if (null != differences) {
8940 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8941 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008942 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008943 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008944
Tommy Webb34f81dc2023-02-20 14:10:55 -05008945 if (prevNc != null && (!prevNc.equalsUids(newNc) || !prevNc.equalsTransportTypes(newNc))) {
8946 updateDisallowedUidsForNetwork(nai);
8947 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008948 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008949 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008950 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008951
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008952 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008953 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8954 // the change we're processing can't affect any requests, it can only affect the listens
8955 // on this network. We might have been called by rematchNetworkAndRequests when a
8956 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008957 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008958 } else {
8959 // If the requestable capabilities have changed or the score changed, we can't have been
8960 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008961 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008962 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008963 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008964 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008965
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008966 final boolean oldMetered = prevNc.isMetered();
8967 final boolean newMetered = newNc.isMetered();
8968 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008969
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008970 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008971 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8972 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008973 }
junyulaif2c67e42018-08-07 19:50:45 +08008974
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008975 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8976 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008977
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008978 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008979 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008980 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008981 }
8982
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008983 // This network might have been underlying another network. Propagate its capabilities.
8984 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008985
8986 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008987 mDnsManager.updateTransportsForNetwork(
8988 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008989 }
lucaslin53e8a262021-06-08 01:43:59 +08008990
8991 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008992 }
8993
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008994 /** Convenience method to update the capabilities for a given network. */
8995 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008996 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008997 }
8998
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008999 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00009000 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009001 *
9002 * Ingress interface filtering enforces that all apps under the given network can only receive
9003 * packets from the network's interface (and loopback). This is important for VPNs because
9004 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
9005 * non-VPN interfaces.
9006 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00009007 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009008 * 1. the network is an app VPN (not legacy VPN)
9009 * 2. the VPN does not allow bypass
9010 * 3. the VPN is fully-routed
9011 * 4. the VPN interface is non-null
9012 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09009013 * @see INetd#firewallAddUidInterfaceRules
9014 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009015 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00009016 @Nullable
9017 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009018 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009019 if (nc == null || lp == null) return null;
9020 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009021 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08009022 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009023 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08009024 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00009025 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00009026 && !lp.hasExcludeRoute()) {
9027 return lp.getInterfaceName();
9028 }
9029 return null;
9030 }
9031
9032 /**
9033 * Returns whether we need to set interface filtering rule or not
9034 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00009035 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00009036 String isolationIface) {
9037 // Allow rules are always needed if VPN isolation is enabled.
9038 if (isolationIface != null) return true;
9039
9040 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
9041 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
9042 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jean03552c42023-05-29 17:02:43 +09009043 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009044 }
9045
Chiachang Wang28afaff2020-12-10 22:24:47 +08009046 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
9047 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
9048 int index = 0;
9049 for (UidRange range : ranges) {
9050 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
9051 index++;
9052 }
9053 return stableRanges;
9054 }
9055
Chalard Jeane6c95272022-01-25 21:04:21 +09009056 private static UidRangeParcel[] intsToUidRangeStableParcels(
9057 final @NonNull ArraySet<Integer> uids) {
9058 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
9059 int index = 0;
9060 for (int uid : uids) {
9061 stableRanges[index] = new UidRangeParcel(uid, uid);
9062 index++;
9063 }
9064 return stableRanges;
9065 }
9066
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009067 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
9068 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
9069 for (int i = 0; i < ranges.length; i++) {
9070 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
9071 }
9072 return stableRanges;
9073 }
9074
Motomu Utsumia20f7602023-03-16 17:04:21 +09009075 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi5d718002023-06-04 21:32:08 +09009076 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08009077 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
9078 try {
Motomu Utsumi5d718002023-06-04 21:32:08 +09009079 if (mDeps.isAtLeastU()) {
9080 final Set<Integer> exemptUidSet = new ArraySet<>();
9081 for (final int uid: exemptUids) {
9082 exemptUidSet.add(uid);
9083 }
9084 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
9085 } else {
9086 mNetd.socketDestroy(uidRangeParcels, exemptUids);
9087 }
Ken Chen5e65a852020-12-24 12:59:10 +08009088 } catch (Exception e) {
9089 loge("Exception in socket destroy: ", e);
9090 }
9091 }
9092 }
9093
paulhuaa0743d2021-05-26 21:56:03 +08009094 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi5d718002023-06-04 21:32:08 +09009095 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08009096 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
9097 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
9098 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi5d718002023-06-04 21:32:08 +09009099 exemptUids[0] = VPN_UID;
9100 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08009101 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
9102
Motomu Utsumi6345e462023-03-13 13:24:50 +09009103 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi5d718002023-06-04 21:32:08 +09009104 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009105 try {
9106 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08009107 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009108 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009109 } else {
paulhu0e79d952021-06-09 16:11:35 +08009110 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009111 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009112 }
9113 } catch (Exception e) {
9114 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
9115 " on netId " + nai.network.netId + ". " + e);
9116 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09009117 // Close sockets that established connection while requesting netd.
Motomu Utsumi5d718002023-06-04 21:32:08 +09009118 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009119 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009120
lucaslin53e8a262021-06-08 01:43:59 +08009121 private boolean isProxySetOnAnyDefaultNetwork() {
9122 ensureRunningOnConnectivityServiceThread();
9123 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9124 final NetworkAgentInfo nai = nri.getSatisfier();
9125 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
9126 return true;
9127 }
9128 }
9129 return false;
9130 }
9131
9132 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
9133 NetworkCapabilities newNc) {
9134 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
9135 // the proxy might be changed since the default network satisfied by the apps might also
9136 // changed.
9137 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
9138 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09009139 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
9140 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09009141 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08009142 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
9143 mProxyTracker.sendProxyBroadcast();
9144 }
9145 }
9146
Chalard Jeane6c95272022-01-25 21:04:21 +09009147 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
9148 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009149 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
9150 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009151 if (null == prevRanges) prevRanges = new ArraySet<>();
9152 if (null == newRanges) newRanges = new ArraySet<>();
9153 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9154
9155 prevRanges.removeAll(newRanges);
9156 newRanges.removeAll(prevRangesCopy);
9157
9158 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009159 // When updating the VPN uid routing rules, add the new range first then remove the old
9160 // range. If old range were removed first, there would be a window between the old
9161 // range being removed and the new range being added, during which UIDs contained
9162 // in both ranges are not subject to any VPN routing rules. Adding new range before
9163 // removing old range works because, unlike the filtering rules below, it's possible to
9164 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009165 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9166 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9167 // [1-5] & [1-2],[4-5] == [3]
9168 // Then we can do:
9169 // maybeCloseSockets([3])
9170 // mNetd.networkAddUidRanges([1-2],[4-5])
9171 // mNetd.networkRemoveUidRanges([1-5])
9172 // maybeCloseSockets([3])
9173 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9174 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009175 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009176 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009177 }
9178 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009179 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009180 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009181 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9182 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009183 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9184 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009185 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009186 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009187 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9188 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9189 // were added first and then newRanges got removed later, there would be only one uid
9190 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9191 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9192 // Note that this is in contrast with the (more robust) update of VPN routing rules
9193 // above, where the addition of new ranges happens before the removal of old ranges.
9194 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9195 // to be removed will never overlap with the new range to be added.
9196 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009197 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9198 prevNc.getOwnerUid());
Oliver Scottb825c6f2022-10-27 23:52:45 +00009199 mPermissionMonitor.updateVpnLockdownUidInterfaceRules(
9200 nai.linkProperties.getInterfaceName(), prevRanges, prevNc.getOwnerUid(),
9201 false /* add */);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009202 }
9203 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009204 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Oliver Scottb825c6f2022-10-27 23:52:45 +00009205 mPermissionMonitor.updateVpnLockdownUidInterfaceRules(
9206 nai.linkProperties.getInterfaceName(), newRanges, newNc.getOwnerUid(),
9207 true /* add */);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009208 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009209 } catch (Exception e) {
9210 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009211 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009212 }
9213 }
9214
Chalard Jeande665262022-02-25 16:12:12 +09009215 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009216 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
Tommy Webb34f81dc2023-02-20 14:10:55 -05009217 if (!nai.isVPN()) {
9218 updateAllowedUidsForNetwork(nai);
9219 }
Chalard Jeane6c95272022-01-25 21:04:21 +09009220 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009221 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9222 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009223 if (prevEmpty && newEmpty) return;
9224
9225 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009226 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009227 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009228 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009229
9230 if (prevUids.equals(newUids)) return;
9231
9232 // This implementation is very simple and vastly faster for sets of Integers than
9233 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9234 // a key computed from the value and has storage for that.
9235 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9236 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9237 toRemove.removeAll(newUids);
9238 toAdd.removeAll(prevUids);
9239
9240 try {
9241 if (!toAdd.isEmpty()) {
9242 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9243 nai.network.netId,
9244 intsToUidRangeStableParcels(toAdd),
9245 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9246 }
9247 if (!toRemove.isEmpty()) {
9248 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9249 nai.network.netId,
9250 intsToUidRangeStableParcels(toRemove),
9251 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9252 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009253 } catch (ServiceSpecificException e) {
9254 // Has the interface disappeared since the network was built ?
9255 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009256 } catch (RemoteException e) {
9257 // Netd died. This usually causes a runtime restart anyway.
9258 }
9259 }
9260
Junyu Lai2ed7d412022-10-07 16:52:21 +08009261 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9262 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009263 ensureRunningOnConnectivityServiceThread();
9264
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009265 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009266 // Ignore updates for disconnected networks
9267 return;
9268 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009269 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009270 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009271 + "; created=" + nai.getCreatedTime()
9272 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009273 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009274 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9275 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009276 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009277 }
9278
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009279 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9280 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009281 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009282 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009283 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009284 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9285 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9286 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009287 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9288 // need to be sent as a separate extra.
9289 final NetworkRequest req = nri.isMultilayerRequest()
9290 ? nri.getActiveRequest()
9291 // Non-multilayer listen requests do not have an active request
9292 : nri.mRequests.get(0);
9293 if (req == null) {
9294 Log.wtf(TAG, "No request in NRI " + nri);
9295 }
9296 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009297 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009298 sendIntent(nri.mPendingIntent, intent);
9299 }
9300 // else not handled
9301 }
9302
Michael Groover73f69482023-01-27 11:01:25 -06009303 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9304 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009305 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9306 mPendingIntentWakeLock.acquire();
9307 try {
9308 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009309 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jean03552c42023-05-29 17:02:43 +09009310 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009311 // Explicitly disallow the receiver from starting activities, to prevent apps from
9312 // utilizing the PendingIntent as a backdoor to do this.
9313 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9314 }
9315 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9316 null /* requiredPermission */,
Chalard Jean03552c42023-05-29 17:02:43 +09009317 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009318 } catch (PendingIntent.CanceledException e) {
9319 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9320 mPendingIntentWakeLock.release();
9321 releasePendingNetworkRequest(pendingIntent);
9322 }
9323 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9324 }
9325
9326 @Override
9327 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9328 String resultData, Bundle resultExtras) {
9329 if (DBG) log("Finished sending " + pendingIntent);
9330 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009331 // Release with a delay so the receiving client has an opportunity to put in its
9332 // own request.
9333 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009334 }
9335
Chalard Jean46bfbf02022-02-02 00:56:25 +09009336 // networkAgent is only allowed to be null if notificationType is
9337 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9338 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009339 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009340 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009341 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009342 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009343 // Default request has no msgr. Also prevents callbacks from being invoked for
9344 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9345 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9346 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009347 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009348 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009349 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009350 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009351 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009352 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009353 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009354 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9355 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009356 }
Roshan Pius951c0032020-12-22 15:10:42 -08009357 final boolean includeLocationSensitiveInfo =
9358 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009359 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009360 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009361 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009362 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009363 networkCapabilitiesRestrictedForCallerPermissions(
9364 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9365 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009366 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009367 nri.mCallingAttributionTag);
9368 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009369 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9370 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08009371 // For this notification, arg1 contains the blocked status.
9372 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009373 break;
9374 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009375 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009376 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009377 break;
9378 }
9379 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009380 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009381 final NetworkCapabilities netCap =
9382 networkCapabilitiesRestrictedForCallerPermissions(
9383 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9384 putParcelable(
9385 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009386 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009387 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009388 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009389 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009390 break;
9391 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009392 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009393 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9394 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009395 break;
9396 }
junyulaif2c67e42018-08-07 19:50:45 +08009397 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009398 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009399 msg.arg1 = arg1;
9400 break;
9401 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009402 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009403 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009404 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009405 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009406 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009407 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009408 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009409 }
James Mattis45d81842021-01-10 14:24:24 -08009410 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009411 } catch (RemoteException e) {
9412 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009413 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009414 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009415 }
9416
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009417 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9418 bundle.putParcelable(t.getClass().getSimpleName(), t);
9419 }
9420
Chalard Jean0702f982021-09-16 21:50:07 +09009421 /**
9422 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9423 *
9424 * When a request should be assigned to a new network, it is normally lingered to give
9425 * time for apps to gracefully migrate their connections. When both networks are on the same
9426 * radio, but that radio can't do time-sharing efficiently, this may end up being
9427 * counter-productive because any traffic on the old network may drastically reduce the
9428 * performance of the new network.
9429 * The stack supports a configuration to let modem vendors state that their radio can't
9430 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9431 * from one cell network to another can't be done gracefully.
9432 *
9433 * @param oldNai the old network serving the request
9434 * @param newNai the new network serving the request
9435 * @return whether the switch can be graceful
9436 */
9437 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9438 @NonNull final NetworkAgentInfo newSatisfier) {
9439 if (mCellularRadioTimesharingCapable) return true;
9440 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9441 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9442 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9443 }
9444
Paul Jensenaf94b982014-09-30 15:37:41 -04009445 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009446 if (nai.numRequestNetworkRequests() != 0) {
9447 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9448 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009449 // Ignore listening and track default requests.
9450 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009451 loge("Dead network still had at least " + nr);
9452 break;
9453 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009454 }
Jean Chalard01a7d322023-06-27 08:54:23 +00009455 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009456 }
9457
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009458 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9459 if (oldNetwork == null) {
9460 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9461 return;
9462 }
Chalard Jean49707572019-12-10 21:07:02 +09009463 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009464
9465 // If we get here it means that the last linger timeout for this network expired. So there
9466 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009467 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009468
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009469 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009470 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009471 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009472 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009473 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009474 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009475 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009476 }
9477
James Mattise3ef1912020-12-20 11:09:58 -08009478 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9479 boolean isDefaultChanged = false;
9480 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9481 final NetworkReassignment.RequestReassignment reassignment =
9482 changes.getReassignment(defaultRequestInfo);
9483 if (null == reassignment) {
9484 continue;
9485 }
9486 // reassignment only contains those instances where the satisfying network changed.
9487 isDefaultChanged = true;
9488 // Notify system services of the new default.
9489 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9490 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009491
James Mattise3ef1912020-12-20 11:09:58 -08009492 if (isDefaultChanged) {
9493 // Hold a wakelock for a short time to help apps in migrating to a new default.
9494 scheduleReleaseNetworkTransitionWakelock();
9495 }
9496 }
9497
Aaron Huang25ef1712021-06-08 13:11:45 +08009498 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9499 if (null == oldDefaultNetwork) return;
9500 // The network stopped being the default. If it was using a PAC proxy, then the
9501 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9502 // to the local proxy server, which would forward them over the newly default network.
9503 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9504 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9505 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9506 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9507 }
9508
James Mattise3ef1912020-12-20 11:09:58 -08009509 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9510 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9511 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9512 if (DBG) {
9513 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9514 }
Chalard Jean8e382112019-12-03 20:45:30 +09009515
James Mattisd31bdfa2020-12-23 16:37:26 -08009516 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9517 if (newDefaultNetwork != null) {
9518 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009519 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009520
James Mattisd31bdfa2020-12-23 16:37:26 -08009521 // Set an app level managed default and return since further processing only applies to the
9522 // default network.
9523 if (mDefaultRequest != nri) {
9524 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9525 return;
9526 }
9527
9528 makeDefaultNetwork(newDefaultNetwork);
9529
James Mattise3ef1912020-12-20 11:09:58 -08009530 if (oldDefaultNetwork != null) {
9531 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9532 }
9533 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang25ef1712021-06-08 13:11:45 +08009534 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009535 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang25ef1712021-06-08 13:11:45 +08009536 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009537 updateTcpBufferSizes(null != newDefaultNetwork
9538 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009539 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009540 }
9541
James Mattisd31bdfa2020-12-23 16:37:26 -08009542 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9543 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9544 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9545 try {
9546 if (VDBG) {
9547 log("Setting default network for " + nri
9548 + " using UIDs " + nri.getUids()
9549 + " with old network " + (oldDefaultNetwork != null
9550 ? oldDefaultNetwork.network().getNetId() : "null")
9551 + " and new network " + (newDefaultNetwork != null
9552 ? newDefaultNetwork.network().getNetId() : "null"));
9553 }
9554 if (nri.getUids().isEmpty()) {
9555 throw new IllegalStateException("makeDefaultForApps called without specifying"
9556 + " any applications to set as the default." + nri);
9557 }
9558 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009559 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009560 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009561 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009562 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009563 }
9564 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009565 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009566 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009567 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009568 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009569 }
9570 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009571 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009572 }
Tommy Webb34f81dc2023-02-20 14:10:55 -05009573 updateUidDefaultNetworkRules(newDefaultNetwork);
James Mattisd31bdfa2020-12-23 16:37:26 -08009574 }
9575
Junyu Lai35665cc2022-12-19 17:37:48 +08009576 /**
9577 * Collect restricted uid ranges for the given network and UserHandle, these uids
9578 * are not restricted for matched enterprise networks but being restricted for non-matched
9579 * enterprise networks and non-enterprise networks.
9580 */
9581 @NonNull
9582 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9583 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9584 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9585 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9586 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9587
9588 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9589 // The NC is built from a `ProfileNetworkPreference` which has only one
9590 // enterprise ID, so it's guaranteed to have exactly one.
9591 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9592 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9593 continue;
9594 }
9595 }
9596
9597 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9598 pref.capabilities.getUidRanges())) {
9599 throw new IllegalArgumentException(
9600 "Overlapping uid range in preference: " + pref);
9601 }
9602 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9603 }
9604 return restrictedUidRanges;
9605 }
9606
9607 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009608 // Netd command is not implemented before U.
Chalard Jean03552c42023-05-29 17:02:43 +09009609 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +08009610
Junyu Lai35665cc2022-12-19 17:37:48 +08009611 ensureRunningOnConnectivityServiceThread();
9612 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9613 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9614 .getUserHandles(true /* excludeDying */);
9615 if (users.isEmpty()) {
9616 throw new IllegalStateException("No user is available");
9617 }
9618
9619 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9620 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9621 for (final UserHandle user : users) {
9622 final ArraySet<UidRange> restrictedUidRanges =
9623 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9624 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9625 UidRange.createForUser(user), restrictedUidRanges));
9626 }
9627
9628 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9629 configs.add(new NativeUidRangeConfig(
9630 nai.network.netId, rangesParcel, 0 /* subPriority */));
9631 }
9632
9633 // The netd API replaces the previous configs with the current configs.
9634 // Thus, for network disconnection or preference removal, no need to
9635 // unset previous config. Instead, collecting all currently needed
9636 // configs and issue to netd.
9637 try {
9638 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9639 } catch (ServiceSpecificException e) {
9640 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009641 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009642 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009643 // Netd died. This will cause a runtime restart anyway.
9644 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009645 }
9646 }
9647
James Mattisd31bdfa2020-12-23 16:37:26 -08009648 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9649 try {
9650 if (null != newDefaultNetwork) {
9651 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9652 } else {
9653 mNetd.networkClearDefault();
9654 }
9655 } catch (RemoteException | ServiceSpecificException e) {
9656 loge("Exception setting default network :" + e);
9657 }
Tommy Webb34f81dc2023-02-20 14:10:55 -05009658 updateUidDefaultNetworkRules(newDefaultNetwork);
James Mattisd31bdfa2020-12-23 16:37:26 -08009659 }
9660
Chalard Jean05cbe972019-12-09 11:50:38 +09009661 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009662 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009663 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009664 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009665 processNewlySatisfiedListenRequests(nai);
9666 }
9667
9668 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009669 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9670 if (nri.isMultilayerRequest()) {
9671 continue;
9672 }
9673 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009674 if (!nr.isListen()) continue;
9675 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009676 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009677 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9678 }
9679 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009680 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009681
Chalard Jeancd397a22019-11-22 22:33:33 +09009682 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009683 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9684 if (nri.isMultilayerRequest()) {
9685 continue;
9686 }
9687 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009688 if (!nr.isListen()) continue;
9689 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9690 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009691 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009692 }
9693 }
9694 }
9695
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009696 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009697 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009698 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009699 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009700 @Nullable public final NetworkRequest mOldNetworkRequest;
9701 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009702 @Nullable public final NetworkAgentInfo mOldNetwork;
9703 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009704 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009705 @Nullable final NetworkRequest oldNetworkRequest,
9706 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009707 @Nullable final NetworkAgentInfo oldNetwork,
9708 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009709 mNetworkRequestInfo = networkRequestInfo;
9710 mOldNetworkRequest = oldNetworkRequest;
9711 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009712 mOldNetwork = oldNetwork;
9713 mNewNetwork = newNetwork;
9714 }
Chalard Jean49707572019-12-10 21:07:02 +09009715
9716 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009717 final NetworkRequest requestToShow = null != mNewNetworkRequest
9718 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9719 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009720 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9721 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009722 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009723 }
9724
Chalard Jean46a62372019-12-10 21:25:24 +09009725 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009726
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009727 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009728 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009729 }
9730
9731 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009732 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009733 // The code is never supposed to add two reassignments of the same request. Make
9734 // sure this stays true, but without imposing this expensive check on all
9735 // reassignments on all user devices.
9736 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009737 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009738 throw new IllegalStateException("Trying to reassign ["
9739 + reassignment + "] but already have ["
9740 + existing + "]");
9741 }
9742 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009743 }
Chalard Jean46a62372019-12-10 21:25:24 +09009744 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009745 }
9746
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009747 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009748 // the passed request.
9749 @Nullable
9750 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009751 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009752 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009753 }
9754 return null;
9755 }
Chalard Jean49707572019-12-10 21:07:02 +09009756
9757 public String toString() {
9758 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9759 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009760 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009761 for (final RequestReassignment rr : getRequestReassignments()) {
9762 sj.add(rr.toString());
9763 }
9764 return sj.toString();
9765 }
9766
9767 public String debugString() {
9768 final StringBuilder sb = new StringBuilder();
9769 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009770 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009771 for (final RequestReassignment rr : getRequestReassignments()) {
9772 sb.append("\n ").append(rr);
9773 }
9774 return sb.append("\n").toString();
9775 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009776 }
9777
Chalard Jean24344d72019-12-04 13:32:31 +09009778 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009779 @Nullable final NetworkRequest previousRequest,
9780 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009781 @Nullable final NetworkAgentInfo previousSatisfier,
9782 @Nullable final NetworkAgentInfo newSatisfier,
9783 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009784 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009785 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009786 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009787 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009788 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09009789 }
James Mattisa076c532020-12-02 14:12:41 -08009790 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009791 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009792 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009793 // If this network switch can't be supported gracefully, the request is not
9794 // lingered. This allows letting go of the network sooner to reclaim some
9795 // performance on the new network, since the radio can't do both at the same
9796 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009797 //
9798 // Also don't linger the request if the old network has been destroyed.
9799 // A destroyed network does not provide actual network connectivity, so
9800 // lingering it is not useful. In particular this ensures that a destroyed
9801 // network is outscored by its replacement,
9802 // then it is torn down immediately instead of being lingered, and any apps that
9803 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009804 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9805 }
Chalard Jean24344d72019-12-04 13:32:31 +09009806 } else {
9807 if (VDBG || DDBG) log(" accepting network in place of null");
9808 }
junyulai0ac374f2020-12-14 18:41:52 +08009809
9810 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9811 // and immediately satisfies a request then remove the timer. This will happen for
9812 // all networks except in the case of an underlying network for a VCN.
9813 if (newSatisfier.isNascent()) {
9814 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009815 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009816 }
9817
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009818 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009819 newSatisfier.unlingerRequest(newRequest.requestId);
9820 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009821 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009822 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009823 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009824 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009825 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009826 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009827 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009828 }
James Mattisa076c532020-12-02 14:12:41 -08009829 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009830 }
James Mattisa076c532020-12-02 14:12:41 -08009831 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009832 }
9833
James Mattisa076c532020-12-02 14:12:41 -08009834 /**
9835 * This function is triggered when something can affect what network should satisfy what
9836 * request, and it computes the network reassignment from the passed collection of requests to
9837 * network match to the one that the system should now have. That data is encoded in an
9838 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9839 * satisfier.
9840 *
9841 * After the reassignment is computed, it is applied to the state objects.
9842 *
9843 * @param networkRequests the nri objects to evaluate for possible network reassignment
9844 * @return NetworkReassignment listing of proposed network assignment changes
9845 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009846 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009847 private NetworkReassignment computeNetworkReassignment(
9848 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009849 final NetworkReassignment changes = new NetworkReassignment();
9850
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009851 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009852 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009853 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009854 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009855 }
Chalard Jean857a1712019-12-10 21:08:07 +09009856
James Mattisa076c532020-12-02 14:12:41 -08009857 for (final NetworkRequestInfo nri : networkRequests) {
9858 // Non-multilayer listen requests can be ignored.
9859 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9860 continue;
9861 }
9862 NetworkAgentInfo bestNetwork = null;
9863 NetworkRequest bestRequest = null;
9864 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009865 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009866 // Stop evaluating as the highest possible priority request is satisfied.
9867 if (null != bestNetwork) {
9868 bestRequest = req;
9869 break;
9870 }
9871 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009872 if (null == bestNetwork && isDefaultBlocked(nri)) {
9873 // Remove default networking if disallowed for managed default requests.
9874 bestNetwork = mNoServiceNetwork;
9875 }
9876 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009877 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009878 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009879 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009880 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009881 }
9882 return changes;
9883 }
9884
James Mattisa076c532020-12-02 14:12:41 -08009885 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9886 return new HashSet<>(mNetworkRequests.values());
9887 }
9888
Paul Jensenc88b39b2015-06-16 14:27:36 -04009889 /**
James Mattisa076c532020-12-02 14:12:41 -08009890 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009891 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009892 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009893 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009894 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9895 }
9896
9897 /**
9898 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9899 * being disconnected.
9900 */
9901 private void rematchNetworksAndRequests(
9902 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9903 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009904 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009905 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009906 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09009907 final long computed = SystemClock.elapsedRealtime();
9908 applyNetworkReassignment(changes, start);
9909 final long applied = SystemClock.elapsedRealtime();
9910 issueNetworkNeeds();
9911 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09009912 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009913 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
9914 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009915 log(changes.debugString());
9916 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009917 // Shorter form, only one line of log
9918 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
9919 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009920 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09009921 }
Chalard Jean64520dc2019-12-04 19:55:32 +09009922
Chalard Jeand7f762d2019-12-10 19:01:29 +09009923 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09009924 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009925 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09009926
9927 // Since most of the time there are only 0 or 1 background networks, it would probably
9928 // be more efficient to just use an ArrayList here. TODO : measure performance
9929 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
9930 for (final NetworkAgentInfo nai : nais) {
9931 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
9932 }
9933
Chalard Jeand7f762d2019-12-10 19:01:29 +09009934 // First, update the lists of satisfied requests in the network agents. This is necessary
9935 // because some code later depends on this state to be correct, most prominently computing
9936 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09009937 for (final NetworkReassignment.RequestReassignment event :
9938 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009939 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
9940 event.mOldNetworkRequest, event.mNewNetworkRequest,
9941 event.mOldNetwork, event.mNewNetwork,
9942 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09009943 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009944
James Mattise3ef1912020-12-20 11:09:58 -08009945 // Process default network changes if applicable.
9946 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009947
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009948 // Notify requested networks are available after the default net is switched, but
9949 // before LegacyTypeTracker sends legacy broadcasts
9950 for (final NetworkReassignment.RequestReassignment event :
9951 changes.getRequestReassignments()) {
9952 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009953 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009954 } else {
James Mattisa076c532020-12-02 14:12:41 -08009955 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009956 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009957 }
9958 }
9959
junyulai0ac374f2020-12-14 18:41:52 +08009960 // Update the inactivity state before processing listen callbacks, because the background
9961 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009962 // just yet though, because they have to be sent after the listens are processed to keep
9963 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08009964 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09009965 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08009966 // Rematching may have altered the inactivity state of some networks, so update all
9967 // inactivity timers. updateInactivityState reads the state from the network agent
9968 // and does nothing if the state has not changed : the source of truth is controlled
9969 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
9970 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08009971 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08009972 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009973 }
9974 }
9975
Chalard Jeanb10ab412019-12-11 14:12:30 +09009976 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009977 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009978 // Process listen requests and update capabilities if the background state has
9979 // changed for this network. For consistency with previous behavior, send onLost
9980 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09009981 processNewlyLostListenRequests(nai);
9982 if (oldBackground != nai.isBackgroundNetwork()) {
9983 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009984 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09009985 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009986 }
9987
junyulai0ac374f2020-12-14 18:41:52 +08009988 for (final NetworkAgentInfo nai : inactiveNetworks) {
9989 // For nascent networks, if connecting with no foreground request, skip broadcasting
9990 // LOSING for backward compatibility. This is typical when mobile data connected while
9991 // wifi connected with mobile data always-on enabled.
9992 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009993 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009994 }
9995
James Mattise3ef1912020-12-20 11:09:58 -08009996 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09009997
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009998 // Tear down all unneeded networks.
Jean Chalard01a7d322023-06-27 08:54:23 +00009999 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010000 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +080010001 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010002 // This network has active linger timers and no requests, but is not
10003 // lingering. Linger it.
10004 //
10005 // One way (the only way?) this can happen if this network is unvalidated
10006 // and became unneeded due to another network improving its score to the
10007 // point where this network will no longer be able to satisfy any requests
10008 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +080010009 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010010 notifyNetworkLosing(nai, now);
10011 }
Chalard Jean0a8afda2019-11-07 19:05:18 +090010012 } else {
Chalard Jean49707572019-12-10 21:07:02 +090010013 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +090010014 teardownUnneededNetwork(nai);
10015 }
10016 }
Paul Jensen05e85ee2014-09-11 11:00:39 -040010017 }
10018 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010019
Chalard Jean62edfd82019-12-02 18:39:29 +090010020 /**
10021 * Apply a change in background state resulting from rematching networks with requests.
10022 *
10023 * During rematch, a network may change background states by starting to satisfy or stopping
10024 * to satisfy a foreground request. Listens don't count for this. When a network changes
10025 * background states, its capabilities need to be updated and callbacks fired for the
10026 * capability change.
10027 *
10028 * @param nai The network that changed background states
10029 */
10030 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
10031 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
10032 if (Objects.equals(nai.networkCapabilities, newNc)) return;
10033 updateNetworkPermissions(nai, newNc);
10034 nai.getAndSetNetworkCapabilities(newNc);
10035 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
10036 }
10037
Chalard Jeanf0344532019-11-19 19:23:38 +090010038 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -080010039 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010040 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +090010041 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
10042 changes.getReassignment(mDefaultRequest);
10043 final NetworkAgentInfo oldDefaultNetwork =
10044 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
10045 final NetworkAgentInfo newDefaultNetwork =
10046 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -080010047
Chalard Jean5b409c72021-02-04 13:12:59 +090010048 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010049 // Maintain the illusion : since the legacy API only understands one network at a time,
10050 // if the default network changed, apps should see a disconnected broadcast for the
10051 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +090010052 if (oldDefaultNetwork != null) {
10053 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
10054 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010055 }
Chalard Jean5b409c72021-02-04 13:12:59 +090010056 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010057 // The new default network can be newly null if and only if the old default
10058 // network doesn't satisfy the default request any more because it lost a
10059 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +090010060 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -080010061 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +090010062 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010063 }
10064 }
10065
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010066 // Now that all the callbacks have been sent, send the legacy network broadcasts
10067 // as needed. This is necessary so that legacy requests correctly bind dns
10068 // requests to this network. The legacy users are listening for this broadcast
10069 // and will generally do a dns request so they can ensureRouteToHost and if
10070 // they do that before the callbacks happen they'll use the default network.
10071 //
10072 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
10073 // callbacks, but if apps can receive the broadcast before the callback, they still might
10074 // have an inconsistent view of networking.
10075 //
10076 // This *does* introduce a race where if the user uses the new api
10077 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
10078 // they may get old info. Reverse this after the old startUsing api is removed.
10079 // This is on top of the multiple intent sequencing referenced in the todo above.
10080 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +090010081 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010082 addNetworkToLegacyTypeTracker(nai);
10083 }
The Android Open Source Project28527d22009-03-03 19:31:44 -080010084 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010085 }
10086
Chalard Jean0354d8c2021-01-12 10:58:56 +090010087 private void issueNetworkNeeds() {
10088 ensureRunningOnConnectivityServiceThread();
10089 for (final NetworkOfferInfo noi : mNetworkOffers) {
10090 issueNetworkNeeds(noi);
10091 }
10092 }
10093
10094 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
10095 ensureRunningOnConnectivityServiceThread();
10096 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10097 informOffer(nri, noi.offer, mNetworkRanker);
10098 }
10099 }
10100
10101 /**
10102 * Inform a NetworkOffer about any new situation of a request.
10103 *
10104 * This function handles updates to offers. A number of events may happen that require
10105 * updating the registrant for this offer about the situation :
10106 * • The offer itself was updated. This may lead the offer to no longer being able
10107 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
10108 * or conversely being strengthened enough to beat the satisfier (and therefore
10109 * start being needed)
10110 * • The network satisfying a request changed (including cases where the request
10111 * starts or stops being satisfied). The new network may be a stronger or weaker
10112 * match than the old one, possibly affecting whether the offer is needed.
10113 * • The network satisfying a request updated their score. This may lead the offer
10114 * to no longer be able to beat it if the current satisfier got better, or
10115 * conversely start being a good choice if the current satisfier got weaker.
10116 *
10117 * @param nri The request
10118 * @param offer The offer. This may be an updated offer.
10119 */
10120 private static void informOffer(@NonNull NetworkRequestInfo nri,
10121 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
10122 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
10123 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +090010124
10125 // Multi-layer requests have a currently active request, the one being satisfied.
10126 // Since the system will try to bring up a better network than is currently satisfying
10127 // the request, NetworkProviders need to be told the offers matching the requests *above*
10128 // the currently satisfied one are needed, that the ones *below* the satisfied one are
10129 // not needed, and the offer is needed for the active request iff the offer can beat
10130 // the satisfier.
10131 // For non-multilayer requests, the logic above gracefully degenerates to only the
10132 // last case.
10133 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
10134 // providers that the offer is needed for this request, until the active request is found.
10135 // In a second phase, deal with the currently active request. In a third phase, inform
10136 // the providers that offer is unneeded for the remaining requests.
10137
10138 // First phase : inform providers of all requests above the active request.
10139 int i;
10140 for (i = 0; nri.mRequests.size() > i; ++i) {
10141 final NetworkRequest request = nri.mRequests.get(i);
10142 if (activeRequest == request) break; // Found the active request : go to phase 2
10143 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10144 // Since this request is higher-priority than the one currently satisfied, if the
10145 // offer can satisfy it, the provider should try and bring up the network for sure ;
10146 // no need to even ask the ranker – an offer that can satisfy is always better than
10147 // no network. Hence tell the provider so unless it already knew.
10148 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
10149 offer.onNetworkNeeded(request);
10150 }
10151 }
10152
10153 // Second phase : deal with the active request (if any)
10154 if (null != activeRequest && activeRequest.isRequest()) {
10155 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000010156 // If an offer can satisfy the request, it is considered needed if it is currently
10157 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090010158 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000010159 && satisfier.factorySerialNumber == offer.providerId
10160 && activeRequest.canBeSatisfiedBy(offer.caps);
10161 final boolean newNeeded = currentlyServing
10162 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010163 if (newNeeded != oldNeeded) {
10164 if (newNeeded) {
10165 offer.onNetworkNeeded(activeRequest);
10166 } else {
10167 // The offer used to be able to beat the satisfier. Now it can't.
10168 offer.onNetworkUnneeded(activeRequest);
10169 }
10170 }
10171 }
10172
10173 // Third phase : inform the providers that the offer isn't needed for any request
10174 // below the active one.
10175 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10176 final NetworkRequest request = nri.mRequests.get(i);
10177 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10178 // Since this request is lower-priority than the one currently satisfied, if the
10179 // offer can satisfy it, the provider should not try and bring up the network.
10180 // Hence tell the provider so unless it already knew.
10181 if (offer.neededFor(request)) {
10182 offer.onNetworkUnneeded(request);
10183 }
10184 }
10185 }
10186
Chalard Jean61c79252019-11-07 23:07:32 +090010187 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10188 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10189 NetworkRequest nr = nai.requestAt(i);
10190 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10191 // legacy type tracker filters out repeat adds
10192 mLegacyTypeTracker.add(nr.legacyType, nai);
10193 }
10194 }
10195
10196 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010197 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010198 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10199 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10200 if (nai.isVPN()) {
10201 mLegacyTypeTracker.add(TYPE_VPN, nai);
10202 }
10203 }
10204
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010205 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010206 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010207 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010208 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010209 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010210 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010211
Chalard Jean254bd162022-08-25 13:04:51 +090010212 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010213 // Don't repeat publish.
10214 if (newInetCondition == mDefaultInetConditionPublished) return;
10215
10216 mDefaultInetConditionPublished = newInetCondition;
10217 sendInetConditionBroadcast(nai.networkInfo);
10218 }
10219
Chalard Jeand61375d2020-01-14 22:46:36 +090010220 @NonNull
10221 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10222 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010223 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010224 final boolean suspended =
10225 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10226 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10227 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10228 // state. This is because the network could have been suspended before connecting,
10229 // or it could be disconnecting while being suspended, and in both these cases
10230 // the state should not be overridden. Note that the only detailed state that
10231 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10232 // worry about multiple different substates of CONNECTED.
10233 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10234 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010235 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10236 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10237 // network agent is created, then goes to suspended, then goes out of suspended without
10238 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010239 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010240 ? NetworkInfo.DetailedState.CONNECTED
10241 : NetworkInfo.DetailedState.CONNECTING,
10242 info.getReason(),
10243 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010244 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010245 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010246 return newInfo;
10247 }
10248
10249 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10250 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10251
Erik Kline99f301b2017-02-15 19:59:17 +090010252 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010253 NetworkInfo oldInfo = null;
10254 synchronized (networkAgent) {
10255 oldInfo = networkAgent.networkInfo;
10256 networkAgent.networkInfo = newInfo;
10257 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010258
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010259 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010260 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10261 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010262 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010263
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +090010264 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010265 // A network that has just connected has zero requests and is thus a foreground network.
10266 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10267
Luke Huangfdd11f82019-04-09 18:41:49 +080010268 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +090010269
10270 networkAgent.setCreated();
10271
10272 // If the network is created immediately on register, then apply the LinkProperties now.
10273 // Otherwise, this is done further down when the network goes into connected state.
10274 // Applying the LinkProperties means that the network is ready to carry traffic -
10275 // interfaces and routing rules have been added, DNS servers programmed, etc.
10276 // For VPNs, this must be done before the capabilities are updated, because as soon as
10277 // that happens, UIDs are routed to the network.
10278 if (shouldCreateNetworksImmediately()) {
10279 applyInitialLinkProperties(networkAgent);
10280 }
10281
10282 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10283 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010284 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010285 // Initialize the network's capabilities to their starting values according to the
10286 // underlying networks. This ensures that the capabilities are correct before
10287 // anything happens to the network.
10288 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010289 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010290 networkAgent.onNetworkCreated();
Tommy Webb34f81dc2023-02-20 14:10:55 -050010291 updateDisallowedUidsForNetwork(networkAgent);
Chalard Jeande665262022-02-25 16:12:12 +090010292 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010293 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010294 }
10295
Chalard Jean254bd162022-08-25 13:04:51 +090010296 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10297 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010298
lucaslin45e639b2019-04-03 17:09:28 +080010299 // NetworkCapabilities need to be set before sending the private DNS config to
10300 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010301 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10302
Erik Kline9a62f012018-03-21 07:18:33 -070010303 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +090010304 if (!shouldCreateNetworksImmediately()) {
10305 applyInitialLinkProperties(networkAgent);
10306 } else {
10307 // The network was created when the agent registered, and the LinkProperties are
10308 // already up-to-date. However, updateLinkProperties also makes some changes only
10309 // when the network connects. Apply those changes here. On T and below these are
10310 // handled by the applyInitialLinkProperties call just above.
10311 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10312 // If something depends on both LinkProperties and connected state, it should be in
10313 // this method as well.
10314 networkAgent.clatd.update();
10315 updateProxy(networkAgent.linkProperties, null);
10316 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010317
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010318 // If a rate limit has been configured and is applicable to this network (network
10319 // provides internet connectivity), apply it. The tc police filter cannot be attached
10320 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
10321 // updateInterfaces -> INetd#networkAddInterface.
10322 // Note: in case of a system server crash, the NetworkController constructor in netd
10323 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10324 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10325 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10326 mIngressRateLimit);
10327 }
10328
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010329 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10330 // command must be sent after updating LinkProperties to maximize chances of
10331 // NetworkMonitor seeing the correct LinkProperties when starting.
10332 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010333 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010334 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010335 }
Chalard Jeand4900722022-02-06 12:25:38 +090010336 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10337 params.networkAgentConfig = networkAgent.networkAgentConfig;
10338 params.networkCapabilities = networkAgent.networkCapabilities;
10339 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10340 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010341 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10342 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10343 // call that would cause a Log.wtf to be emitted from the system_server process, and
10344 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10345 // process to check the interface version, just use an SDK check. NetworkStack will
10346 // always be new enough when running on T+.
Chalard Jean03552c42023-05-29 17:02:43 +090010347 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010348 networkAgent.networkMonitor().notifyNetworkConnected(params);
10349 } else {
10350 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10351 params.networkCapabilities);
10352 }
Chalard Jean3f0ff5b2023-06-05 19:26:17 +090010353 final long evaluationDelay;
10354 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10355 // If the network is anything other than pure wifi, use the default timeout.
10356 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10357 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10358 // If the network is explicitly selected, use the default timeout because it's
10359 // shorter and the user is likely staring at the screen expecting it to validate
10360 // right away.
10361 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10362 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10363 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10364 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10365 } else {
10366 // It's wifi, automatically connected, and bad wifi is preferred : use the
10367 // longer timeout to avoid the device switching to captive portals with bad
10368 // signal or very slow response.
10369 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10370 }
10371 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010372
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010373 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10374 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10375 // capabilities, so it only needs to be done once on initial connect, not every time the
10376 // network's capabilities change. Note that we do this before rematching the network,
10377 // so we could decide to tear it down immediately afterwards. That's fine though - on
10378 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10379 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010380 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010381
junyulai0ac374f2020-12-14 18:41:52 +080010382 // Before first rematching networks, put an inactivity timer without any request, this
10383 // allows {@code updateInactivityState} to update the state accordingly and prevent
10384 // tearing down for any {@code unneeded} evaluation in this period.
10385 // Note that the timer will not be rescheduled since the expiry time is
10386 // fixed after connection regardless of the network satisfying other requests or not.
10387 // But it will be removed as soon as the network satisfies a request for the first time.
10388 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10389 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010390 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010391
Paul Jensen05e85ee2014-09-11 11:00:39 -040010392 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010393 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010394
10395 // This has to happen after matching the requests, because callbacks are just requests.
10396 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010397 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard01a7d322023-06-27 08:54:23 +000010398 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010399 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010400 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010401 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010402 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010403 if (networkAgent.isVPN()) {
10404 // As the active or bound network changes for apps, broadcast the default proxy, as
10405 // apps may need to update their proxy data. This is called after disconnecting from
10406 // VPN to make sure we do not broadcast the old proxy data.
10407 // TODO(b/122649188): send the broadcast only to VPN users.
10408 mProxyTracker.sendProxyBroadcast();
10409 }
Chalard Jean254bd162022-08-25 13:04:51 +090010410 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10411 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010412 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010413 }
10414 }
10415
Chalard Jean28018572020-12-21 18:36:52 +090010416 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010417 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10418 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010419 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010420 }
10421
Erik Kline99f301b2017-02-15 19:59:17 +090010422 // Notify only this one new request of the current state. Transfer all the
10423 // current state by calling NetworkCapabilities and LinkProperties callbacks
10424 // so that callers can be guaranteed to have as close to atomicity in state
10425 // transfer as can be supported by this current API.
10426 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010427 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010428 if (nri.mPendingIntent != null) {
10429 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10430 // Attempt no subsequent state pushes where intents are involved.
10431 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010432 }
Erik Kline99f301b2017-02-15 19:59:17 +090010433
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010434 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010435 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010436 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10437 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10438 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010439 }
10440
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010441 // Notify the requests on this NAI that the network is now lingered.
10442 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010443 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010444 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10445 }
10446
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010447 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10448 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10449 return vpnBlocked
10450 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10451 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10452 }
10453
10454 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10455 if (blockedReasons == BLOCKED_REASON_NONE) {
10456 mUidBlockedReasons.delete(uid);
10457 } else {
10458 mUidBlockedReasons.put(uid, blockedReasons);
10459 }
10460 }
10461
junyulaif2c67e42018-08-07 19:50:45 +080010462 /**
10463 * Notify of the blocked state apps with a registered callback matching a given NAI.
10464 *
10465 * Unlike other callbacks, blocked status is different between each individual uid. So for
10466 * any given nai, all requests need to be considered according to the uid who filed it.
10467 *
10468 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010469 * @param oldMetered True if the previous network capabilities were metered.
10470 * @param newMetered True if the current network capabilities are metered.
10471 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10472 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010473 */
10474 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010475 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10476 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010477
10478 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10479 NetworkRequest nr = nai.requestAt(i);
10480 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010481
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010482 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10483 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10484 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010485 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010486 : oldVpnBlocked;
10487
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010488 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10489 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10490 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010491 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010492 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010493 }
10494 }
10495 }
10496
10497 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010498 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010499 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010500 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010501 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010502 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010503 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010504 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010505 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010506
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010507 final int oldBlockedState = getBlockedState(
10508 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
10509 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
10510 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080010511 continue;
junyulaif2c67e42018-08-07 19:50:45 +080010512 }
junyulaif2c67e42018-08-07 19:50:45 +080010513 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10514 NetworkRequest nr = nai.requestAt(i);
10515 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010516 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010517 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10518 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010519 }
10520 }
10521 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010522 }
10523
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010524 @VisibleForTesting
10525 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010526 // The NetworkInfo we actually send out has no bearing on the real
10527 // state of affairs. For example, if the default connection is mobile,
10528 // and a request for HIPRI has just gone away, we need to pretend that
10529 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10530 // the state to DISCONNECTED, even though the network is of type MOBILE
10531 // and is still connected.
10532 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10533 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010534 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010535 if (state != DetailedState.DISCONNECTED) {
10536 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010537 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010538 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010539 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010540 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10541 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10542 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10543 if (info.isFailover()) {
10544 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10545 nai.networkInfo.setFailover(false);
10546 }
10547 if (info.getReason() != null) {
10548 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10549 }
10550 if (info.getExtraInfo() != null) {
10551 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10552 }
10553 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010554 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010555 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010556 if (newDefaultAgent != null) {
10557 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10558 newDefaultAgent.networkInfo);
10559 } else {
10560 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10561 }
10562 }
10563 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10564 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010565 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010566 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010567 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010568 }
10569 }
10570 }
10571
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010572 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010573 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010574 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010575 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010576 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010577 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10578 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010579 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10580 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010581 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010582 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010583 } else {
10584 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10585 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010586 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010587 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010588
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010589 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10590 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10591 }
10592
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010593 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010594 * Returns the list of all interfaces that could be used by network traffic that does not
10595 * explicitly specify a network. This includes the default network, but also all VPNs that are
10596 * currently connected.
10597 *
10598 * Must be called on the handler thread.
10599 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010600 @NonNull
10601 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010602 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010603 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010604 final Set<Integer> activeNetIds = new ArraySet<>();
10605 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10606 if (nri.isBeingSatisfied()) {
10607 activeNetIds.add(nri.getSatisfier().network().netId);
10608 }
10609 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010610 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010611 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010612 defaultNetworks.add(nai.network);
10613 }
10614 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010615 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010616 }
10617
10618 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010619 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10620 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010621 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010622 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010623 ensureRunningOnConnectivityServiceThread();
10624 String activeIface = null;
10625 LinkProperties activeLinkProperties = getActiveLinkProperties();
10626 if (activeLinkProperties != null) {
10627 activeIface = activeLinkProperties.getInterfaceName();
10628 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010629
junyulai2050bed2021-01-23 09:46:34 +080010630 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010631 try {
junyulaide41fc22021-01-22 22:46:01 +080010632 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010633 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010634 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10635 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010636 } catch (Exception ignored) {
10637 }
10638 }
10639
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010640 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010641 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010642 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010643 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010644 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010645
10646 if (!TextUtils.isEmpty(settingUrl)) {
10647 return settingUrl;
10648 }
10649
10650 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010651 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010652 if (!TextUtils.isEmpty(settingUrl)) {
10653 return settingUrl;
10654 }
10655
10656 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010657 }
10658
10659 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010660 public void startNattKeepalive(Network network, int intervalSeconds,
10661 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010662 enforceKeepalivePermission();
10663 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010664 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000010665 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
10666 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000010667 // false and set the underpinned network to null because there is no way and no
10668 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10669 // deprecated method.
10670 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010671 }
10672
10673 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010674 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010675 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010676 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010677 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010678 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010679 mKeepaliveTracker.startNattKeepalive(
10680 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010681 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10682 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010683 } finally {
10684 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10685 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010686 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10687 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010688 }
10689 }
junyulaid05a1922019-01-15 11:32:44 +080010690 }
10691
10692 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010693 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010694 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010695 try {
10696 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010697 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010698 mKeepaliveTracker.startTcpKeepalive(
10699 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10700 } finally {
10701 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10702 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010703 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10704 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010705 }
10706 }
junyulai0835a1e2019-01-08 20:04:33 +080010707 }
10708
10709 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010710 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010711 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010712 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10713 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010714 }
10715
10716 @Override
Remi NGUYEN VAN6ca02962023-02-20 20:10:09 +090010717 public int[] getSupportedKeepalives() {
10718 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
10719 // Backwards compatibility with CTS 13
10720 android.Manifest.permission.QUERY_ALL_PACKAGES);
10721
10722 return BinderUtils.withCleanCallingIdentity(() ->
10723 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
10724 }
10725
10726 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010727 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010728 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010729
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010730 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010731 final long token = Binder.clearCallingIdentity();
10732 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010733 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10734 UserHandle.getUserHandleForUid(uid))) {
10735 return;
10736 }
10737
Heemin Seogdb8489d2019-06-12 09:21:44 -070010738 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10739 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010740
10741 // Turn airplane mode off
10742 setAirplaneMode(false);
10743
10744 // restore private DNS settings to default mode (opportunistic)
10745 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10746 UserHandle.getUserHandleForUid(uid))) {
10747 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10748 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10749 }
10750
10751 Settings.Global.putString(mContext.getContentResolver(),
10752 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010753 } finally {
10754 Binder.restoreCallingIdentity(token);
10755 }
Stuart Scottd5463642015-04-02 18:00:02 -070010756 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010757
Ricky Wai7097cc92018-01-23 04:09:45 +000010758 @Override
10759 public byte[] getNetworkWatchlistConfigHash() {
10760 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10761 if (nwm == null) {
10762 loge("Unable to get NetworkWatchlistManager");
10763 return null;
10764 }
10765 // Redirect it to network watchlist service to access watchlist file and calculate hash.
10766 return nwm.getWatchlistConfigHash();
10767 }
10768
Hugo Benichibe0c7652016-05-31 16:28:06 +090010769 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090010770 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080010771 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090010772 }
Hugo Benichif4210292017-04-21 15:07:12 +090010773
10774 private static boolean toBool(int encodedBoolean) {
10775 return encodedBoolean != 0; // Only 0 means false.
10776 }
10777
10778 private static int encodeBool(boolean b) {
10779 return b ? 1 : 0;
10780 }
mswest4632928412018-03-12 10:34:34 -070010781
10782 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010783 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
10784 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
10785 @NonNull String[] args) {
10786 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
10787 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070010788 }
10789
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010790 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070010791 @Override
10792 public int onCommand(String cmd) {
10793 if (cmd == null) {
10794 return handleDefaultCommands(cmd);
10795 }
10796 final PrintWriter pw = getOutPrintWriter();
10797 try {
10798 switch (cmd) {
10799 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010800 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
10801 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070010802 final String action = getNextArg();
10803 if ("enable".equals(action)) {
10804 setAirplaneMode(true);
10805 return 0;
10806 } else if ("disable".equals(action)) {
10807 setAirplaneMode(false);
10808 return 0;
10809 } else if (action == null) {
10810 final ContentResolver cr = mContext.getContentResolver();
10811 final int enabled = Settings.Global.getInt(cr,
10812 Settings.Global.AIRPLANE_MODE_ON);
10813 pw.println(enabled == 0 ? "disabled" : "enabled");
10814 return 0;
10815 } else {
10816 onHelp();
10817 return -1;
10818 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010819 case "reevaluate":
10820 // Usage : adb shell cmd connectivity reevaluate <netId>
10821 // If netId is omitted, then reevaluate the default network
10822 final String netId = getNextArg();
10823 final NetworkAgentInfo nai;
10824 if (null == netId) {
10825 // Note that the command is running on the wrong thread to call this,
10826 // so this could in principle return stale data. But it can't crash.
10827 nai = getDefaultNetwork();
10828 } else {
10829 // If netId can't be parsed, this throws NumberFormatException, which
10830 // is passed back to adb who prints it.
10831 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
10832 }
10833 if (null == nai) {
10834 pw.println("Unknown network (net ID not found or no default network)");
10835 return 0;
10836 }
10837 Log.d(TAG, "Reevaluating network " + nai.network);
10838 reportNetworkConnectivity(nai.network, !nai.isValidated());
10839 return 0;
mswest4632928412018-03-12 10:34:34 -070010840 default:
10841 return handleDefaultCommands(cmd);
10842 }
10843 } catch (Exception e) {
10844 pw.println(e);
10845 }
10846 return -1;
10847 }
10848
10849 @Override
10850 public void onHelp() {
10851 PrintWriter pw = getOutPrintWriter();
10852 pw.println("Connectivity service commands:");
10853 pw.println(" help");
10854 pw.println(" Print this help text.");
10855 pw.println(" airplane-mode [enable|disable]");
10856 pw.println(" Turn airplane mode on or off.");
10857 pw.println(" airplane-mode");
10858 pw.println(" Get airplane mode.");
10859 }
10860 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010861
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090010862 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010863 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
10864 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
10865 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080010866 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010867 }
10868
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090010869 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
10870 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090010871 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
10872 final TransportInfo newInfo = nc.getTransportInfo();
10873 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
10874 return;
10875 }
10876 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090010877 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090010878 }
10879 }
10880
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010881 /**
10882 * @param connectionInfo the connection to resolve.
10883 * @return {@code uid} if the connection is found and the app has permission to observe it
10884 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
10885 * connection is not found.
10886 */
10887 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010888 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
10889 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
10890 }
10891
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090010892 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010893 connectionInfo.local, connectionInfo.remote);
10894
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010895 if (uid == INVALID_UID) return uid; // Not found.
10896
10897 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
10898 // VPN, if any, that applies to the UID that owns the connection.
10899 if (checkNetworkStackPermission()) return uid;
10900
10901 final NetworkAgentInfo vpn = getVpnForUid(uid);
10902 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090010903 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010904 return INVALID_UID;
10905 }
10906
10907 return uid;
10908 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000010909
Benedict Wong493e04b2018-11-09 14:45:34 -080010910 /**
10911 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
10912 *
10913 * <p>The TestNetworkService must be run in the system server due to TUN creation.
10914 */
10915 @Override
10916 public IBinder startOrGetTestNetworkService() {
10917 synchronized (mTNSLock) {
10918 TestNetworkService.enforceTestNetworkPermissions(mContext);
10919
10920 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080010921 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080010922 }
10923
10924 return mTNS;
10925 }
10926 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080010927
Cody Kesting73708bf2019-12-18 10:57:50 -080010928 /**
10929 * Handler used for managing all Connectivity Diagnostics related functions.
10930 *
10931 * @see android.net.ConnectivityDiagnosticsManager
10932 *
10933 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
10934 */
10935 @VisibleForTesting
10936 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010937 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
10938
Cody Kesting73708bf2019-12-18 10:57:50 -080010939 /**
10940 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
10941 * android.net.ConnectivityDiagnosticsManager}.
10942 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
10943 * NetworkRequestInfo to be registered
10944 */
10945 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
10946
10947 /**
10948 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
10949 * android.net.ConnectivityDiagnosticsManager}.
10950 * obj = the IConnectivityDiagnosticsCallback to be unregistered
10951 * arg1 = the uid of the caller
10952 */
10953 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
10954
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010955 /**
10956 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010957 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010958 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
10959 * NetworkMonitor.
10960 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010961 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010962 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010963
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010964 /**
10965 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
10966 * been detected on the network.
10967 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
10968 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
10969 * arg2 = NetID.
10970 * data = PersistableBundle of extras passed from NetworkMonitor.
10971 */
10972 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
10973
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010974 /**
10975 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
10976 * the platform. This event will invoke {@link
10977 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
10978 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070010979 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010980 */
10981 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
10982
Cody Kesting73708bf2019-12-18 10:57:50 -080010983 private ConnectivityDiagnosticsHandler(Looper looper) {
10984 super(looper);
10985 }
10986
10987 @Override
10988 public void handleMessage(Message msg) {
10989 switch (msg.what) {
10990 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10991 handleRegisterConnectivityDiagnosticsCallback(
10992 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
10993 break;
10994 }
10995 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10996 handleUnregisterConnectivityDiagnosticsCallback(
10997 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
10998 break;
10999 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011000 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011001 final ConnectivityReportEvent reportEvent =
11002 (ConnectivityReportEvent) msg.obj;
11003
Aaron Huang959d3642021-01-21 15:47:41 +080011004 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011005 break;
11006 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011007 case EVENT_DATA_STALL_SUSPECTED: {
11008 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080011009 final Pair<Long, PersistableBundle> arg =
11010 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011011 if (nai == null) break;
11012
Aaron Huang959d3642021-01-21 15:47:41 +080011013 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011014 break;
11015 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011016 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070011017 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011018 break;
11019 }
11020 default: {
11021 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
11022 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011023 }
11024 }
11025 }
11026
11027 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
11028 @VisibleForTesting
11029 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
11030 @NonNull private final IConnectivityDiagnosticsCallback mCb;
11031 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011032 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011033
11034 @VisibleForTesting
11035 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011036 @NonNull IConnectivityDiagnosticsCallback cb,
11037 @NonNull NetworkRequestInfo nri,
11038 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011039 mCb = cb;
11040 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011041 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011042 }
11043
11044 @Override
11045 public void binderDied() {
11046 log("ConnectivityDiagnosticsCallback IBinder died.");
11047 unregisterConnectivityDiagnosticsCallback(mCb);
11048 }
11049 }
11050
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011051 /**
11052 * Class used for sending information from {@link
11053 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
11054 */
11055 private static class NetworkTestedResults {
11056 private final int mNetId;
11057 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011058 @Nullable private final String mRedirectUrl;
11059
11060 private NetworkTestedResults(
11061 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
11062 mNetId = netId;
11063 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011064 mRedirectUrl = redirectUrl;
11065 }
11066 }
11067
11068 /**
11069 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
11070 * ConnectivityDiagnosticsHandler}.
11071 */
11072 private static class ConnectivityReportEvent {
11073 private final long mTimestampMillis;
11074 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080011075 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011076
Aaron Huang959d3642021-01-21 15:47:41 +080011077 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
11078 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011079 mTimestampMillis = timestampMillis;
11080 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080011081 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011082 }
11083 }
11084
Cody Kestingf1120be2020-08-03 18:01:40 -070011085 /**
11086 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
11087 * ConnectivityDiagnosticsHandler}.
11088 */
11089 private static class ReportedNetworkConnectivityInfo {
11090 public final boolean hasConnectivity;
11091 public final boolean isNetworkRevalidating;
11092 public final int reporterUid;
11093 @NonNull public final NetworkAgentInfo nai;
11094
11095 private ReportedNetworkConnectivityInfo(
11096 boolean hasConnectivity,
11097 boolean isNetworkRevalidating,
11098 int reporterUid,
11099 @NonNull NetworkAgentInfo nai) {
11100 this.hasConnectivity = hasConnectivity;
11101 this.isNetworkRevalidating = isNetworkRevalidating;
11102 this.reporterUid = reporterUid;
11103 this.nai = nai;
11104 }
11105 }
11106
Cody Kesting73708bf2019-12-18 10:57:50 -080011107 private void handleRegisterConnectivityDiagnosticsCallback(
11108 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11109 ensureRunningOnConnectivityServiceThread();
11110
11111 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011112 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011113 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11114
James Mattis64b8b0f2020-11-24 17:40:49 -080011115 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11116 // confusing for these networks to change when an NRI is satisfied in another layer.
11117 if (nri.isMultilayerRequest()) {
11118 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11119 + "network requests.");
11120 }
11121
Cody Kesting73708bf2019-12-18 10:57:50 -080011122 // This means that the client registered the same callback multiple times. Do
11123 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011124 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011125 if (VDBG) log("Diagnostics callback is already registered");
11126
11127 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11128 // incremented when the NetworkRequestInfo is created as part of
11129 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011130 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011131 return;
11132 }
11133
Cody Kesting31f1ff62020-03-05 10:46:02 -080011134 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011135
11136 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011137 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011138 } catch (RemoteException e) {
11139 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011140 return;
11141 }
11142
11143 // Once registered, provide ConnectivityReports for matching Networks
11144 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11145 synchronized (mNetworkForNetId) {
11146 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11147 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011148 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11149 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011150 matchingNetworks.add(nai);
11151 }
11152 }
11153 }
11154 for (final NetworkAgentInfo nai : matchingNetworks) {
11155 final ConnectivityReport report = nai.getConnectivityReport();
11156 if (report == null) {
11157 continue;
11158 }
11159 if (!checkConnectivityDiagnosticsPermissions(
11160 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11161 continue;
11162 }
11163
11164 try {
11165 cb.onConnectivityReportAvailable(report);
11166 } catch (RemoteException e) {
11167 // Exception while sending the ConnectivityReport. Move on to the next network.
11168 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011169 }
11170 }
11171
11172 private void handleUnregisterConnectivityDiagnosticsCallback(
11173 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11174 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011175 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011176
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011177 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11178 mConnectivityDiagnosticsCallbacks.remove(iCb);
11179 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011180 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11181 return;
11182 }
11183
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011184 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011185
Cody Kesting70fa2b22020-12-02 12:16:56 -080011186 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11187 // (if the Binder died)
11188 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11189 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011190 return;
11191 }
11192
Cody Kesting46cb1672020-03-04 13:35:20 -080011193 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11194 // incremented when the NetworkRequestInfo is created as part of
11195 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011196 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011197
Cody Kesting31f1ff62020-03-05 10:46:02 -080011198 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011199 }
11200
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011201 private void handleNetworkTestedWithExtras(
11202 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11203 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011204 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011205 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011206 final ConnectivityReport report =
11207 new ConnectivityReport(
11208 reportEvent.mNai.network,
11209 reportEvent.mTimestampMillis,
11210 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011211 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011212 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011213 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011214
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011215 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011216 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011217 for (final IConnectivityDiagnosticsCallback cb : results) {
11218 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011219 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011220 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011221 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011222 }
11223 }
11224 }
11225
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011226 private void handleDataStallSuspected(
11227 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11228 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011229 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011230 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011231 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011232 new DataStallReport(
11233 nai.network,
11234 timestampMillis,
11235 detectionMethod,
11236 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011237 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011238 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011239 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011240 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011241 for (final IConnectivityDiagnosticsCallback cb : results) {
11242 try {
11243 cb.onDataStallSuspected(report);
11244 } catch (RemoteException ex) {
11245 loge("Error invoking onDataStallSuspected", ex);
11246 }
11247 }
11248 }
11249
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011250 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011251 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11252 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11253 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11254
11255 // If the Network is being re-validated as a result of this call to
11256 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11257 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011258 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011259 getMatchingPermissionedCallbacks(
11260 nai,
11261 reportedNetworkConnectivityInfo.isNetworkRevalidating
11262 ? Process.INVALID_UID
11263 : reportedNetworkConnectivityInfo.reporterUid);
11264
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011265 for (final IConnectivityDiagnosticsCallback cb : results) {
11266 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011267 cb.onNetworkConnectivityReported(
11268 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011269 } catch (RemoteException ex) {
11270 loge("Error invoking onNetworkConnectivityReported", ex);
11271 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011272
11273 // If the Network isn't re-validating, also provide the cached report. If there is no
11274 // cached report, the Network is still being validated and a report will be sent once
11275 // validation is complete. Note that networks which never undergo validation will still
11276 // have a cached ConnectivityReport with RESULT_SKIPPED.
11277 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11278 try {
11279 cb.onConnectivityReportAvailable(cachedReport);
11280 } catch (RemoteException ex) {
11281 loge("Error invoking onConnectivityReportAvailable", ex);
11282 }
11283 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011284 }
11285 }
11286
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011287 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011288 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11289 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011290 sanitized.setUids(null);
11291 sanitized.setAdministratorUids(new int[0]);
11292 sanitized.setOwnerUid(Process.INVALID_UID);
11293 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011294 }
11295
Cody Kestingf1120be2020-08-03 18:01:40 -070011296 /**
11297 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11298 *
11299 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11300 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011301 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011302 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011303 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011304 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011305 mConnectivityDiagnosticsCallbacks.entrySet()) {
11306 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11307 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011308
James Mattis64b8b0f2020-11-24 17:40:49 -080011309 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011310 if (!nai.satisfies(nri.mRequests.get(0))) {
11311 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011312 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011313
11314 // UID for this callback must either be:
11315 // - INVALID_UID (which sends callbacks to all UIDs), or
11316 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11317 // notified as a result)
11318 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11319 continue;
11320 }
11321
11322 if (!checkConnectivityDiagnosticsPermissions(
11323 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11324 continue;
11325 }
11326
11327 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011328 }
11329 return results;
11330 }
11331
Cody Kesting7474f672021-05-11 14:22:40 -070011332 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11333 @NonNull NetworkAgentInfo nai) {
11334 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11335 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11336 }
11337
Cody Kesting160ef392021-05-05 13:17:22 -070011338 private boolean hasLocationPermission(String packageName, int uid) {
11339 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11340 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11341 // call in a try-catch.
11342 try {
11343 if (!mLocationPermissionChecker.checkLocationPermission(
11344 packageName, null /* featureId */, uid, null /* message */)) {
11345 return false;
11346 }
11347 } catch (SecurityException e) {
11348 return false;
11349 }
11350
11351 return true;
11352 }
11353
11354 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11355 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011356 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011357 && virtual.networkCapabilities.getOwnerUid() == uid
11358 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11359 return true;
11360 }
11361 }
11362
11363 return false;
11364 }
11365
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011366 @VisibleForTesting
11367 boolean checkConnectivityDiagnosticsPermissions(
11368 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
11369 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
11370 return true;
11371 }
11372
Cody Kesting160ef392021-05-05 13:17:22 -070011373 // Administrator UIDs also contains the Owner UID
11374 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11375 if (!CollectionUtils.contains(administratorUids, callbackUid)
11376 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011377 return false;
11378 }
11379
Cody Kesting7474f672021-05-11 14:22:40 -070011380 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
11381 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011382 }
11383
Cody Kestingd199a9d2019-12-17 12:55:28 -080011384 @Override
11385 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011386 @NonNull IConnectivityDiagnosticsCallback callback,
11387 @NonNull NetworkRequest request,
11388 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011389 Objects.requireNonNull(callback, "callback must not be null");
11390 Objects.requireNonNull(request, "request must not be null");
11391 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
11392
Cody Kesting73708bf2019-12-18 10:57:50 -080011393 if (request.legacyType != TYPE_NONE) {
11394 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
11395 + " Please use NetworkCapabilities instead.");
11396 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011397 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080011398 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011399
11400 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
11401 // and administrator uids to be safe.
11402 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080011403 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011404
11405 final NetworkRequest requestWithId =
11406 new NetworkRequest(
11407 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
11408
11409 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
11410 //
11411 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
11412 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
11413 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011414 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080011415 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011416 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011417
11418 mConnectivityDiagnosticsHandler.sendMessage(
11419 mConnectivityDiagnosticsHandler.obtainMessage(
11420 ConnectivityDiagnosticsHandler
11421 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
11422 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011423 }
11424
11425 @Override
11426 public void unregisterConnectivityDiagnosticsCallback(
11427 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011428 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080011429 mConnectivityDiagnosticsHandler.sendMessage(
11430 mConnectivityDiagnosticsHandler.obtainMessage(
11431 ConnectivityDiagnosticsHandler
11432 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011433 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080011434 0,
11435 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011436 }
Cody Kestingf53a0752020-04-15 12:33:28 -070011437
Yan Yanfe96dde2022-12-05 23:00:01 +000011438 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
11439 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
11440 if (underlyingNetworks == null) return false;
11441
11442 for (Network network : underlyingNetworks) {
11443 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
11444 return true;
11445 }
11446 }
11447 return false;
11448 }
11449
Cody Kestingf53a0752020-04-15 12:33:28 -070011450 @Override
11451 public void simulateDataStall(int detectionMethod, long timestampMillis,
11452 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011453 Objects.requireNonNull(network, "network must not be null");
11454 Objects.requireNonNull(extras, "extras must not be null");
11455
paulhu3ffffe72021-09-16 10:15:22 +080011456 enforceAnyPermissionOf(mContext,
11457 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070011458 android.Manifest.permission.NETWORK_STACK);
11459 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011460 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
11461 throw new SecurityException(
11462 "Data Stall simulation is only possible for test networks or networks built on"
11463 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070011464 }
11465
11466 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011467 if (nai == null
11468 || (nai.creatorUid != mDeps.getCallingUid()
11469 && nai.creatorUid != Process.SYSTEM_UID)) {
11470 throw new SecurityException(
11471 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070011472 }
11473
Cody Kesting652e3ec2020-05-21 12:08:21 -070011474 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
11475 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
11476 // Data Stall information as a DataStallReportParcelable and passing to
11477 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
11478 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070011479 final DataStallReportParcelable p = new DataStallReportParcelable();
11480 p.timestampMillis = timestampMillis;
11481 p.detectionMethod = detectionMethod;
11482
11483 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
11484 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
11485 }
11486 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
11487 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
11488 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
11489 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
11490 }
11491
Serik Beketayevec8ad212020-12-07 22:43:07 -080011492 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070011493 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011494
lucaslin66f44212021-02-23 01:12:55 +080011495 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
11496 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080011497 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080011498 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080011499 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080011500 }
lucaslin37a16d92021-01-21 19:48:09 +080011501
11502 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011503 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080011504 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080011505 nai.clatd.interfaceLinkStateChanged(iface, up);
11506 }
11507 }
11508
11509 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011510 public void onInterfaceRemoved(@NonNull String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080011511 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080011512 nai.clatd.interfaceRemoved(iface);
11513 }
lucaslin66f44212021-02-23 01:12:55 +080011514 }
11515 }
11516
lucaslin1a8b4c62021-01-21 02:02:55 +080011517 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11518
11519 /**
11520 * Class used for updating network activity tracking with netd and notify network activity
11521 * changes.
11522 */
11523 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011524 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011525 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011526 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080011527 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11528 new RemoteCallbackList<>();
11529 // Indicate the current system default network activity is active or not.
11530 @GuardedBy("mActiveIdleTimers")
11531 private boolean mNetworkActive;
11532 @GuardedBy("mActiveIdleTimers")
Chalard Jean46bfbf02022-02-02 00:56:25 +090011533 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1193a5d2021-01-21 02:04:15 +080011534 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080011535
Chalard Jean46bfbf02022-02-02 00:56:25 +090011536 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080011537 public final int timeout;
11538 public final int transportType;
11539
11540 IdleTimerParams(int timeout, int transport) {
11541 this.timeout = timeout;
11542 this.transportType = transport;
11543 }
11544 }
11545
11546 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080011547 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011548 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080011549 mNetd = netd;
11550 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080011551 }
11552
lucaslin66f44212021-02-23 01:12:55 +080011553 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
11554 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
11555 synchronized (mActiveIdleTimers) {
11556 mNetworkActive = active;
11557 // If there are no idle timers, it means that system is not monitoring
11558 // activity, so the system default network for those default network
11559 // unspecified apps is always considered active.
11560 //
11561 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
11562 // any network activity change event. Whenever this event is received,
11563 // the mActiveIdleTimers should be always not empty. The legacy behavior
11564 // is no-op. Remove to refer to mNetworkActive only.
11565 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
11566 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
11567 }
11568 }
11569 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011570
lucaslin1193a5d2021-01-21 02:04:15 +080011571 // The network activity should only be updated from ConnectivityService handler thread
11572 // when mActiveIdleTimers lock is held.
11573 @GuardedBy("mActiveIdleTimers")
11574 private void reportNetworkActive() {
11575 final int length = mNetworkActivityListeners.beginBroadcast();
11576 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
11577 try {
11578 for (int i = 0; i < length; i++) {
11579 try {
11580 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
11581 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011582 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080011583 }
11584 }
11585 } finally {
11586 mNetworkActivityListeners.finishBroadcast();
11587 }
11588 }
11589
11590 @GuardedBy("mActiveIdleTimers")
11591 public void handleReportNetworkActivity() {
11592 synchronized (mActiveIdleTimers) {
11593 reportNetworkActive();
11594 }
11595 }
11596
lucaslin1a8b4c62021-01-21 02:02:55 +080011597 // This is deprecated and only to support legacy use cases.
11598 private int transportTypeToLegacyType(int type) {
11599 switch (type) {
11600 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011601 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080011602 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011603 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080011604 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011605 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080011606 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011607 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080011608 default:
11609 loge("Unexpected transport in transportTypeToLegacyType: " + type);
11610 }
11611 return ConnectivityManager.TYPE_NONE;
11612 }
11613
11614 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
11615 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
11616 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
11617 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
11618 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
11619 final long ident = Binder.clearCallingIdentity();
11620 try {
11621 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
11622 RECEIVE_DATA_ACTIVITY_CHANGE,
11623 null /* resultReceiver */,
11624 null /* scheduler */,
11625 0 /* initialCode */,
11626 null /* initialData */,
11627 null /* initialExtra */);
11628 } finally {
11629 Binder.restoreCallingIdentity(ident);
11630 }
11631 }
11632
11633 /**
11634 * Setup data activity tracking for the given network.
11635 *
11636 * Every {@code setupDataActivityTracking} should be paired with a
11637 * {@link #removeDataActivityTracking} for cleanup.
11638 */
11639 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
11640 final String iface = networkAgent.linkProperties.getInterfaceName();
11641
11642 final int timeout;
11643 final int type;
11644
11645 if (networkAgent.networkCapabilities.hasTransport(
11646 NetworkCapabilities.TRANSPORT_CELLULAR)) {
11647 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011648 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080011649 10);
11650 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11651 } else if (networkAgent.networkCapabilities.hasTransport(
11652 NetworkCapabilities.TRANSPORT_WIFI)) {
11653 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011654 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080011655 15);
11656 type = NetworkCapabilities.TRANSPORT_WIFI;
11657 } else {
11658 return; // do not track any other networks
11659 }
11660
lucaslinb961efc2021-01-21 02:03:17 +080011661 updateRadioPowerState(true /* isActive */, type);
11662
lucaslin1a8b4c62021-01-21 02:02:55 +080011663 if (timeout > 0 && iface != null) {
11664 try {
lucaslin1193a5d2021-01-21 02:04:15 +080011665 synchronized (mActiveIdleTimers) {
11666 // Networks start up.
11667 mNetworkActive = true;
11668 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
11669 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
11670 reportNetworkActive();
11671 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011672 } catch (Exception e) {
11673 // You shall not crash!
11674 loge("Exception in setupDataActivityTracking " + e);
11675 }
11676 }
11677 }
11678
11679 /**
11680 * Remove data activity tracking when network disconnects.
11681 */
11682 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
11683 final String iface = networkAgent.linkProperties.getInterfaceName();
11684 final NetworkCapabilities caps = networkAgent.networkCapabilities;
11685
lucaslinb961efc2021-01-21 02:03:17 +080011686 if (iface == null) return;
11687
11688 final int type;
11689 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
11690 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11691 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
11692 type = NetworkCapabilities.TRANSPORT_WIFI;
11693 } else {
11694 return; // do not track any other networks
11695 }
11696
11697 try {
11698 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080011699 synchronized (mActiveIdleTimers) {
11700 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
11701 // The call fails silently if no idle timer setup for this interface
11702 mNetd.idletimerRemoveInterface(iface, params.timeout,
11703 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080011704 }
lucaslinb961efc2021-01-21 02:03:17 +080011705 } catch (Exception e) {
11706 // You shall not crash!
11707 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080011708 }
11709 }
11710
11711 /**
11712 * Update data activity tracking when network state is updated.
11713 */
11714 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
11715 NetworkAgentInfo oldNetwork) {
11716 if (newNetwork != null) {
11717 setupDataActivityTracking(newNetwork);
11718 }
11719 if (oldNetwork != null) {
11720 removeDataActivityTracking(oldNetwork);
11721 }
11722 }
lucaslinb961efc2021-01-21 02:03:17 +080011723
11724 private void updateRadioPowerState(boolean isActive, int transportType) {
11725 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
11726 switch (transportType) {
11727 case NetworkCapabilities.TRANSPORT_CELLULAR:
11728 bs.reportMobileRadioPowerState(isActive, NO_UID);
11729 break;
11730 case NetworkCapabilities.TRANSPORT_WIFI:
11731 bs.reportWifiRadioPowerState(isActive, NO_UID);
11732 break;
11733 default:
11734 logw("Untracked transport type:" + transportType);
11735 }
11736 }
lucaslin1193a5d2021-01-21 02:04:15 +080011737
11738 public boolean isDefaultNetworkActive() {
11739 synchronized (mActiveIdleTimers) {
11740 // If there are no idle timers, it means that system is not monitoring activity,
11741 // so the default network is always considered active.
11742 //
11743 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
11744 // tracking is disabled (negative idle timer value configured), or no active default
11745 // network. In the latter case, this reports active but it should report inactive.
11746 return mNetworkActive || mActiveIdleTimers.isEmpty();
11747 }
11748 }
11749
11750 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
11751 mNetworkActivityListeners.register(l);
11752 }
11753
11754 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
11755 mNetworkActivityListeners.unregister(l);
11756 }
lucaslin012f7a12021-01-21 02:04:35 +080011757
11758 public void dump(IndentingPrintWriter pw) {
11759 synchronized (mActiveIdleTimers) {
11760 pw.print("mNetworkActive="); pw.println(mNetworkActive);
11761 pw.println("Idle timers:");
11762 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
11763 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
11764 final IdleTimerParams params = ent.getValue();
11765 pw.print(" timeout="); pw.print(params.timeout);
11766 pw.print(" type="); pw.println(params.transportType);
11767 }
11768 }
11769 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011770 }
James Mattis47db0582021-01-01 14:13:35 -080011771
Daniel Brightf9e945b2020-06-15 16:10:01 -070011772 /**
11773 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
11774 *
11775 * @param socketInfo the socket information
11776 * @param callback the callback to register
11777 */
11778 @Override
11779 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
11780 @NonNull final IQosCallback callback) {
11781 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
11782 if (nai == null || nai.networkCapabilities == null) {
11783 try {
11784 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
11785 } catch (final RemoteException ex) {
11786 loge("registerQosCallbackInternal: RemoteException", ex);
11787 }
11788 return;
11789 }
11790 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
11791 }
11792
11793 /**
11794 * Register a {@link IQosCallback} with base {@link QosFilter}.
11795 *
11796 * @param filter the filter to register
11797 * @param callback the callback to register
11798 * @param nai the agent information related to the filter's network
11799 */
11800 @VisibleForTesting
11801 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
11802 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011803 Objects.requireNonNull(filter, "filter must be non-null");
11804 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011805
11806 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080011807 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
11808 // on this network is unregistered when the app loses permission or b) no QoS
11809 // callbacks are sent for restricted networks unless the app currently has permission
11810 // to access restricted networks.
11811 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070011812 }
11813 mQosCallbackTracker.registerCallback(callback, filter, nai);
11814 }
11815
11816 /**
11817 * Unregisters the given callback.
11818 *
11819 * @param callback the callback to unregister
11820 */
11821 @Override
11822 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011823 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011824 mQosCallbackTracker.unregisterCallback(callback);
11825 }
James Mattis47db0582021-01-01 14:13:35 -080011826
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011827 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
11828 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
11829 // Enterprise device can be fully managed like device owner and such use case
11830 // also should be supported. Calling app check for work profile and fully managed device
11831 // is already done in DevicePolicyManager.
11832 // This check is an extra caution to be sure device is fully managed or not.
11833 final UserManager um = mContext.getSystemService(UserManager.class);
11834 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
11835 if (um.isManagedProfile(profile.getIdentifier())) {
11836 return true;
11837 }
Chalard Jean03552c42023-05-29 17:02:43 +090011838 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011839 return false;
11840 }
11841
James Mattis45d81842021-01-10 14:24:24 -080011842 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011843 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011844 *
11845 * See the documentation for the individual preferences for a description of the supported
11846 * behaviors.
11847 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011848 * @param profile If the device owner is set, any profile is allowed.
11849 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011850 * @param preferences the list of profile network preferences for the
11851 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011852 * @param listener an optional listener to listen for completion of the operation.
11853 */
11854 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011855 public void setProfileNetworkPreferences(
11856 @NonNull final UserHandle profile,
11857 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090011858 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011859 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011860 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011861
11862 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011863 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
11864 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
11865 .build();
11866 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011867 }
11868
paulhu3ffffe72021-09-16 10:15:22 +080011869 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011870 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011871 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011872 }
11873 if (profile.getIdentifier() < 0) {
11874 throw new IllegalArgumentException("Must explicitly specify a user handle ("
11875 + "UserHandle.CURRENT not supported)");
11876 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011877 if (!isNetworkPreferenceAllowedForProfile(profile)) {
11878 throw new IllegalArgumentException("Profile must be a managed profile "
11879 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011880 }
paulhuaa0743d2021-05-26 21:56:03 +080011881
Chalard Jean0606fc82022-12-14 20:34:43 +090011882 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011883 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011884 for (final ProfileNetworkPreference preference : preferences) {
11885 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011886 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080011887 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011888 switch (preference.getPreference()) {
11889 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
11890 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011891 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011892 if (preference.getPreferenceEnterpriseId() != 0) {
11893 throw new IllegalArgumentException(
11894 "Invalid enterprise identifier in setProfileNetworkPreferences");
11895 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011896 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080011897 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
11898 blockingNonEnterprise = true;
11899 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011900 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
11901 allowFallback = false;
11902 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011903 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011904 // This code is needed even though there is a check later on,
11905 // because isRangeAlreadyInPreferenceList assumes that every preference
11906 // has a UID list.
11907 if (hasDefaultPreference) {
11908 throw new IllegalArgumentException(
11909 "Default profile preference should not be set along with other "
11910 + "preference");
11911 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011912 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
11913 throw new IllegalArgumentException(
11914 "Invalid enterprise identifier in setProfileNetworkPreferences");
11915 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011916 final Set<UidRange> uidRangeSet =
11917 getUidListToBeAppliedForNetworkPreference(profile, preference);
11918 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
11919 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
11920 } else {
11921 throw new IllegalArgumentException(
11922 "Overlapping uid range in setProfileNetworkPreferences");
11923 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011924 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011925 nc.addEnterpriseId(
11926 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011927 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11928 break;
11929 default:
11930 throw new IllegalArgumentException(
11931 "Invalid preference in setProfileNetworkPreferences");
11932 }
Junyu Lai35665cc2022-12-19 17:37:48 +080011933 preferenceList.add(new ProfileNetworkPreferenceInfo(
11934 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011935 if (hasDefaultPreference && preferenceList.size() > 1) {
11936 throw new IllegalArgumentException(
11937 "Default profile preference should not be set along with other preference");
11938 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011939 }
11940 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011941 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011942 }
11943
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011944 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
11945 @NonNull final UserHandle profile,
11946 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
11947 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080011948 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
11949 profileNetworkPreference.getIncludedUids());
11950
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011951 if (uidRangeSet.size() > 0) {
11952 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
11953 throw new IllegalArgumentException(
11954 "Allow uid range is outside the uid range of profile.");
11955 }
11956 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080011957 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011958 profileNetworkPreference.getExcludedUids());
11959 if (disallowUidRangeSet.size() > 0) {
11960 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
11961 throw new IllegalArgumentException(
11962 "disallow uid range is outside the uid range of profile.");
11963 }
11964 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
11965 disallowUidRangeSet);
11966 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011967 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011968 uidRangeSet.add(profileUids);
11969 }
11970 }
11971 return uidRangeSet;
11972 }
11973
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011974 private boolean isEnterpriseIdentifierValid(
11975 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011976 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011977 return true;
11978 }
11979 return false;
11980 }
11981
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011982 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090011983 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011984 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090011985 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011986 // The NRI for a user should contain the request for capabilities.
11987 // If fallback to default network is needed then NRI should include
11988 // the request for the default network. Create an image of it to
11989 // have the correct UIDs in it (also a request can only be part of one NRI, because
11990 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011991 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
11992 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011993 if (pref.allowFallback) {
11994 nrs.add(createDefaultInternetRequestForTransport(
11995 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11996 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011997 if (VDBG) {
11998 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
11999 pref.capabilities.getUids()));
12000 }
12001
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012002 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080012003 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080012004 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012005 result.add(nri);
12006 }
12007 return result;
12008 }
12009
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012010 /**
12011 * Compare if the given UID range sets have the same UIDs.
12012 *
12013 */
12014 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090012015 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012016 @NonNull Set<UidRange> uidRangeSet) {
12017 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
12018 return false;
12019 }
Chalard Jean0606fc82022-12-14 20:34:43 +090012020 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012021 if (UidRangeUtils.doesRangeSetOverlap(
12022 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
12023 return true;
12024 }
12025 }
12026 return false;
12027 }
12028
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012029 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090012030 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012031 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012032 /*
12033 * handleSetProfileNetworkPreference is always called for single user.
12034 * preferenceList only contains preferences for different uids within the same user
12035 * (enforced by getUidListToBeAppliedForNetworkPreference).
12036 * Clear all the existing preferences for the user before applying new preferences.
12037 *
12038 */
Chalard Jean0606fc82022-12-14 20:34:43 +090012039 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
12040 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012041 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
12042 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012043
paulhu74128522021-09-28 02:29:03 +000012044 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
12045 addPerAppDefaultNetworkRequests(
12046 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080012047 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080012048
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012049 // Finally, rematch.
12050 rematchAllNetworksAndRequests();
12051
12052 if (null != listener) {
12053 try {
12054 listener.onComplete();
12055 } catch (RemoteException e) {
12056 loge("Listener for setProfileNetworkPreference has died");
12057 }
12058 }
12059 }
12060
paulhu51f77dc2021-06-07 02:34:20 +000012061 @VisibleForTesting
12062 @NonNull
12063 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12064 @NonNull final Set<Integer> uids) {
12065 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12066 if (uids.size() == 0) {
12067 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12068 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
12069 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
12070 return nris;
12071 }
12072
12073 final List<NetworkRequest> requests = new ArrayList<>();
12074 // The NRI should be comprised of two layers:
12075 // - The request for the mobile network preferred.
12076 // - The request for the default network, for fallback.
12077 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012078 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012079 requests.add(createDefaultInternetRequestForTransport(
12080 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12081 final Set<UidRange> ranges = new ArraySet<>();
12082 for (final int uid : uids) {
12083 ranges.add(new UidRange(uid, uid));
12084 }
12085 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080012086 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080012087 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000012088 return nris;
12089 }
12090
12091 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000012092 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000012093 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
12094 addPerAppDefaultNetworkRequests(
12095 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000012096 // Finally, rematch.
12097 rematchAllNetworksAndRequests();
12098 }
12099
Patrick Rohr2857ac42022-01-21 14:58:16 +010012100 private void handleIngressRateLimitChanged() {
12101 final long oldIngressRateLimit = mIngressRateLimit;
12102 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
12103 mContext);
12104 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
12105 if (canNetworkBeRateLimited(networkAgent)) {
12106 // If rate limit has previously been enabled, remove the old limit first.
12107 if (oldIngressRateLimit >= 0) {
12108 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
12109 }
12110 if (mIngressRateLimit >= 0) {
12111 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12112 mIngressRateLimit);
12113 }
12114 }
12115 }
12116 }
12117
12118 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012119 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jean03552c42023-05-29 17:02:43 +090012120 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012121
Patrick Rohrff3b3f82022-02-09 15:15:52 +010012122 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
12123 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
12124 // internet connectivity can be rate limited.
12125 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
12126 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010012127 return false;
12128 }
12129
12130 final String iface = networkAgent.linkProperties.getInterfaceName();
12131 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012132 // This may happen in tests, but if there is no interface then there is nothing that
12133 // can be rate limited.
12134 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012135 return false;
12136 }
12137 return true;
12138 }
12139
James Mattis45d81842021-01-10 14:24:24 -080012140 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012141 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12142 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012143 }
12144
12145 /**
12146 * Used by automotive devices to set the network preferences used to direct traffic at an
12147 * application level as per the given OemNetworkPreferences. An example use-case would be an
12148 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12149 * vehicle via a particular network.
12150 *
12151 * Calling this will overwrite the existing preference.
12152 *
James Mattisda32cfe2021-01-26 16:23:52 -080012153 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012154 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012155 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012156 */
James Mattis47db0582021-01-01 14:13:35 -080012157 @Override
James Mattis45d81842021-01-10 14:24:24 -080012158 public void setOemNetworkPreference(
12159 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012160 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012161
James Mattisfa270db2021-05-31 17:11:10 -070012162 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12163 // Only bypass the permission/device checks if this is a valid test request.
12164 if (isValidTestOemNetworkPreference(preference)) {
12165 enforceManageTestNetworksPermission();
12166 } else {
12167 enforceAutomotiveDevice();
12168 enforceOemNetworkPreferencesPermission();
12169 validateOemNetworkPreferences(preference);
12170 }
James Mattis45d81842021-01-10 14:24:24 -080012171
James Mattis45d81842021-01-10 14:24:24 -080012172 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
12173 new Pair<>(preference, listener)));
12174 }
12175
James Mattisfa270db2021-05-31 17:11:10 -070012176 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000012177 * Sets the specified UIDs to get/receive the VPN as the only default network.
12178 *
12179 * Calling this will overwrite the existing network preference for this session, and the
12180 * specified UIDs won't get any default network when no VPN is connected.
12181 *
12182 * @param session The VPN session which manages the passed UIDs.
12183 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
12184 * setting for this session if the array is empty. Null is not allowed, the
12185 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
12186 * @hide
12187 */
12188 @Override
12189 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
12190 Objects.requireNonNull(ranges);
12191 enforceNetworkStackOrSettingsPermission();
12192 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
12193 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
12194 throw new IllegalArgumentException(
12195 "setVpnNetworkPreference: Passed UID ranges overlap");
12196 }
12197
12198 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
12199 new VpnNetworkPreferenceInfo(session,
12200 new ArraySet<UidRange>(Arrays.asList(ranges)))));
12201 }
12202
12203 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
12204 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
12205
12206 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
12207 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
12208
12209 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
12210 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
12211 // Finally, rematch.
12212 rematchAllNetworksAndRequests();
12213 }
12214
12215 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
12216 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
12217 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12218 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
12219 final List<NetworkRequest> requests = new ArrayList<>();
12220 // Request VPN only, so other networks won't be the fallback options when VPN is not
12221 // connected temporarily.
12222 requests.add(createVpnRequest());
12223 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
12224 setNetworkRequestUids(requests, uidRanges);
12225 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
12226 }
12227 return nris;
12228 }
12229
12230 /**
James Mattisfa270db2021-05-31 17:11:10 -070012231 * Check the validity of an OEM network preference to be used for testing purposes.
12232 * @param preference the preference to validate
12233 * @return true if this is a valid OEM network preference test request.
12234 */
12235 private boolean isValidTestOemNetworkPreference(
12236 @NonNull final OemNetworkPreferences preference) {
12237 // Allow for clearing of an existing OemNetworkPreference used for testing.
12238 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
12239 // changes after this check is complete. This is an unlikely scenario as calling of this API
12240 // is controlled by the OEM therefore the added complexity is not worth adding given those
12241 // circumstances. That said, it is an edge case to be aware of hence this comment.
12242 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
12243 && isTestOemNetworkPreference(mOemNetworkPreferences);
12244 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
12245 }
12246
12247 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
12248 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
12249 return prefMap.size() == 1
12250 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
12251 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
12252 }
12253
James Mattis45d81842021-01-10 14:24:24 -080012254 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
12255 for (@OemNetworkPreferences.OemNetworkPreference final int pref
12256 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070012257 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
12258 throw new IllegalArgumentException(
12259 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
12260 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080012261 }
12262 }
12263 }
12264
12265 private void handleSetOemNetworkPreference(
12266 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012267 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080012268 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12269 if (DBG) {
12270 log("set OEM network preferences :" + preference.toString());
12271 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012272
James Mattiscb1e0362021-04-06 17:07:42 -070012273 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000012274 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
12275 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
12276 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080012277 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080012278
12279 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012280 try {
12281 listener.onComplete();
12282 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080012283 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012284 }
James Mattis45d81842021-01-10 14:24:24 -080012285 }
12286 }
12287
paulhu74128522021-09-28 02:29:03 +000012288 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080012289 // Skip the requests which are set by other network preference. Because the uid range rules
12290 // should stay in netd.
12291 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080012292 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080012293 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080012294 }
12295
James Mattis3ce3d3c2021-02-09 18:18:28 -080012296 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
12297 ensureRunningOnConnectivityServiceThread();
12298 mDefaultNetworkRequests.addAll(nris);
12299 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
12300 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080012301 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000012302 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
12303 nrisToRegister.addAll(
12304 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
12305 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012306 }
12307
12308 /**
12309 * All current requests that are tracking the default network need to be assessed as to whether
12310 * or not the current set of per-application default requests will be changing their default
12311 * network. If so, those requests will need to be updated so that they will send callbacks for
12312 * default network changes at the appropriate time. Additionally, those requests tracking the
12313 * default that were previously updated by this flow will need to be reassessed.
12314 * @return the nris which will need to be updated.
12315 */
12316 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
12317 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
12318 // Get the distinct nris to check since for multilayer requests, it is possible to have the
12319 // same nri in the map's values for each of its NetworkRequest objects.
12320 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080012321 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012322 // Include this nri if it is currently being tracked.
12323 if (isPerAppTrackedNri(nri)) {
12324 defaultCallbackRequests.add(nri);
12325 continue;
12326 }
12327 // We only track callbacks for requests tracking the default.
12328 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
12329 continue;
12330 }
12331 // Include this nri if it will be tracked by the new per-app default requests.
12332 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012333 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080012334 if (isNriGoingToBeTracked) {
12335 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080012336 }
12337 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080012338 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080012339 }
12340
James Mattis3ce3d3c2021-02-09 18:18:28 -080012341 /**
12342 * Create nris for those network requests that are currently tracking the default network that
12343 * are being controlled by a per-application default.
12344 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
12345 * foundation when creating the nri. Important items include the calling uid's original
12346 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
12347 * requests are assumed to have already been validated as needing to be updated.
12348 * @return the Set of nris to use when registering network requests.
12349 */
12350 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
12351 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
12352 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
12353 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
12354 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012355 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012356
Chalard Jean9473c982021-07-29 20:03:04 +090012357 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080012358 if (trackingNri == mDefaultRequest) {
12359 callbackRequestsToRegister.add(new NetworkRequestInfo(
12360 callbackRequest,
12361 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
12362 continue;
12363 }
12364
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012365 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012366 callbackRequestsToRegister.add(new NetworkRequestInfo(
12367 callbackRequest,
12368 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012369 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090012370 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080012371 }
12372 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080012373 }
12374
Chalard Jean17215832021-03-01 14:06:28 +090012375 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
12376 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090012377 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012378 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090012379 }
12380 }
12381
James Mattis45d81842021-01-10 14:24:24 -080012382 /**
12383 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
12384 */
12385 @VisibleForTesting
12386 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012387 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080012388 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012389 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080012390 final SparseArray<Set<Integer>> uids =
12391 createUidsFromOemNetworkPreferences(preference);
12392 for (int i = 0; i < uids.size(); i++) {
12393 final int key = uids.keyAt(i);
12394 final Set<Integer> value = uids.valueAt(i);
12395 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
12396 // No need to add an nri without any requests.
12397 if (0 == nri.mRequests.size()) {
12398 continue;
12399 }
12400 nris.add(nri);
12401 }
12402
12403 return nris;
12404 }
12405
12406 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
12407 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070012408 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080012409 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080012410 final List<UserHandle> users =
12411 mContext.getSystemService(UserManager.class).getUserHandles(true);
12412 if (null == users || users.size() == 0) {
12413 if (VDBG || DDBG) {
12414 log("No users currently available for setting the OEM network preference.");
12415 }
James Mattisb6b6a432021-06-01 22:30:36 -070012416 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080012417 }
James Mattis45d81842021-01-10 14:24:24 -080012418 for (final Map.Entry<String, Integer> entry :
12419 preference.getNetworkPreferences().entrySet()) {
12420 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070012421 // Add the rules for all users as this policy is device wide.
12422 for (final UserHandle user : users) {
12423 try {
12424 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
12425 if (!prefToUids.contains(pref)) {
12426 prefToUids.put(pref, new ArraySet<>());
12427 }
12428 prefToUids.get(pref).add(uid);
12429 } catch (PackageManager.NameNotFoundException e) {
12430 // Although this may seem like an error scenario, it is ok that uninstalled
12431 // packages are sent on a network preference as the system will watch for
12432 // package installations associated with this network preference and update
12433 // accordingly. This is done to minimize race conditions on app install.
12434 continue;
James Mattis45d81842021-01-10 14:24:24 -080012435 }
James Mattis45d81842021-01-10 14:24:24 -080012436 }
12437 }
James Mattisb6b6a432021-06-01 22:30:36 -070012438 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080012439 }
12440
12441 private NetworkRequestInfo createNriFromOemNetworkPreferences(
12442 @OemNetworkPreferences.OemNetworkPreference final int preference,
12443 @NonNull final Set<Integer> uids) {
12444 final List<NetworkRequest> requests = new ArrayList<>();
12445 // Requests will ultimately be evaluated by order of insertion therefore it matters.
12446 switch (preference) {
12447 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
12448 requests.add(createUnmeteredNetworkRequest());
12449 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070012450 requests.add(createDefaultInternetRequestForTransport(
12451 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080012452 break;
12453 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
12454 requests.add(createUnmeteredNetworkRequest());
12455 requests.add(createOemPaidNetworkRequest());
12456 break;
12457 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
12458 requests.add(createOemPaidNetworkRequest());
12459 break;
12460 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
12461 requests.add(createOemPrivateNetworkRequest());
12462 break;
James Mattisfa270db2021-05-31 17:11:10 -070012463 case OEM_NETWORK_PREFERENCE_TEST:
12464 requests.add(createUnmeteredNetworkRequest());
12465 requests.add(createTestNetworkRequest());
12466 requests.add(createDefaultRequest());
12467 break;
12468 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
12469 requests.add(createTestNetworkRequest());
12470 break;
James Mattis45d81842021-01-10 14:24:24 -080012471 default:
12472 // This should never happen.
12473 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
12474 + " called with invalid preference of " + preference);
12475 }
12476
James Mattisfa270db2021-05-31 17:11:10 -070012477 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090012478 for (final int uid : uids) {
12479 ranges.add(new UidRange(uid, uid));
12480 }
12481 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080012482 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080012483 }
12484
12485 private NetworkRequest createUnmeteredNetworkRequest() {
12486 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12487 .addCapability(NET_CAPABILITY_NOT_METERED)
12488 .addCapability(NET_CAPABILITY_VALIDATED);
12489 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
12490 }
12491
12492 private NetworkRequest createOemPaidNetworkRequest() {
12493 // NET_CAPABILITY_OEM_PAID is a restricted capability.
12494 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12495 .addCapability(NET_CAPABILITY_OEM_PAID)
12496 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12497 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12498 }
12499
12500 private NetworkRequest createOemPrivateNetworkRequest() {
12501 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
12502 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12503 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
12504 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12505 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12506 }
12507
12508 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070012509 final NetworkCapabilities netcap = new NetworkCapabilities();
12510 netcap.addCapability(NET_CAPABILITY_INTERNET);
12511 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
12512 return netcap;
12513 }
12514
12515 private NetworkRequest createTestNetworkRequest() {
12516 final NetworkCapabilities netcap = new NetworkCapabilities();
12517 netcap.clearAll();
12518 netcap.addTransportType(TRANSPORT_TEST);
12519 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080012520 }
James Mattis47db0582021-01-01 14:13:35 -080012521 }
markchien738ad912021-12-09 18:15:45 +080012522
12523 @Override
12524 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
12525 enforceNetworkStackOrSettingsPermission();
12526
12527 try {
12528 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012529 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012530 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012531 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012532 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012533 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012534 throw new IllegalStateException(e);
12535 }
12536 }
12537
12538 @Override
12539 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
12540 enforceNetworkStackOrSettingsPermission();
12541
12542 try {
12543 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012544 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012545 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012546 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012547 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012548 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012549 throw new IllegalStateException(e);
12550 }
12551 }
markchiene1561fa2021-12-09 22:00:56 +080012552
12553 @Override
markchien3c04e662022-03-22 16:29:56 +080012554 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080012555 enforceNetworkStackOrSettingsPermission();
12556
markchien3c04e662022-03-22 16:29:56 +080012557 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
12558 int firewallRule = getFirewallRuleType(chain, rule);
12559
12560 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
12561 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
12562 }
12563
markchiene1561fa2021-12-09 22:00:56 +080012564 try {
markchien3c04e662022-03-22 16:29:56 +080012565 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012566 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080012567 throw new IllegalStateException(e);
12568 }
12569 }
markchien98a6f952022-01-13 23:43:53 +080012570
Motomu Utsumi900b8062023-01-19 16:16:49 +090012571 @Override
12572 public int getUidFirewallRule(final int chain, final int uid) {
12573 enforceNetworkStackOrSettingsPermission();
12574 return mBpfNetMaps.getUidRule(chain, uid);
12575 }
12576
markchien3c04e662022-03-22 16:29:56 +080012577 private int getFirewallRuleType(int chain, int rule) {
12578 final int defaultRule;
12579 switch (chain) {
12580 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000012581 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
12582 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000012583 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080012584 defaultRule = FIREWALL_RULE_ALLOW;
12585 break;
12586 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
12587 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
12588 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
12589 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
12590 defaultRule = FIREWALL_RULE_DENY;
12591 break;
12592 default:
12593 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
12594 }
12595 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
12596
12597 return rule;
12598 }
12599
Motomu Utsumied1848c2023-03-28 18:08:12 +090012600 private void closeSocketsForFirewallChainLocked(final int chain)
12601 throws ErrnoException, SocketException, InterruptedIOException {
12602 if (mBpfNetMaps.isFirewallAllowList(chain)) {
12603 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
12604 // So, close all non-system socket owned by uids that are not explicitly allowed
12605 Set<Range<Integer>> ranges = new ArraySet<>();
12606 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
12607 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
12608 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
12609 } else {
12610 // Denylist means the firewall allows all by default, uids must be explicitly denied
12611 // So, close socket owned by uids that are explicitly denied
12612 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
12613 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
12614 }
12615 }
12616
markchien98a6f952022-01-13 23:43:53 +080012617 @Override
12618 public void setFirewallChainEnabled(final int chain, final boolean enable) {
12619 enforceNetworkStackOrSettingsPermission();
12620
12621 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012622 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012623 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080012624 throw new IllegalStateException(e);
12625 }
Motomu Utsumied1848c2023-03-28 18:08:12 +090012626
Chalard Jean03552c42023-05-29 17:02:43 +090012627 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumied1848c2023-03-28 18:08:12 +090012628 try {
12629 closeSocketsForFirewallChainLocked(chain);
12630 } catch (ErrnoException | SocketException | InterruptedIOException e) {
12631 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
12632 }
12633 }
markchien98a6f952022-01-13 23:43:53 +080012634 }
12635
markchien00a0bed2022-01-13 23:46:13 +080012636 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012637 public boolean getFirewallChainEnabled(final int chain) {
12638 enforceNetworkStackOrSettingsPermission();
12639
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000012640 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012641 }
12642
12643 @Override
markchien00a0bed2022-01-13 23:46:13 +080012644 public void replaceFirewallChain(final int chain, final int[] uids) {
12645 enforceNetworkStackOrSettingsPermission();
12646
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000012647 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080012648 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080012649
12650 @Override
12651 public IBinder getCompanionDeviceManagerProxyService() {
12652 enforceNetworkStackPermission(mContext);
12653 return mCdmps;
12654 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070012655}