blob: 639a0ba33c6f72d102f8b44417fa2a8ce72cf321 [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);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006803 }
6804
6805 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6806 }
6807
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006808 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006809 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006810 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006811 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006812 }
6813
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006814 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6815 return mLockdownEnabled
6816 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6817 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006818 }
6819
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006820 private NetworkAgentInfo getLegacyLockdownNai() {
6821 if (!mLockdownEnabled) {
6822 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006823 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006824 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006825 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6826 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006827
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006828 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006829 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6830 // a local variable. There is no need to make a copy because its contents cannot change.
6831 final Network[] underlying = nai.declaredUnderlyingNetworks;
6832 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006833 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006834 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006835
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006836 // The legacy lockdown VPN always uses the default network.
6837 // If the VPN's underlying network is no longer the current default network, it means that
6838 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006839 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6840 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006841 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006842 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006843 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006844 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006845
6846 return nai;
6847 };
6848
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006849 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6850 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6851 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006852 private DetailedState getLegacyLockdownState(DetailedState origState) {
6853 if (origState != DetailedState.CONNECTED) {
6854 return origState;
6855 }
6856 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6857 ? DetailedState.CONNECTING
6858 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006859 }
6860
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006861 private void filterForLegacyLockdown(NetworkInfo ni) {
6862 if (!mLockdownEnabled || !ni.isConnected()) return;
6863 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6864 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6865 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6866 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6867 // network, this time with a state of CONNECTED.
6868 //
6869 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6870 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6871 // is not too far off the truth, since an always-on VPN, when not connected, is always
6872 // trying to reconnect.
6873 if (getLegacyLockdownNai() == null) {
6874 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6875 }
6876 }
6877
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006878 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006879 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006880 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006881 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006882 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6883 return;
6884 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006885 final long ident = Binder.clearCallingIdentity();
6886 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006887 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006888 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006889 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006890 } finally {
6891 Binder.restoreCallingIdentity(ident);
6892 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006893 }
Wink Savillecb117d32013-08-29 14:57:08 -07006894
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006895 @Override
6896 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006897 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006898 final long ident = Binder.clearCallingIdentity();
6899 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006900 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006901 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006902 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6903 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006904 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006905 } finally {
6906 Binder.restoreCallingIdentity(ident);
6907 }
6908 }
6909
James Mattis02220e22021-03-13 19:27:21 -08006910 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006911 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6912 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6913 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006914 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006915 }
6916
James Mattis02220e22021-03-13 19:27:21 -08006917 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006918 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006919 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006920 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6921 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006922 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006923 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6924 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6925 }
junyulaid91e7052020-08-28 13:44:33 +08006926 }
6927
James Mattis02220e22021-03-13 19:27:21 -08006928 private void onPackageChanged(@NonNull final String packageName) {
6929 // This is necessary in case a package is added or removed, but also when it's replaced to
6930 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6931 // as one in the preferences, then it should follow the same routing as that other package,
6932 // which means updating the rules is never to be needed in this case (whether it joins or
6933 // leaves a UID with a preference).
6934 if (isMappedInOemNetworkPreference(packageName)) {
6935 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6936 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09006937
6938 // Invalidates cache entry when the package is updated.
6939 synchronized (mSelfCertifiedCapabilityCache) {
6940 mSelfCertifiedCapabilityCache.remove(packageName);
6941 }
James Mattis02220e22021-03-13 19:27:21 -08006942 }
6943
6944 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006945 @Override
6946 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006947 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006948 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006949 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006950
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006951 // User should be filled for below intents, check the existence.
6952 if (user == null) {
6953 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6954 return;
6955 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006956
Lorenzo Colitticd675292021-02-04 17:32:07 +09006957 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006958 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006959 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006960 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006961 } else {
junyulaid91e7052020-08-28 13:44:33 +08006962 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006963 }
6964 }
6965 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006966
James Mattis02220e22021-03-13 19:27:21 -08006967 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6968 @Override
6969 public void onReceive(Context context, Intent intent) {
6970 ensureRunningOnConnectivityServiceThread();
6971 switch (intent.getAction()) {
6972 case Intent.ACTION_PACKAGE_ADDED:
6973 case Intent.ACTION_PACKAGE_REMOVED:
6974 case Intent.ACTION_PACKAGE_REPLACED:
6975 onPackageChanged(intent.getData().getSchemeSpecificPart());
6976 break;
6977 default:
6978 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6979 }
6980 }
6981 };
6982
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006983 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006984 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006985
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006986 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006987 public final String name;
6988 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006989 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006990 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006991
lifraf3a3492021-03-10 13:58:14 +08006992 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6993 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006994 this.name = name;
6995 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006996 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006997 mDeathRecipient = deathRecipient;
6998
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006999 if (mDeathRecipient == null) {
7000 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007001 }
7002 }
7003
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007004 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007005 try {
7006 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
7007 } catch (RemoteException e) {
7008 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007009 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007010 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007011 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007012
James Mattis4fce5d12020-11-12 15:53:42 -08007013 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
7014 for (int i = 0; i < requests.size(); i++) {
7015 ensureNetworkRequestHasType(requests.get(i));
7016 }
7017 }
7018
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007019 private void ensureNetworkRequestHasType(NetworkRequest request) {
7020 if (request.type == NetworkRequest.Type.NONE) {
7021 throw new IllegalArgumentException(
7022 "All NetworkRequests in ConnectivityService must have a type");
7023 }
7024 }
7025
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007026 /**
7027 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08007028 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007029 */
James Mattis258ea3c2020-11-15 15:04:40 -08007030 @VisibleForTesting
7031 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08007032 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
7033 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08007034 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08007035
James Mattisa076c532020-12-02 14:12:41 -08007036 // mSatisfier and mActiveRequest rely on one another therefore set them together.
7037 void setSatisfier(
7038 @Nullable final NetworkAgentInfo satisfier,
7039 @Nullable final NetworkRequest activeRequest) {
7040 mSatisfier = satisfier;
7041 mActiveRequest = activeRequest;
7042 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007043
James Mattisd31bdfa2020-12-23 16:37:26 -08007044 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007045 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09007046 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08007047 private NetworkAgentInfo mSatisfier;
7048 NetworkAgentInfo getSatisfier() {
7049 return mSatisfier;
7050 }
7051
7052 // The request in mRequests assigned to a network agent. This is null if none of the
7053 // requests in mRequests can be satisfied. This member has the constraint of only being
7054 // accessible on the handler thread.
7055 @Nullable
7056 private NetworkRequest mActiveRequest;
7057 NetworkRequest getActiveRequest() {
7058 return mActiveRequest;
7059 }
7060
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007061 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007062 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08007063 @Nullable
7064 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007065
7066 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08007067 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007068 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007069 final int mPid;
7070 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08007071 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007072 @Nullable
7073 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007074
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007075 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08007076 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007077
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007078 // Effective UID of this request. This is different from mUid when a privileged process
7079 // files a request on behalf of another UID. This UID is used to determine blocked status,
7080 // UID matching, and so on. mUid above is used for permission checks and to enforce the
7081 // maximum limit of registered callbacks per UID.
7082 final int mAsUid;
7083
paulhu48291862021-07-14 14:53:57 +08007084 // Preference order of this request.
7085 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08007086
James Mattis3ce3d3c2021-02-09 18:18:28 -08007087 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
7088 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
7089 // maintained for keying off of. This is only a concern when the original nri
7090 // mNetworkRequests changes which happens currently for apps that register callbacks to
7091 // track the default network. In those cases, the nri is updated to have mNetworkRequests
7092 // that match the per-app default nri that currently tracks the calling app's uid so that
7093 // callbacks are fired at the appropriate time. When the callbacks fire,
7094 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
7095 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
7096 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7097 @NonNull
7098 private final NetworkRequest mNetworkRequestForCallback;
7099 NetworkRequest getNetworkRequestForCallback() {
7100 return mNetworkRequestForCallback;
7101 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007102
James Mattisd31bdfa2020-12-23 16:37:26 -08007103 /**
7104 * Get the list of UIDs this nri applies to.
7105 */
7106 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00007107 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08007108 // networkCapabilities.getUids() returns a defensive copy.
7109 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007110 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
7111 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08007112 }
7113
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007114 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
7115 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08007116 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08007117 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007118 }
7119
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007120 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007121 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08007122 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007123 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007124 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007125 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007126 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08007127 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007128 mBinder = null;
7129 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007130 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007131 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007132 mPerUidCounter = getRequestCounter(this);
7133 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007134 /**
7135 * Location sensitive data not included in pending intent. Only included in
7136 * {@link NetworkCallback}.
7137 */
7138 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007139 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007140 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007141 }
7142
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007143 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007144 @Nullable final IBinder binder,
7145 @NetworkCallback.Flag int callbackFlags,
7146 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007147 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7148 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007149 }
7150
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007151 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007152 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007153 @Nullable final IBinder binder,
7154 @NetworkCallback.Flag int callbackFlags,
7155 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007156 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007157 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007158 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007159 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007160 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007161 mBinder = binder;
7162 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007163 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007164 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007165 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007166 mPerUidCounter = getRequestCounter(this);
7167 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007168 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007169 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007170 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007171 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007172 }
7173
James Mattis3ce3d3c2021-02-09 18:18:28 -08007174 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7175 @NonNull final List<NetworkRequest> r) {
7176 super();
7177 ensureAllNetworkRequestsHaveType(r);
7178 mRequests = initializeRequests(r);
7179 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007180 final NetworkAgentInfo satisfier = nri.getSatisfier();
7181 if (null != satisfier) {
7182 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7183 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007184 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007185 // As this code creates a new NRI with a new set of requests, figure out which of
7186 // the list of requests should be the active request. It is always the first
7187 // request of the list that can be satisfied by the satisfier since the order of
7188 // requests is a priority order.
7189 // Note even in the presence of a satisfier there may not be an active request,
7190 // when the satisfier is the no-service network.
7191 NetworkRequest activeRequest = null;
7192 for (final NetworkRequest candidate : r) {
7193 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7194 activeRequest = candidate;
7195 break;
7196 }
7197 }
7198 setSatisfier(satisfier, activeRequest);
7199 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007200 mMessenger = nri.mMessenger;
7201 mBinder = nri.mBinder;
7202 mPid = nri.mPid;
7203 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007204 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007205 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007206 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007207 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007208 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007209 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007210 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007211 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007212 }
7213
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007214 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007215 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007216 }
7217
paulhue9913722021-05-26 15:19:20 +08007218 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007219 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007220 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007221 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007222 }
7223
James Mattis2516da32021-01-31 17:06:19 -08007224 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7225 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7226 // false.
7227 boolean isBeingSatisfied() {
7228 return (null != mSatisfier && null != mActiveRequest);
7229 }
7230
James Mattis3d229892020-11-16 16:46:28 -08007231 boolean isMultilayerRequest() {
7232 return mRequests.size() > 1;
7233 }
7234
James Mattis45d81842021-01-10 14:24:24 -08007235 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7236 // Creating a defensive copy to prevent the sender from modifying the list being
7237 // reflected in the return value of this method.
7238 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007239 return Collections.unmodifiableList(tempRequests);
7240 }
7241
James Mattisb1392002021-03-31 13:57:52 -07007242 void linkDeathRecipient() {
7243 if (null != mBinder) {
7244 try {
7245 mBinder.linkToDeath(this, 0);
7246 } catch (RemoteException e) {
7247 binderDied();
7248 }
7249 }
7250 }
7251
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007252 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007253 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007254 try {
7255 mBinder.unlinkToDeath(this, 0);
7256 } catch (NoSuchElementException e) {
7257 // Temporary workaround for b/194394697 pending analysis of additional logs
7258 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7259 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007260 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007261 }
7262
paulhu48291862021-07-14 14:53:57 +08007263 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7264 // Compare two preference orders.
7265 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007266 }
7267
paulhu48291862021-07-14 14:53:57 +08007268 int getPreferenceOrderForNetd() {
7269 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7270 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7271 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007272 }
paulhu48291862021-07-14 14:53:57 +08007273 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007274 }
7275
James Mattis4fce5d12020-11-12 15:53:42 -08007276 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007277 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007278 // As an immutable collection, mRequests cannot change by the time the
7279 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7280 // is acceptable. Use handleReleaseNetworkRequest and not directly
7281 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7282 // the app already unregistered the request.
7283 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7284 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007285 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007286
James Mattis4fce5d12020-11-12 15:53:42 -08007287 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007288 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007289 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7290 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007291 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007292 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007293 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007294 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007295 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007296 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007297 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007298 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007299 }
7300
Junyu Lai00d92df2022-07-05 11:01:52 +08007301 // Keep backward compatibility since the ServiceSpecificException is used by
7302 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7303 public static class RequestInfoPerUidCounter extends PerUidCounter {
7304 RequestInfoPerUidCounter(int maxCountPerUid) {
7305 super(maxCountPerUid);
7306 }
7307
7308 @Override
7309 public synchronized void incrementCountOrThrow(int uid) {
7310 try {
7311 super.incrementCountOrThrow(uid);
7312 } catch (IllegalStateException e) {
7313 throw new ServiceSpecificException(
7314 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7315 "Uid " + uid + " exceeded its allotted requests limit");
7316 }
7317 }
7318
7319 @Override
7320 public synchronized void decrementCountOrThrow(int uid) {
7321 throw new UnsupportedOperationException("Use decrementCount instead.");
7322 }
7323
7324 public synchronized void decrementCount(int uid) {
7325 try {
7326 super.decrementCountOrThrow(uid);
7327 } catch (IllegalStateException e) {
7328 logwtf("Exception when decrement per uid request count: ", e);
7329 }
7330 }
7331 }
7332
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007333 // This checks that the passed capabilities either do not request a
7334 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007335 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007336 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09007337 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007338 throw new SecurityException("Insufficient permissions to request a specific SSID");
7339 }
paulhu1a407652019-03-22 16:35:06 +08007340
7341 if (nc.hasSignalStrength()
7342 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
7343 throw new SecurityException(
7344 "Insufficient permissions to request a specific signal strength");
7345 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007346 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007347
junyulai2217bec2021-04-14 23:33:31 +08007348 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07007349 enforceNetworkFactoryPermission();
7350 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007351 }
7352
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007353 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007354 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007355 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007356 // mNetworkRequests may contain the same value multiple times in case of
7357 // multilayer requests. It won't matter in this case because the thresholds
7358 // will then be the same and be deduplicated as they enter the `thresholds` set.
7359 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007360 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7361 for (final NetworkRequest req : nri.mRequests) {
7362 if (req.networkCapabilities.hasSignalStrength()
7363 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7364 thresholds.add(req.networkCapabilities.getSignalStrength());
7365 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007366 }
7367 }
7368 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007369 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007370 }
7371
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007372 private void updateSignalStrengthThresholds(
7373 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007374 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007375
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007376 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007377 String detail;
7378 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7379 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7380 } else {
7381 detail = reason;
7382 }
7383 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007384 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007385 }
7386
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007387 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007388 }
7389
Chalard Jeandd421992021-12-16 23:16:02 +09007390 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007391 if (nc == null) {
7392 return;
7393 }
7394 NetworkSpecifier ns = nc.getNetworkSpecifier();
7395 if (ns == null) {
7396 return;
7397 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007398 if (ns instanceof MatchAllNetworkSpecifier) {
7399 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7400 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007401 }
7402
Chalard Jeandd421992021-12-16 23:16:02 +09007403 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007404 ensureValidNetworkSpecifier(nc);
7405 if (nc.isPrivateDnsBroken()) {
7406 throw new IllegalArgumentException("Can't request broken private DNS");
7407 }
Chalard Jeande665262022-02-25 16:12:12 +09007408 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007409 throw new IllegalArgumentException("Can't request access UIDs");
7410 }
lucasline117e2e2019-10-22 18:27:33 +08007411 }
7412
Chalard Jeandd421992021-12-16 23:16:02 +09007413 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7414 ensureListenableCapabilities(nc);
7415 final String badCapability = nc.describeFirstNonRequestableCapability();
7416 if (badCapability != null) {
7417 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7418 }
7419 }
7420
Chiachang Wang3bc52762021-11-25 14:17:57 +08007421 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7422 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007423 private boolean isTargetSdkAtleast(int version, int callingUid,
7424 @NonNull String callingPackageName) {
7425 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007426 final PackageManager pm =
7427 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007428 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007429 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007430 if (callingVersion < version) return false;
7431 } catch (PackageManager.NameNotFoundException e) { }
7432 return true;
7433 }
7434
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007435 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007436 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007437 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007438 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007439 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08007440 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007441 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7442 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007443 throw new SecurityException("Insufficient permissions to specify legacy type");
7444 }
markchienfac84a22020-03-18 21:16:15 +08007445 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007446 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007447 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007448 // Privileged callers can track the default network of another UID by passing in a UID.
7449 if (asUid != Process.INVALID_UID) {
7450 enforceSettingsPermission();
7451 } else {
7452 asUid = callingUid;
7453 }
junyulaiad010792021-01-11 16:53:38 +08007454 final NetworkRequest.Type reqType;
7455 try {
7456 reqType = NetworkRequest.Type.values()[reqTypeInt];
7457 } catch (ArrayIndexOutOfBoundsException e) {
7458 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7459 }
7460 switch (reqType) {
7461 case TRACK_DEFAULT:
7462 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007463 // is unused and will be replaced by ones appropriate for the UID (usually, the
7464 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007465 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007466 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007467 enforceAccessPermission();
7468 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007469 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007470 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007471 networkCapabilities = new NetworkCapabilities(defaultNc);
7472 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007473 case BACKGROUND_REQUEST:
7474 enforceNetworkStackOrSettingsPermission();
7475 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007476 case REQUEST:
7477 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7478 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007479 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007480 // TODO: this is incorrect. We mark the request as metered or not depending on
7481 // the state of the app when the request is filed, but we never change the
7482 // request if the app changes network state. http://b/29964605
7483 enforceMeteredApnPolicy(networkCapabilities);
7484 break;
junyulai1b1c8742021-03-12 20:05:08 +08007485 case LISTEN_FOR_BEST:
7486 enforceAccessPermission();
7487 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7488 break;
junyulaiad010792021-01-11 16:53:38 +08007489 default:
7490 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007491 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007492 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007493 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007494 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007495
junyulai1b1c8742021-03-12 20:05:08 +08007496 // Enforce FOREGROUND if the caller does not have permission to use background network.
7497 if (reqType == LISTEN_FOR_BEST) {
7498 restrictBackgroundRequestForCaller(networkCapabilities);
7499 }
7500
7501 // Set the UID range for this request to the single UID of the requester, unless the
7502 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007503 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7504 // are no visible methods to set the UIDs, an app could use reflection to try and get
7505 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007506 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007507 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7508 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007509
Etan Cohen85000162017-02-05 10:42:27 -08007510 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007511 throw new IllegalArgumentException("Bad timeout specified");
7512 }
Etan Cohen9786d922015-11-18 10:56:15 -08007513
James Mattis3ce3d3c2021-02-09 18:18:28 -08007514 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007515 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007516 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007517 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007518 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007519 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007520
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007521 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7522 // copied from the default request above. (This is necessary to ensure, for example, that
7523 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7524 // changes don't alter request matching.
7525 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7526 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007527 throw new IllegalStateException(
7528 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007529 + networkCapabilities + " vs. " + defaultNc);
7530 }
7531
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007532 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007533 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007534 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007535 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007536 }
7537 return networkRequest;
7538 }
7539
James Mattis3ce3d3c2021-02-09 18:18:28 -08007540 /**
7541 * Return the nri to be used when registering a network request. Specifically, this is used with
7542 * requests registered to track the default request. If there is currently a per-app default
7543 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7544 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007545 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7546 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007547 * @param nr the network request for the nri.
7548 * @param msgr the messenger for the nri.
7549 * @param binder the binder for the nri.
7550 * @param callingAttributionTag the calling attribution tag for the nri.
7551 * @return the nri to register.
7552 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007553 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007554 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007555 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007556 @Nullable String callingAttributionTag) {
7557 final List<NetworkRequest> requests;
7558 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7559 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007560 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007561 } else {
7562 requests = Collections.singletonList(nr);
7563 }
Roshan Pius951c0032020-12-22 15:10:42 -08007564 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007565 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007566 }
7567
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007568 private boolean shouldCheckCapabilitiesDeclaration(
7569 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7570 @NonNull final String callingPackageName) {
7571 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7572 // Only run the check if the change is enabled.
7573 if (!mDeps.isChangeEnabled(
7574 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7575 callingPackageName, user)) {
7576 return false;
7577 }
7578
7579 return networkCapabilities.hasCapability(
7580 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7581 || networkCapabilities.hasCapability(
7582 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7583 }
7584
7585 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
7586 @NonNull final NetworkCapabilities networkCapabilities) {
7587 // This check is added to fix the linter error for "current min is 30", which is not going
7588 // to happen because Connectivity service always run in S+.
Chalard Jean03552c42023-05-29 17:02:43 +09007589 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007590 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7591 return;
7592 }
7593 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007594 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007595 try {
7596 synchronized (mSelfCertifiedCapabilityCache) {
7597 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7598 callerPackageName);
7599 if (applicationNetworkCapabilities == null) {
7600 final PackageManager packageManager = mContext.getPackageManager();
7601 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7602 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7603 callerPackageName
7604 );
7605 final XmlResourceParser parser = packageManager
7606 .getResourcesForApplication(callerPackageName)
7607 .getXml(networkSliceProperty.getResourceId());
7608 applicationNetworkCapabilities =
7609 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7610 mSelfCertifiedCapabilityCache.put(callerPackageName,
7611 applicationNetworkCapabilities);
7612 }
7613
7614 }
7615 } catch (PackageManager.NameNotFoundException ne) {
7616 throw new SecurityException(
7617 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7618 + " property");
7619 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7620 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007621 } finally {
7622 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007623 }
7624
7625 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7626 networkCapabilities);
7627 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007628 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007629 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007630 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7631 callingPackageName)) {
7632 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities);
7633 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007634 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007635 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7636 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7637 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7638 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007639 }
junyulai96bd9fe2022-03-08 17:36:42 +08007640 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007641 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007642 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007643 }
7644 }
7645
fenglu3f357402015-03-20 11:29:56 -07007646 @Override
fenglub00f4882015-04-21 17:12:05 -07007647 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007648 enforceAccessPermission();
7649 NetworkAgentInfo nai = null;
7650 if (network == null) {
7651 return false;
7652 }
7653 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007654 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007655 }
7656 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007657 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007658 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007659 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007660 Integer uidReqs = mBandwidthRequests.get(uid);
7661 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007662 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007663 }
7664 mBandwidthRequests.put(uid, ++uidReqs);
7665 }
fenglu3f357402015-03-20 11:29:56 -07007666 return true;
7667 }
7668 return false;
7669 }
7670
Felipe Leme0a5ae422016-06-20 16:36:29 -07007671 private boolean isSystem(int uid) {
7672 return uid < Process.FIRST_APPLICATION_UID;
7673 }
fenglu3f357402015-03-20 11:29:56 -07007674
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007675 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007676 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007677 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007678 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007679 return;
7680 }
Hugo Benichi39621362017-02-11 17:04:43 +09007681 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7682 // Policy already enforced.
7683 return;
7684 }
paulhuaf50d7d2020-12-24 19:47:34 +08007685 final long ident = Binder.clearCallingIdentity();
7686 try {
7687 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7688 // If UID is restricted, don't allow them to bring up metered APNs.
7689 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7690 }
7691 } finally {
7692 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007693 }
7694 }
7695
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007696 @Override
7697 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007698 PendingIntent operation, @NonNull String callingPackageName,
7699 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007700 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007701 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007702 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007703 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007704 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007705 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007706 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007707 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007708 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007709 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7710 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007711
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007712 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007713 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007714 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7715 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007716 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007717 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7718 nri));
7719 return networkRequest;
7720 }
7721
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007722 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7723 mHandler.sendMessageDelayed(
7724 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007725 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007726 }
7727
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007728 @Override
7729 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007730 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007731 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007732 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007733 }
7734
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007735 // In order to implement the compatibility measure for pre-M apps that call
7736 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7737 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7738 // This ensures it has permission to do so.
7739 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7740 if (nc == null) {
7741 return false;
7742 }
7743 int[] transportTypes = nc.getTransportTypes();
7744 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7745 return false;
7746 }
7747 try {
7748 mContext.enforceCallingOrSelfPermission(
7749 android.Manifest.permission.ACCESS_WIFI_STATE,
7750 "ConnectivityService");
7751 } catch (SecurityException e) {
7752 return false;
7753 }
7754 return true;
7755 }
7756
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007757 @Override
7758 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007759 Messenger messenger, IBinder binder,
7760 @NetworkCallback.Flag int callbackFlags,
7761 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007762 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007763 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7764 enforceAccessPermission();
7765 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007766
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007767 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007768 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007769 Binder.getCallingPid(), callingUid, callingPackageName);
7770 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007771 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7772 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7773 // onLost and onAvailable callbacks when networks move in and out of the background.
7774 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7775 // can't request networks.
7776 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007777 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007778
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007779 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007780 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007781 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007782 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007783 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007784 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007785
7786 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7787 return networkRequest;
7788 }
7789
7790 @Override
7791 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007792 PendingIntent operation, @NonNull String callingPackageName,
7793 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007794 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007795 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007796 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7797 enforceAccessPermission();
7798 }
Chalard Jeandd421992021-12-16 23:16:02 +09007799 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007800 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007801 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007802 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007803 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007804
7805 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007806 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007807 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7808 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007809 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007810
WeiZhang1cc3f172021-06-03 19:02:04 -05007811 mHandler.sendMessage(mHandler.obtainMessage(
7812 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007813 }
7814
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007815 /** Returns the next Network provider ID. */
7816 public final int nextNetworkProviderId() {
7817 return mNextNetworkProviderId.getAndIncrement();
7818 }
7819
Erik Kline0c04b742016-07-07 16:50:58 +09007820 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007821 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007822 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007823 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007824 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007825 }
7826
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007827 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7828 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007829 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7830 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7831 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007832 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007833 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007834 return;
7835 }
7836
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007837 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7838 mNetworkProviderInfos.put(npi.messenger, npi);
7839 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007840 }
7841
7842 @Override
7843 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007844 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007845 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007846 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007847 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007848 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7849 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007850 }
7851
7852 @Override
7853 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007854 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007855 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007856 }
7857
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007858 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007859 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007860 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7861 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007862 Objects.requireNonNull(score);
7863 Objects.requireNonNull(caps);
7864 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007865 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007866 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007867 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7868 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007869 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7870 }
7871
Chalard Jeanbb902a52021-08-18 01:35:19 +09007872 private void updateOfferScore(final NetworkOffer offer) {
7873 final boolean yieldToBadWiFi =
7874 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7875 final NetworkOffer newOffer = new NetworkOffer(
7876 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7877 offer.caps, offer.callback, offer.providerId);
7878 if (offer.equals(newOffer)) return;
7879 handleRegisterNetworkOffer(newOffer);
7880 }
7881
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007882 @Override
7883 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007884 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007885 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7886 }
7887
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007888 private void handleUnregisterNetworkProvider(Messenger messenger) {
7889 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7890 if (npi == null) {
7891 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007892 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007893 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007894 // Unregister all the offers from this provider
7895 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7896 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007897 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007898 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7899 toRemove.add(noi);
7900 }
7901 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007902 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007903 handleUnregisterNetworkOffer(noi);
7904 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007905 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007906 }
7907
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007908 @Override
James Mattisf7027322020-12-13 16:28:14 -08007909 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007910 if (request.hasTransport(TRANSPORT_TEST)) {
7911 enforceNetworkFactoryOrTestNetworksPermission();
7912 } else {
7913 enforceNetworkFactoryPermission();
7914 }
James Mattisf7027322020-12-13 16:28:14 -08007915 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7916 if (nri != null) {
7917 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7918 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7919 mHandler.post(() -> handleReleaseNetworkRequest(
7920 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7921 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007922 }
7923
Paul Jensen1f567382015-02-13 14:18:39 -05007924 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7925 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007926 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007927 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007928 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007929 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007930 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007931
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007932 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007933 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007934 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007935
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007936 // UID ranges for users that are currently blocked by VPNs.
7937 // This array is accessed and iterated on multiple threads without holding locks, so its
7938 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7939 // (on the handler thread).
7940 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7941
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007942 // Must only be accessed on the handler thread
7943 @NonNull
7944 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7945
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007946 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007947 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007948
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007949 // Current OEM network preferences. This object must only be written to on the handler thread.
7950 // Since it is immutable and always non-null, other threads may read it if they only care
7951 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007952 @NonNull
7953 private OemNetworkPreferences mOemNetworkPreferences =
7954 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007955 // Current per-profile network preferences. This object follows the same threading rules as
7956 // the OEM network preferences above.
7957 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007958 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7959 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007960
lucaslin3ba7cc22022-12-19 02:35:33 +00007961 // Current VPN network preferences. This object follows the same threading rules as the OEM
7962 // network preferences above.
7963 @NonNull
7964 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7965 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7966
paulhu51f77dc2021-06-07 02:34:20 +00007967 // A set of UIDs that should use mobile data preferentially if available. This object follows
7968 // the same threading rules as the OEM network preferences above.
7969 @NonNull
7970 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7971
James Mattiscb1e0362021-04-06 17:07:42 -07007972 // OemNetworkPreferences activity String log entries.
7973 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7974 @NonNull
7975 private final LocalLog mOemNetworkPreferencesLogs =
7976 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7977
James Mattis02220e22021-03-13 19:27:21 -08007978 /**
7979 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7980 * @param packageName the package name to check existence of a mapping for.
7981 * @return true if a mapping exists, false otherwise
7982 */
7983 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7984 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7985 }
7986
James Mattise3ef1912020-12-20 11:09:58 -08007987 // The always-on request for an Internet-capable network that apps without a specific default
7988 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007989 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007990 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007991 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007992 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007993 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007994 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007995 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007996
James Mattisd31bdfa2020-12-23 16:37:26 -08007997 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7998 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7999 }
8000
8001 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08008002 * Return the default network request currently tracking the given uid.
8003 * @param uid the uid to check.
8004 * @return the NetworkRequestInfo tracking the given uid.
8005 */
8006 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08008007 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008008 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008009 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008010 // Checking the first request is sufficient as only multilayer requests will have more
8011 // than one request and for multilayer, all requests will track the same uids.
8012 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08008013 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08008014 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008015 highestPriorityNri = nri;
8016 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08008017 }
8018 }
paulhuaa0743d2021-05-26 21:56:03 +08008019 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008020 }
8021
8022 /**
8023 * Get a copy of the network requests of the default request that is currently tracking the
8024 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008025 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8026 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008027 * @param requestorUid the uid to check the default for.
8028 * @param requestorPackageName the requestor's package name.
8029 * @return a copy of the default's NetworkRequest that is tracking the given uid.
8030 */
8031 @NonNull
8032 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008033 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008034 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008035 getDefaultRequestTrackingUid(asUid).mRequests,
8036 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008037 }
8038
8039 /**
8040 * Copy the given nri's NetworkRequest collection.
8041 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008042 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8043 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008044 * @param requestorUid the uid to set on the copied collection.
8045 * @param requestorPackageName the package name to set on the copied collection.
8046 * @return the copied NetworkRequest collection.
8047 */
8048 @NonNull
8049 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008050 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
8051 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008052 final List<NetworkRequest> requests = new ArrayList<>();
8053 for (final NetworkRequest nr : requestsToCopy) {
8054 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008055 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08008056 nr.legacyType, nextNetworkRequestId(), nr.type));
8057 }
8058 return requests;
8059 }
8060
8061 @NonNull
8062 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008063 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
8064 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09008065 // These capabilities are for a TRACK_DEFAULT callback, so:
8066 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
8067 // mDefaultRequest and a per-UID default request.
8068 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008069 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09008070 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008071 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
8072 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008073 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008074 restrictRequestUidsForCallerAndSetRequestorInfo(
8075 netCap, requestorUid, requestorPackageName);
8076 return netCap;
8077 }
8078
8079 /**
8080 * Get the nri that is currently being tracked for callbacks by per-app defaults.
8081 * @param nr the network request to check for equality against.
8082 * @return the nri if one exists, null otherwise.
8083 */
8084 @Nullable
8085 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
8086 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8087 if (nri.getNetworkRequestForCallback().equals(nr)) {
8088 return nri;
8089 }
8090 }
8091 return null;
8092 }
8093
8094 /**
8095 * Check if an nri is currently being managed by per-app default networking.
8096 * @param nri the nri to check.
8097 * @return true if this nri is currently being managed by per-app default networking.
8098 */
8099 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
8100 // nri.mRequests.get(0) is only different from the original request filed in
8101 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
8102 // functionality therefore if these two don't match, it means this particular nri is
8103 // currently being managed by a per-app default.
8104 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
8105 }
8106
8107 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08008108 * Determine if an nri is a managed default request that disallows default networking.
8109 * @param nri the request to evaluate
8110 * @return true if device-default networking is disallowed
8111 */
8112 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
8113 // Check if this nri is a managed default that supports the default network at its
8114 // lowest priority request.
8115 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
8116 final NetworkCapabilities lowestPriorityNetCap =
8117 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
8118 return isPerAppDefaultRequest(nri)
8119 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
8120 lowestPriorityNetCap));
8121 }
8122
Erik Kline05f2b402015-04-30 12:58:40 +09008123 // Request used to optionally keep mobile data active even when higher
8124 // priority networks like Wi-Fi are active.
8125 private final NetworkRequest mDefaultMobileDataRequest;
8126
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07008127 // Request used to optionally keep wifi data active even when higher
8128 // priority networks like ethernet are active.
8129 private final NetworkRequest mDefaultWifiRequest;
8130
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08008131 // Request used to optionally keep vehicle internal network always active
8132 private final NetworkRequest mDefaultVehicleRequest;
8133
James Mattisd31bdfa2020-12-23 16:37:26 -08008134 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8135 // network with no service. This NAI should never be matched against, nor should any public API
8136 // ever return the associated network. For this reason, this NAI is not in the list of available
8137 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8138 // default requests that don't support using the device default network which will ultimately
8139 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8140 @VisibleForTesting
8141 final NetworkAgentInfo mNoServiceNetwork;
8142
Chalard Jean5b409c72021-02-04 13:12:59 +09008143 // The NetworkAgentInfo currently satisfying the default request, if any.
8144 private NetworkAgentInfo getDefaultNetwork() {
8145 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008146 }
8147
James Mattis2516da32021-01-31 17:06:19 -08008148 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008149 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008150 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8151 // Currently, all network requests will have the same uids therefore checking the first
8152 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008153 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008154 if (null == uids) {
8155 continue;
8156 }
8157 for (final UidRange range : uids) {
8158 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008159 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008160 highestPriorityNri = nri;
8161 }
James Mattis2516da32021-01-31 17:06:19 -08008162 }
8163 }
8164 }
paulhuaa0743d2021-05-26 21:56:03 +08008165 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008166 }
8167
Varun Ananddf569952019-02-06 10:13:38 -08008168 @Nullable
8169 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8170 return nai != null ? nai.network : null;
8171 }
8172
8173 private void ensureRunningOnConnectivityServiceThread() {
8174 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8175 throw new IllegalStateException(
8176 "Not running on ConnectivityService thread: "
8177 + Thread.currentThread().getName());
8178 }
8179 }
8180
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008181 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008182 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8183 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008184 }
8185
Chalard Jean29d06db2018-05-02 21:14:54 +09008186 /**
8187 * Register a new agent with ConnectivityService to handle a network.
8188 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008189 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008190 * @param networkInfo the initial info associated with this network. It can be updated later :
8191 * see {@link #updateNetworkInfo}.
8192 * @param linkProperties the initial link properties of this network. They can be updated
8193 * later : see {@link #updateLinkProperties}.
8194 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008195 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008196 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008197 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008198 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008199 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008200 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008201 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09008202 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09008203 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
8204 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008205 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8206 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8207 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008208 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008209 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008210 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008211 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008212 } else {
8213 enforceNetworkFactoryPermission();
8214 }
8215
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008216 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008217 final long token = Binder.clearCallingIdentity();
8218 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008219 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09008220 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008221 } finally {
8222 Binder.restoreCallingIdentity(token);
8223 }
8224 }
8225
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008226 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008227 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09008228 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
8229 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008230
Chalard Jeandbc46952022-02-02 00:14:18 +09008231 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8232 // and mutate them at any time.
8233 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8234 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8235 final LinkProperties lpCopy = new LinkProperties(linkProperties);
8236
Chalard Jean366c5252022-01-25 18:27:53 +09008237 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008238 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008239 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8240 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008241 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008242 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09008243 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09008244 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
8245 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008246
Chalard Jeandbc46952022-02-02 00:14:18 +09008247 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008248 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008249 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008250 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008251 mDeps.getNetworkStack().makeNetworkMonitor(
8252 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008253 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8254 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008255 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008256 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008257 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008258 }
8259
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008260 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008261 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008262 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008263 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008264 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008265 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8266 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8267 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008268
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008269 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008270
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008271 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008272 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008273 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008274 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008275
8276 try {
8277 networkMonitor.start();
8278 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008279 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008280 }
Chalard Jean366c5252022-01-25 18:27:53 +09008281
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008282 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008283 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008284 updateNetworkInfo(nai, networkInfo);
Tommy Webb34f81dc2023-02-20 14:10:55 -05008285 updateDisallowedUidsForNetwork(nai);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008286 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008287 }
8288
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008289 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8290 @NonNull public final NetworkOffer offer;
8291
8292 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8293 this.offer = offer;
8294 }
8295
8296 @Override
8297 public void binderDied() {
8298 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8299 }
8300 }
8301
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008302 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8303 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8304 if (npi.providerId == providerId) return true;
8305 }
8306 return false;
8307 }
8308
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008309 /**
8310 * Register or update a network offer.
8311 * @param newOffer The new offer. If the callback member is the same as an existing
8312 * offer, it is an update of that offer.
8313 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008314 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008315 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8316 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008317 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008318 // This may actually happen if a provider updates its score or registers and then
8319 // immediately unregisters. The offer would still be in the handler queue, but the
8320 // provider would have been removed.
8321 if (DBG) log("Received offer from an unregistered provider");
8322 return;
8323 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008324 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8325 if (null != existingOffer) {
8326 handleUnregisterNetworkOffer(existingOffer);
8327 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008328 if (DBG) {
8329 // handleUnregisterNetworkOffer has already logged the old offer
8330 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8331 }
8332 } else {
8333 if (DBG) {
8334 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8335 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008336 }
8337 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8338 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008339 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008340 } catch (RemoteException e) {
8341 noi.binderDied();
8342 return;
8343 }
8344 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008345 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008346 }
8347
8348 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8349 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008350 if (DBG) {
8351 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8352 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008353
8354 // If the provider removes the offer and dies immediately afterwards this
8355 // function may be called twice in a row, but the array will no longer contain
8356 // the offer.
8357 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008358 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008359 }
8360
8361 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8362 @NonNull final INetworkOfferCallback callback) {
8363 ensureRunningOnConnectivityServiceThread();
8364 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008365 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008366 }
8367 return null;
8368 }
8369
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008370 /**
8371 * Called when receiving LinkProperties directly from a NetworkAgent.
8372 * Stores into |nai| any data coming from the agent that might also be written to the network's
8373 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8374 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008375 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008376 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008377 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8378 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008379 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008380 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008381 }
8382
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008383 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008384 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008385 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008386
Lorenzo Colittid523d142020-04-01 20:16:30 +09008387 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8388 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8389 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008390 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008391
Suprabh Shukla1e312032023-01-24 03:36:37 -08008392 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008393
8394 // update filtering rules, need to happen after the interface update so netd knows about the
8395 // new interface (the interface name -> index map becomes initialized)
8396 updateVpnFiltering(newLp, oldLp, networkAgent);
8397
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008398 updateMtu(newLp, oldLp);
8399 // TODO - figure out what to do for clat
8400// for (LinkProperties lp : newLp.getStackedLinks()) {
8401// updateMtu(lp, null);
8402// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008403 if (isDefaultNetwork(networkAgent)) {
Aaron Huang25ef1712021-06-08 13:11:45 +08008404 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008405 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8406 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008407
Erik Klineb9888902016-04-05 13:30:49 +09008408 updateRoutes(newLp, oldLp, netId);
8409 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008410 // Make sure LinkProperties represents the latest private DNS status.
8411 // This does not need to be done before updateDnses because the
8412 // LinkProperties are not the source of the private DNS configuration.
8413 // updateDnses will fetch the private DNS configuration from DnsManager.
8414 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008415
Chalard Jean5b409c72021-02-04 13:12:59 +09008416 if (isDefaultNetwork(networkAgent)) {
Aaron Huang25ef1712021-06-08 13:11:45 +08008417 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09008418 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008419 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008420 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008421
8422 updateWakeOnLan(newLp);
8423
Hai Shalome58bdc62021-01-11 18:45:34 -08008424 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8425 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8426 // does, it needs to be merged here.
8427 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8428 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008429
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008430 // TODO - move this check to cover the whole function
8431 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008432 synchronized (networkAgent) {
8433 networkAgent.linkProperties = newLp;
8434 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008435 // Start or stop DNS64 detection and 464xlat according to network state.
8436 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008437 // Notify NSS when relevant events happened. Currently, NSS only cares about
8438 // interface changed to update clat interfaces accounting.
8439 final boolean interfacesChanged = oldLp == null
8440 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8441 if (interfacesChanged) {
8442 notifyIfacesChangedForNetworkStats();
8443 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008444 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8445 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008446 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008447 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008448
8449 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008450 }
8451
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +09008452 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8453 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8454 }
8455
Hai Shalome58bdc62021-01-11 18:45:34 -08008456 /**
8457 * @param naData captive portal data from NetworkAgent
8458 * @param apiData captive portal data from capport API
8459 */
8460 @Nullable
8461 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8462 CaptivePortalData apiData) {
8463 if (naData == null || apiData == null) {
8464 return naData == null ? apiData : naData;
8465 }
8466 final CaptivePortalData.Builder captivePortalBuilder =
8467 new CaptivePortalData.Builder(naData);
8468
8469 if (apiData.isCaptive()) {
8470 captivePortalBuilder.setCaptive(true);
8471 }
8472 if (apiData.isSessionExtendable()) {
8473 captivePortalBuilder.setSessionExtendable(true);
8474 }
8475 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8476 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8477 // otherwise data would be inconsistent. Prefer the capport API info if present,
8478 // as it can generally be refreshed more often.
8479 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8480 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8481 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8482 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8483 // No source has time / bytes remaining information: surface the newest refresh time
8484 // for other fields
8485 captivePortalBuilder.setRefreshTime(
8486 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8487 }
8488
Hai Shalom7c6ab402021-02-04 19:34:06 -08008489 // Prioritize the user portal URL from the network agent if the source is authenticated.
8490 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8491 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8492 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8493 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008494 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008495 // Prioritize the venue information URL from the network agent if the source is
8496 // authenticated.
8497 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8498 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8499 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8500 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008501 }
8502 return captivePortalBuilder.build();
8503 }
8504
Suprabh Shukla619549f2023-04-26 18:47:36 -07008505 @VisibleForTesting
8506 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008507 // This needs to be kept in sync and backwards compatible with the decoding logic in
8508 // NetdEventListenerService, which is non-mainline code.
8509 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8510 }
8511
Suprabh Shukla63e59342023-04-25 23:15:43 -07008512 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8513 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8514 return true;
8515 }
8516 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8517 return true;
8518 }
8519 return false;
8520 }
8521
Suprabh Shukla1e312032023-01-24 03:36:37 -08008522 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008523 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008524 // marks on unsupported interfaces is harmless.
Suprabh Shukla63e59342023-04-25 23:15:43 -07008525 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008526 return;
8527 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008528
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008529 // Mask/mark of zero will not detect anything interesting.
8530 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskif310a142023-06-05 07:29:28 +00008531 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008532 return;
8533 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008534
Suprabh Shukla1e312032023-01-24 03:36:37 -08008535 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008536 try {
8537 if (add) {
Maciej Żenczykowskif310a142023-06-05 07:29:28 +00008538 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008539 } else {
Maciej Żenczykowskif310a142023-06-05 07:29:28 +00008540 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008541 }
8542 } catch (Exception e) {
8543 loge("Exception modifying wakeup packet monitoring: " + e);
8544 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008545 }
8546
Junyu Lai970963e2022-10-25 15:46:47 +08008547 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008548 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008549 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008550 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008551 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008552 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008553 for (final String iface : interfaceDiff.added) {
8554 try {
8555 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008556 mNetd.networkAddInterface(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008557 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008558 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008559 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008560 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008561 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008562 }
Paul Jensenbff73492014-04-28 10:33:11 -04008563 }
8564 }
Chalard Jean9589e722019-11-19 19:03:53 +09008565 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008566 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008567 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008568 wakeupModifyInterface(iface, nai, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08008569 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008570 } catch (Exception e) {
8571 loge("Exception removing interface: " + e);
8572 }
8573 }
8574 }
8575
Tyler Weare4314862019-12-05 14:55:30 -08008576 // TODO: move to frameworks/libs/net.
8577 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
8578 final String nextHop;
8579
8580 switch (route.getType()) {
8581 case RouteInfo.RTN_UNICAST:
8582 if (route.hasGateway()) {
8583 nextHop = route.getGateway().getHostAddress();
8584 } else {
8585 nextHop = INetd.NEXTHOP_NONE;
8586 }
8587 break;
8588 case RouteInfo.RTN_UNREACHABLE:
8589 nextHop = INetd.NEXTHOP_UNREACHABLE;
8590 break;
8591 case RouteInfo.RTN_THROW:
8592 nextHop = INetd.NEXTHOP_THROW;
8593 break;
8594 default:
8595 nextHop = INetd.NEXTHOP_NONE;
8596 break;
8597 }
8598
8599 final RouteInfoParcel rip = new RouteInfoParcel();
8600 rip.ifName = route.getInterface();
8601 rip.destination = route.getDestination().toString();
8602 rip.nextHop = nextHop;
8603 rip.mtu = route.getMtu();
8604
8605 return rip;
8606 }
8607
Paul Jensene0fd4a82014-08-06 15:51:33 -04008608 /**
8609 * Have netd update routes from oldLp to newLp.
8610 * @return true if routes changed between oldLp and newLp
8611 */
Junyu Lai970963e2022-10-25 15:46:47 +08008612 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8613 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008614 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008615 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8616 new CompareOrUpdateResult<>(
8617 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008618 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008619 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008620
8621 // add routes before removing old in case it helps with continuous connectivity
8622
Chalard Jean9dd11612018-06-04 16:52:49 +09008623 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008624 for (RouteInfo route : routeDiff.added) {
8625 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008626 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008627 try {
Tyler Weare4314862019-12-05 14:55:30 -08008628 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008629 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008630 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008631 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008632 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008633 }
8634 }
8635 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008636 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.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008642 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008643 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008644 }
8645 }
8646
8647 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008648 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008649 try {
Tyler Weare4314862019-12-05 14:55:30 -08008650 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008651 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08008652 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008653 }
8654 }
Tyler Weare4314862019-12-05 14:55:30 -08008655
8656 for (RouteInfo route : routeDiff.updated) {
8657 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8658 try {
8659 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
8660 } catch (Exception e) {
8661 loge("Exception in networkUpdateRouteParcel: " + e);
8662 }
8663 }
8664 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8665 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008666 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008667
Junyu Lai970963e2022-10-25 15:46:47 +08008668 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8669 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008670 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8671 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008672 }
Erik Klineb9888902016-04-05 13:30:49 +09008673
Erik Kline31b4a9e2018-01-11 21:07:29 +09008674 if (DBG) {
8675 final Collection<InetAddress> dnses = newLp.getDnsServers();
8676 log("Setting DNS servers for network " + netId + " to " + dnses);
8677 }
Erik Klineb9888902016-04-05 13:30:49 +09008678 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008679 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008680 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008681 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008682 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008683 }
Erik Kline54e35c02017-04-07 15:29:29 +09008684 }
8685
Junyu Lai970963e2022-10-25 15:46:47 +08008686 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8687 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008688 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8689 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008690 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8691 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008692
8693 if (!wasFiltering && !needsFiltering) {
8694 // Nothing to do.
8695 return;
8696 }
8697
8698 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8699 // Nothing changed.
8700 return;
8701 }
8702
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008703 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008704 if (ranges == null || ranges.isEmpty()) {
8705 return;
8706 }
8707
Qingxi Libb8da982020-01-17 17:54:27 -08008708 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008709 // TODO: this create a window of opportunity for apps to receive traffic between the time
8710 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008711 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008712 // old rules are being removed.
8713 if (wasFiltering) {
8714 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8715 }
8716 if (needsFiltering) {
8717 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8718 }
8719 }
8720
Valentin Iftime9fa35092019-09-24 13:32:13 +02008721 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008722 if (mWolSupportedInterfaces == null) {
8723 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008724 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008725 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008726 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8727 }
8728
Luke Huangb913c812018-08-24 20:33:16 +08008729 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008730 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008731 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008732 }
8733 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008734 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008735 }
Luke Huangb913c812018-08-24 20:33:16 +08008736 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008737 }
8738
Chalard Jean62edfd82019-12-02 18:39:29 +09008739 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8740 @NonNull final NetworkCapabilities newNc) {
8741 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8742 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008743 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008744 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008745 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008746 } catch (RemoteException | ServiceSpecificException e) {
8747 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008748 }
8749 }
8750 }
8751
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008752 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008753 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008754 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008755 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008756 underlyingNetworks = underlyingNetworksOrDefault(
8757 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008758 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008759 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8760 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008761 // metered if any underlying is metered, or originally declared metered by the agent.
8762 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008763 boolean roaming = false; // roaming if any underlying is roaming
8764 boolean congested = false; // congested if any underlying is congested
8765 boolean suspended = true; // suspended if all underlying are suspended
8766
8767 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008768 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008769 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008770 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008771 for (Network underlyingNetwork : underlyingNetworks) {
8772 final NetworkAgentInfo underlying =
8773 getNetworkAgentInfoForNetwork(underlyingNetwork);
8774 if (underlying == null) continue;
8775
8776 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8777 hadUnderlyingNetworks = true;
8778 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008779 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008780 }
8781
8782 // Merge capabilities of this underlying network. For bandwidth, assume the
8783 // worst case.
8784 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8785 underlyingCaps.getLinkDownstreamBandwidthKbps());
8786 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8787 underlyingCaps.getLinkUpstreamBandwidthKbps());
8788 // If this underlying network is metered, the VPN is metered (it may cost money
8789 // to send packets on this network).
8790 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8791 // If this underlying network is roaming, the VPN is roaming (the billing structure
8792 // is different than the usual, local one).
8793 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8794 // If this underlying network is congested, the VPN is congested (the current
8795 // condition of the network affects the performance of this network).
8796 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8797 // If this network is not suspended, the VPN is not suspended (the VPN
8798 // is able to transfer some data).
8799 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008800 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008801 }
8802 }
8803 if (!hadUnderlyingNetworks) {
8804 // No idea what the underlying networks are; assume reasonable defaults
8805 metered = true;
8806 roaming = false;
8807 congested = false;
8808 suspended = false;
8809 }
8810
Chalard Jean1d420b32022-10-12 16:39:37 +09008811 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008812 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8813 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8814 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8815 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8816 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8817 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008818 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008819 }
8820
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008821 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008822 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8823 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8824 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008825 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008826 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008827 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008828 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008829 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8830 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008831 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008832 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008833 if (nai.everConnected()
8834 && !nai.isVPN()
8835 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008836 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008837 // does not cause any request (that is not a listen) currently matching that agent to
8838 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008839 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008840 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008841 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008842 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008843 }
8844
Paul Jensen53f08952015-06-16 14:27:36 -04008845 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008846 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008847 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008848 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008849 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008850 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008851 }
Chalard Jean254bd162022-08-25 13:04:51 +09008852 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008853 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008854 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008855 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008856 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008857 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008858 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008859 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008860 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008861 }
Chalard Jean254bd162022-08-25 13:04:51 +09008862 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008863 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8864 } else {
8865 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8866 }
lucasline117e2e2019-10-22 18:27:33 +08008867 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008868
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008869 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008870 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8871 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008872 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008873 }
8874
Lorenzo Colittibd079452021-07-02 11:47:57 +09008875 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008876 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008877 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008878 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008879 }
8880
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008881 return newNc;
8882 }
8883
Lorenzo Colitti44840702021-01-11 22:27:57 +09008884 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8885 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8886 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8887 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8888 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8889 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8890 if (prevSuspended != suspended) {
8891 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8892 // onResumed have been removed.
8893 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8894 : ConnectivityManager.CALLBACK_RESUMED);
8895 }
8896 if (prevSuspended != suspended || prevRoaming != roaming) {
8897 // updateNetworkInfo will mix in the suspended info from the capabilities and
8898 // take appropriate action for the network having possibly changed state.
8899 updateNetworkInfo(nai, nai.networkInfo);
8900 }
8901 }
8902
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008903 /**
8904 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8905 *
8906 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8907 * capabilities we manage and store in {@code nai}, such as validated status and captive
8908 * portal status)
8909 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8910 * potentially triggers rematches.
8911 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8912 * change.)
8913 *
8914 * @param oldScore score of the network before any of the changes that prompted us
8915 * to call this function.
8916 * @param nai the network having its capabilities updated.
8917 * @param nc the new network capabilities.
8918 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008919 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008920 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008921 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008922 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008923 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8924 if (null != differences) {
8925 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8926 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008927 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008928 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008929
Tommy Webb34f81dc2023-02-20 14:10:55 -05008930 if (prevNc != null && (!prevNc.equalsUids(newNc) || !prevNc.equalsTransportTypes(newNc))) {
8931 updateDisallowedUidsForNetwork(nai);
8932 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008933 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008934 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008935 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008936
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008937 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008938 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8939 // the change we're processing can't affect any requests, it can only affect the listens
8940 // on this network. We might have been called by rematchNetworkAndRequests when a
8941 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008942 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008943 } else {
8944 // If the requestable capabilities have changed or the score changed, we can't have been
8945 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008946 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008947 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008948 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008949 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008950
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008951 final boolean oldMetered = prevNc.isMetered();
8952 final boolean newMetered = newNc.isMetered();
8953 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008954
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008955 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008956 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8957 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008958 }
junyulaif2c67e42018-08-07 19:50:45 +08008959
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008960 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8961 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008962
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008963 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008964 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008965 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008966 }
8967
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008968 // This network might have been underlying another network. Propagate its capabilities.
8969 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008970
8971 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008972 mDnsManager.updateTransportsForNetwork(
8973 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008974 }
lucaslin53e8a262021-06-08 01:43:59 +08008975
8976 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008977 }
8978
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008979 /** Convenience method to update the capabilities for a given network. */
8980 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008981 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008982 }
8983
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008984 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008985 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008986 *
8987 * Ingress interface filtering enforces that all apps under the given network can only receive
8988 * packets from the network's interface (and loopback). This is important for VPNs because
8989 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8990 * non-VPN interfaces.
8991 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008992 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008993 * 1. the network is an app VPN (not legacy VPN)
8994 * 2. the VPN does not allow bypass
8995 * 3. the VPN is fully-routed
8996 * 4. the VPN interface is non-null
8997 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008998 * @see INetd#firewallAddUidInterfaceRules
8999 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009000 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00009001 @Nullable
9002 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009003 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009004 if (nc == null || lp == null) return null;
9005 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009006 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08009007 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009008 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08009009 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00009010 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00009011 && !lp.hasExcludeRoute()) {
9012 return lp.getInterfaceName();
9013 }
9014 return null;
9015 }
9016
9017 /**
9018 * Returns whether we need to set interface filtering rule or not
9019 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00009020 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00009021 String isolationIface) {
9022 // Allow rules are always needed if VPN isolation is enabled.
9023 if (isolationIface != null) return true;
9024
9025 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
9026 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
9027 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jean03552c42023-05-29 17:02:43 +09009028 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009029 }
9030
Chiachang Wang28afaff2020-12-10 22:24:47 +08009031 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
9032 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
9033 int index = 0;
9034 for (UidRange range : ranges) {
9035 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
9036 index++;
9037 }
9038 return stableRanges;
9039 }
9040
Chalard Jeane6c95272022-01-25 21:04:21 +09009041 private static UidRangeParcel[] intsToUidRangeStableParcels(
9042 final @NonNull ArraySet<Integer> uids) {
9043 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
9044 int index = 0;
9045 for (int uid : uids) {
9046 stableRanges[index] = new UidRangeParcel(uid, uid);
9047 index++;
9048 }
9049 return stableRanges;
9050 }
9051
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009052 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
9053 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
9054 for (int i = 0; i < ranges.length; i++) {
9055 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
9056 }
9057 return stableRanges;
9058 }
9059
Motomu Utsumia20f7602023-03-16 17:04:21 +09009060 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi5d718002023-06-04 21:32:08 +09009061 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08009062 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
9063 try {
Motomu Utsumi5d718002023-06-04 21:32:08 +09009064 if (mDeps.isAtLeastU()) {
9065 final Set<Integer> exemptUidSet = new ArraySet<>();
9066 for (final int uid: exemptUids) {
9067 exemptUidSet.add(uid);
9068 }
9069 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
9070 } else {
9071 mNetd.socketDestroy(uidRangeParcels, exemptUids);
9072 }
Ken Chen5e65a852020-12-24 12:59:10 +08009073 } catch (Exception e) {
9074 loge("Exception in socket destroy: ", e);
9075 }
9076 }
9077 }
9078
paulhuaa0743d2021-05-26 21:56:03 +08009079 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi5d718002023-06-04 21:32:08 +09009080 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08009081 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
9082 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
9083 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi5d718002023-06-04 21:32:08 +09009084 exemptUids[0] = VPN_UID;
9085 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08009086 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
9087
Motomu Utsumi6345e462023-03-13 13:24:50 +09009088 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi5d718002023-06-04 21:32:08 +09009089 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009090 try {
9091 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08009092 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009093 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009094 } else {
paulhu0e79d952021-06-09 16:11:35 +08009095 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009096 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009097 }
9098 } catch (Exception e) {
9099 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
9100 " on netId " + nai.network.netId + ". " + e);
9101 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09009102 // Close sockets that established connection while requesting netd.
Motomu Utsumi5d718002023-06-04 21:32:08 +09009103 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009104 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009105
lucaslin53e8a262021-06-08 01:43:59 +08009106 private boolean isProxySetOnAnyDefaultNetwork() {
9107 ensureRunningOnConnectivityServiceThread();
9108 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9109 final NetworkAgentInfo nai = nri.getSatisfier();
9110 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
9111 return true;
9112 }
9113 }
9114 return false;
9115 }
9116
9117 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
9118 NetworkCapabilities newNc) {
9119 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
9120 // the proxy might be changed since the default network satisfied by the apps might also
9121 // changed.
9122 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
9123 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09009124 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
9125 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09009126 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08009127 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
9128 mProxyTracker.sendProxyBroadcast();
9129 }
9130 }
9131
Chalard Jeane6c95272022-01-25 21:04:21 +09009132 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
9133 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009134 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
9135 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009136 if (null == prevRanges) prevRanges = new ArraySet<>();
9137 if (null == newRanges) newRanges = new ArraySet<>();
9138 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9139
9140 prevRanges.removeAll(newRanges);
9141 newRanges.removeAll(prevRangesCopy);
9142
9143 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009144 // When updating the VPN uid routing rules, add the new range first then remove the old
9145 // range. If old range were removed first, there would be a window between the old
9146 // range being removed and the new range being added, during which UIDs contained
9147 // in both ranges are not subject to any VPN routing rules. Adding new range before
9148 // removing old range works because, unlike the filtering rules below, it's possible to
9149 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009150 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9151 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9152 // [1-5] & [1-2],[4-5] == [3]
9153 // Then we can do:
9154 // maybeCloseSockets([3])
9155 // mNetd.networkAddUidRanges([1-2],[4-5])
9156 // mNetd.networkRemoveUidRanges([1-5])
9157 // maybeCloseSockets([3])
9158 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9159 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009160 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009161 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009162 }
9163 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009164 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009165 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009166 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9167 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009168 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9169 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009170 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009171 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009172 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9173 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9174 // were added first and then newRanges got removed later, there would be only one uid
9175 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9176 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9177 // Note that this is in contrast with the (more robust) update of VPN routing rules
9178 // above, where the addition of new ranges happens before the removal of old ranges.
9179 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9180 // to be removed will never overlap with the new range to be added.
9181 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009182 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9183 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009184 }
9185 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009186 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009187 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009188 } catch (Exception e) {
9189 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009190 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009191 }
9192 }
9193
Chalard Jeande665262022-02-25 16:12:12 +09009194 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009195 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
Tommy Webb34f81dc2023-02-20 14:10:55 -05009196 if (!nai.isVPN()) {
9197 updateAllowedUidsForNetwork(nai);
9198 }
Chalard Jeane6c95272022-01-25 21:04:21 +09009199 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009200 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9201 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009202 if (prevEmpty && newEmpty) return;
9203
9204 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009205 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009206 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009207 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009208
9209 if (prevUids.equals(newUids)) return;
9210
9211 // This implementation is very simple and vastly faster for sets of Integers than
9212 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9213 // a key computed from the value and has storage for that.
9214 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9215 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9216 toRemove.removeAll(newUids);
9217 toAdd.removeAll(prevUids);
9218
9219 try {
9220 if (!toAdd.isEmpty()) {
9221 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9222 nai.network.netId,
9223 intsToUidRangeStableParcels(toAdd),
9224 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9225 }
9226 if (!toRemove.isEmpty()) {
9227 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9228 nai.network.netId,
9229 intsToUidRangeStableParcels(toRemove),
9230 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9231 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009232 } catch (ServiceSpecificException e) {
9233 // Has the interface disappeared since the network was built ?
9234 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009235 } catch (RemoteException e) {
9236 // Netd died. This usually causes a runtime restart anyway.
9237 }
9238 }
9239
Junyu Lai2ed7d412022-10-07 16:52:21 +08009240 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9241 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009242 ensureRunningOnConnectivityServiceThread();
9243
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009244 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009245 // Ignore updates for disconnected networks
9246 return;
9247 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009248 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009249 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009250 + "; created=" + nai.getCreatedTime()
9251 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009252 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009253 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9254 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009255 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009256 }
9257
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009258 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9259 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009260 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009261 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009262 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009263 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9264 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9265 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009266 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9267 // need to be sent as a separate extra.
9268 final NetworkRequest req = nri.isMultilayerRequest()
9269 ? nri.getActiveRequest()
9270 // Non-multilayer listen requests do not have an active request
9271 : nri.mRequests.get(0);
9272 if (req == null) {
9273 Log.wtf(TAG, "No request in NRI " + nri);
9274 }
9275 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009276 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009277 sendIntent(nri.mPendingIntent, intent);
9278 }
9279 // else not handled
9280 }
9281
Michael Groover73f69482023-01-27 11:01:25 -06009282 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9283 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009284 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9285 mPendingIntentWakeLock.acquire();
9286 try {
9287 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009288 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jean03552c42023-05-29 17:02:43 +09009289 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009290 // Explicitly disallow the receiver from starting activities, to prevent apps from
9291 // utilizing the PendingIntent as a backdoor to do this.
9292 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9293 }
9294 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9295 null /* requiredPermission */,
Chalard Jean03552c42023-05-29 17:02:43 +09009296 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009297 } catch (PendingIntent.CanceledException e) {
9298 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9299 mPendingIntentWakeLock.release();
9300 releasePendingNetworkRequest(pendingIntent);
9301 }
9302 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9303 }
9304
9305 @Override
9306 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9307 String resultData, Bundle resultExtras) {
9308 if (DBG) log("Finished sending " + pendingIntent);
9309 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009310 // Release with a delay so the receiving client has an opportunity to put in its
9311 // own request.
9312 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009313 }
9314
Chalard Jean46bfbf02022-02-02 00:56:25 +09009315 // networkAgent is only allowed to be null if notificationType is
9316 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9317 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009318 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009319 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009320 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009321 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009322 // Default request has no msgr. Also prevents callbacks from being invoked for
9323 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9324 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9325 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009326 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009327 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009328 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009329 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009330 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009331 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009332 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009333 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9334 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009335 }
Roshan Pius951c0032020-12-22 15:10:42 -08009336 final boolean includeLocationSensitiveInfo =
9337 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009338 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009339 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009340 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009341 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009342 networkCapabilitiesRestrictedForCallerPermissions(
9343 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9344 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009345 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009346 nri.mCallingAttributionTag);
9347 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009348 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9349 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08009350 // For this notification, arg1 contains the blocked status.
9351 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009352 break;
9353 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009354 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009355 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009356 break;
9357 }
9358 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009359 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009360 final NetworkCapabilities netCap =
9361 networkCapabilitiesRestrictedForCallerPermissions(
9362 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9363 putParcelable(
9364 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009365 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009366 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009367 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009368 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009369 break;
9370 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009371 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009372 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9373 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009374 break;
9375 }
junyulaif2c67e42018-08-07 19:50:45 +08009376 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009377 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009378 msg.arg1 = arg1;
9379 break;
9380 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009381 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009382 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009383 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009384 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009385 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009386 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009387 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009388 }
James Mattis45d81842021-01-10 14:24:24 -08009389 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009390 } catch (RemoteException e) {
9391 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009392 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009393 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009394 }
9395
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009396 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9397 bundle.putParcelable(t.getClass().getSimpleName(), t);
9398 }
9399
Chalard Jean0702f982021-09-16 21:50:07 +09009400 /**
9401 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9402 *
9403 * When a request should be assigned to a new network, it is normally lingered to give
9404 * time for apps to gracefully migrate their connections. When both networks are on the same
9405 * radio, but that radio can't do time-sharing efficiently, this may end up being
9406 * counter-productive because any traffic on the old network may drastically reduce the
9407 * performance of the new network.
9408 * The stack supports a configuration to let modem vendors state that their radio can't
9409 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9410 * from one cell network to another can't be done gracefully.
9411 *
9412 * @param oldNai the old network serving the request
9413 * @param newNai the new network serving the request
9414 * @return whether the switch can be graceful
9415 */
9416 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9417 @NonNull final NetworkAgentInfo newSatisfier) {
9418 if (mCellularRadioTimesharingCapable) return true;
9419 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9420 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9421 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9422 }
9423
Paul Jensenaf94b982014-09-30 15:37:41 -04009424 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009425 if (nai.numRequestNetworkRequests() != 0) {
9426 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9427 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009428 // Ignore listening and track default requests.
9429 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009430 loge("Dead network still had at least " + nr);
9431 break;
9432 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009433 }
Jean Chalard01a7d322023-06-27 08:54:23 +00009434 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009435 }
9436
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009437 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9438 if (oldNetwork == null) {
9439 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9440 return;
9441 }
Chalard Jean49707572019-12-10 21:07:02 +09009442 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009443
9444 // If we get here it means that the last linger timeout for this network expired. So there
9445 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009446 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009447
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009448 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009449 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009450 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009451 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009452 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009453 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009454 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009455 }
9456
James Mattise3ef1912020-12-20 11:09:58 -08009457 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9458 boolean isDefaultChanged = false;
9459 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9460 final NetworkReassignment.RequestReassignment reassignment =
9461 changes.getReassignment(defaultRequestInfo);
9462 if (null == reassignment) {
9463 continue;
9464 }
9465 // reassignment only contains those instances where the satisfying network changed.
9466 isDefaultChanged = true;
9467 // Notify system services of the new default.
9468 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9469 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009470
James Mattise3ef1912020-12-20 11:09:58 -08009471 if (isDefaultChanged) {
9472 // Hold a wakelock for a short time to help apps in migrating to a new default.
9473 scheduleReleaseNetworkTransitionWakelock();
9474 }
9475 }
9476
Aaron Huang25ef1712021-06-08 13:11:45 +08009477 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9478 if (null == oldDefaultNetwork) return;
9479 // The network stopped being the default. If it was using a PAC proxy, then the
9480 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9481 // to the local proxy server, which would forward them over the newly default network.
9482 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9483 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9484 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9485 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9486 }
9487
James Mattise3ef1912020-12-20 11:09:58 -08009488 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9489 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9490 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9491 if (DBG) {
9492 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9493 }
Chalard Jean8e382112019-12-03 20:45:30 +09009494
James Mattisd31bdfa2020-12-23 16:37:26 -08009495 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9496 if (newDefaultNetwork != null) {
9497 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009498 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009499
James Mattisd31bdfa2020-12-23 16:37:26 -08009500 // Set an app level managed default and return since further processing only applies to the
9501 // default network.
9502 if (mDefaultRequest != nri) {
9503 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9504 return;
9505 }
9506
9507 makeDefaultNetwork(newDefaultNetwork);
9508
James Mattise3ef1912020-12-20 11:09:58 -08009509 if (oldDefaultNetwork != null) {
9510 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9511 }
9512 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang25ef1712021-06-08 13:11:45 +08009513 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009514 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang25ef1712021-06-08 13:11:45 +08009515 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009516 updateTcpBufferSizes(null != newDefaultNetwork
9517 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009518 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009519 }
9520
James Mattisd31bdfa2020-12-23 16:37:26 -08009521 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9522 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9523 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9524 try {
9525 if (VDBG) {
9526 log("Setting default network for " + nri
9527 + " using UIDs " + nri.getUids()
9528 + " with old network " + (oldDefaultNetwork != null
9529 ? oldDefaultNetwork.network().getNetId() : "null")
9530 + " and new network " + (newDefaultNetwork != null
9531 ? newDefaultNetwork.network().getNetId() : "null"));
9532 }
9533 if (nri.getUids().isEmpty()) {
9534 throw new IllegalStateException("makeDefaultForApps called without specifying"
9535 + " any applications to set as the default." + nri);
9536 }
9537 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009538 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009539 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009540 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009541 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009542 }
9543 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009544 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009545 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009546 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009547 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009548 }
9549 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009550 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009551 }
Tommy Webb34f81dc2023-02-20 14:10:55 -05009552 updateUidDefaultNetworkRules(newDefaultNetwork);
James Mattisd31bdfa2020-12-23 16:37:26 -08009553 }
9554
Junyu Lai35665cc2022-12-19 17:37:48 +08009555 /**
9556 * Collect restricted uid ranges for the given network and UserHandle, these uids
9557 * are not restricted for matched enterprise networks but being restricted for non-matched
9558 * enterprise networks and non-enterprise networks.
9559 */
9560 @NonNull
9561 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
9562 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
9563 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
9564 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
9565 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
9566
9567 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
9568 // The NC is built from a `ProfileNetworkPreference` which has only one
9569 // enterprise ID, so it's guaranteed to have exactly one.
9570 final int prefId = pref.capabilities.getEnterpriseIds()[0];
9571 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
9572 continue;
9573 }
9574 }
9575
9576 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
9577 pref.capabilities.getUidRanges())) {
9578 throw new IllegalArgumentException(
9579 "Overlapping uid range in preference: " + pref);
9580 }
9581 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
9582 }
9583 return restrictedUidRanges;
9584 }
9585
9586 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08009587 // Netd command is not implemented before U.
Chalard Jean03552c42023-05-29 17:02:43 +09009588 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +08009589
Junyu Lai35665cc2022-12-19 17:37:48 +08009590 ensureRunningOnConnectivityServiceThread();
9591 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
9592 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
9593 .getUserHandles(true /* excludeDying */);
9594 if (users.isEmpty()) {
9595 throw new IllegalStateException("No user is available");
9596 }
9597
9598 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9599 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
9600 for (final UserHandle user : users) {
9601 final ArraySet<UidRange> restrictedUidRanges =
9602 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
9603 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
9604 UidRange.createForUser(user), restrictedUidRanges));
9605 }
9606
9607 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9608 configs.add(new NativeUidRangeConfig(
9609 nai.network.netId, rangesParcel, 0 /* subPriority */));
9610 }
9611
9612 // The netd API replaces the previous configs with the current configs.
9613 // Thus, for network disconnection or preference removal, no need to
9614 // unset previous config. Instead, collecting all currently needed
9615 // configs and issue to netd.
9616 try {
9617 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9618 } catch (ServiceSpecificException e) {
9619 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009620 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009621 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009622 // Netd died. This will cause a runtime restart anyway.
9623 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009624 }
9625 }
9626
James Mattisd31bdfa2020-12-23 16:37:26 -08009627 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9628 try {
9629 if (null != newDefaultNetwork) {
9630 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9631 } else {
9632 mNetd.networkClearDefault();
9633 }
9634 } catch (RemoteException | ServiceSpecificException e) {
9635 loge("Exception setting default network :" + e);
9636 }
Tommy Webb34f81dc2023-02-20 14:10:55 -05009637 updateUidDefaultNetworkRules(newDefaultNetwork);
James Mattisd31bdfa2020-12-23 16:37:26 -08009638 }
9639
Chalard Jean05cbe972019-12-09 11:50:38 +09009640 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009641 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009642 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009643 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009644 processNewlySatisfiedListenRequests(nai);
9645 }
9646
9647 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009648 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9649 if (nri.isMultilayerRequest()) {
9650 continue;
9651 }
9652 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009653 if (!nr.isListen()) continue;
9654 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009655 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009656 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9657 }
9658 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009659 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009660
Chalard Jeancd397a22019-11-22 22:33:33 +09009661 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009662 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9663 if (nri.isMultilayerRequest()) {
9664 continue;
9665 }
9666 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009667 if (!nr.isListen()) continue;
9668 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9669 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009670 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009671 }
9672 }
9673 }
9674
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009675 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009676 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009677 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009678 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009679 @Nullable public final NetworkRequest mOldNetworkRequest;
9680 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009681 @Nullable public final NetworkAgentInfo mOldNetwork;
9682 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009683 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009684 @Nullable final NetworkRequest oldNetworkRequest,
9685 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009686 @Nullable final NetworkAgentInfo oldNetwork,
9687 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009688 mNetworkRequestInfo = networkRequestInfo;
9689 mOldNetworkRequest = oldNetworkRequest;
9690 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009691 mOldNetwork = oldNetwork;
9692 mNewNetwork = newNetwork;
9693 }
Chalard Jean49707572019-12-10 21:07:02 +09009694
9695 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009696 final NetworkRequest requestToShow = null != mNewNetworkRequest
9697 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9698 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009699 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9700 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009701 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009702 }
9703
Chalard Jean46a62372019-12-10 21:25:24 +09009704 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009705
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009706 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009707 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009708 }
9709
9710 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009711 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009712 // The code is never supposed to add two reassignments of the same request. Make
9713 // sure this stays true, but without imposing this expensive check on all
9714 // reassignments on all user devices.
9715 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009716 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009717 throw new IllegalStateException("Trying to reassign ["
9718 + reassignment + "] but already have ["
9719 + existing + "]");
9720 }
9721 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009722 }
Chalard Jean46a62372019-12-10 21:25:24 +09009723 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009724 }
9725
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009726 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009727 // the passed request.
9728 @Nullable
9729 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009730 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009731 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009732 }
9733 return null;
9734 }
Chalard Jean49707572019-12-10 21:07:02 +09009735
9736 public String toString() {
9737 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9738 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009739 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009740 for (final RequestReassignment rr : getRequestReassignments()) {
9741 sj.add(rr.toString());
9742 }
9743 return sj.toString();
9744 }
9745
9746 public String debugString() {
9747 final StringBuilder sb = new StringBuilder();
9748 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009749 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009750 for (final RequestReassignment rr : getRequestReassignments()) {
9751 sb.append("\n ").append(rr);
9752 }
9753 return sb.append("\n").toString();
9754 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009755 }
9756
Chalard Jean24344d72019-12-04 13:32:31 +09009757 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009758 @Nullable final NetworkRequest previousRequest,
9759 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009760 @Nullable final NetworkAgentInfo previousSatisfier,
9761 @Nullable final NetworkAgentInfo newSatisfier,
9762 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009763 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009764 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009765 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009766 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009767 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09009768 }
James Mattisa076c532020-12-02 14:12:41 -08009769 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009770 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009771 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009772 // If this network switch can't be supported gracefully, the request is not
9773 // lingered. This allows letting go of the network sooner to reclaim some
9774 // performance on the new network, since the radio can't do both at the same
9775 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009776 //
9777 // Also don't linger the request if the old network has been destroyed.
9778 // A destroyed network does not provide actual network connectivity, so
9779 // lingering it is not useful. In particular this ensures that a destroyed
9780 // network is outscored by its replacement,
9781 // then it is torn down immediately instead of being lingered, and any apps that
9782 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009783 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9784 }
Chalard Jean24344d72019-12-04 13:32:31 +09009785 } else {
9786 if (VDBG || DDBG) log(" accepting network in place of null");
9787 }
junyulai0ac374f2020-12-14 18:41:52 +08009788
9789 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9790 // and immediately satisfies a request then remove the timer. This will happen for
9791 // all networks except in the case of an underlying network for a VCN.
9792 if (newSatisfier.isNascent()) {
9793 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009794 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009795 }
9796
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009797 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009798 newSatisfier.unlingerRequest(newRequest.requestId);
9799 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009800 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009801 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009802 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009803 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009804 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009805 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009806 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009807 }
James Mattisa076c532020-12-02 14:12:41 -08009808 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009809 }
James Mattisa076c532020-12-02 14:12:41 -08009810 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009811 }
9812
James Mattisa076c532020-12-02 14:12:41 -08009813 /**
9814 * This function is triggered when something can affect what network should satisfy what
9815 * request, and it computes the network reassignment from the passed collection of requests to
9816 * network match to the one that the system should now have. That data is encoded in an
9817 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9818 * satisfier.
9819 *
9820 * After the reassignment is computed, it is applied to the state objects.
9821 *
9822 * @param networkRequests the nri objects to evaluate for possible network reassignment
9823 * @return NetworkReassignment listing of proposed network assignment changes
9824 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009825 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009826 private NetworkReassignment computeNetworkReassignment(
9827 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009828 final NetworkReassignment changes = new NetworkReassignment();
9829
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009830 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009831 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009832 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009833 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009834 }
Chalard Jean857a1712019-12-10 21:08:07 +09009835
James Mattisa076c532020-12-02 14:12:41 -08009836 for (final NetworkRequestInfo nri : networkRequests) {
9837 // Non-multilayer listen requests can be ignored.
9838 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9839 continue;
9840 }
9841 NetworkAgentInfo bestNetwork = null;
9842 NetworkRequest bestRequest = null;
9843 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009844 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009845 // Stop evaluating as the highest possible priority request is satisfied.
9846 if (null != bestNetwork) {
9847 bestRequest = req;
9848 break;
9849 }
9850 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009851 if (null == bestNetwork && isDefaultBlocked(nri)) {
9852 // Remove default networking if disallowed for managed default requests.
9853 bestNetwork = mNoServiceNetwork;
9854 }
9855 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009856 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009857 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009858 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009859 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009860 }
9861 return changes;
9862 }
9863
James Mattisa076c532020-12-02 14:12:41 -08009864 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9865 return new HashSet<>(mNetworkRequests.values());
9866 }
9867
Paul Jensenc88b39b2015-06-16 14:27:36 -04009868 /**
James Mattisa076c532020-12-02 14:12:41 -08009869 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009870 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009871 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009872 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009873 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9874 }
9875
9876 /**
9877 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9878 * being disconnected.
9879 */
9880 private void rematchNetworksAndRequests(
9881 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9882 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009883 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009884 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009885 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09009886 final long computed = SystemClock.elapsedRealtime();
9887 applyNetworkReassignment(changes, start);
9888 final long applied = SystemClock.elapsedRealtime();
9889 issueNetworkNeeds();
9890 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09009891 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009892 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
9893 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009894 log(changes.debugString());
9895 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009896 // Shorter form, only one line of log
9897 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
9898 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009899 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09009900 }
Chalard Jean64520dc2019-12-04 19:55:32 +09009901
Chalard Jeand7f762d2019-12-10 19:01:29 +09009902 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09009903 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009904 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09009905
9906 // Since most of the time there are only 0 or 1 background networks, it would probably
9907 // be more efficient to just use an ArrayList here. TODO : measure performance
9908 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
9909 for (final NetworkAgentInfo nai : nais) {
9910 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
9911 }
9912
Chalard Jeand7f762d2019-12-10 19:01:29 +09009913 // First, update the lists of satisfied requests in the network agents. This is necessary
9914 // because some code later depends on this state to be correct, most prominently computing
9915 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09009916 for (final NetworkReassignment.RequestReassignment event :
9917 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009918 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
9919 event.mOldNetworkRequest, event.mNewNetworkRequest,
9920 event.mOldNetwork, event.mNewNetwork,
9921 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09009922 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009923
James Mattise3ef1912020-12-20 11:09:58 -08009924 // Process default network changes if applicable.
9925 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009926
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009927 // Notify requested networks are available after the default net is switched, but
9928 // before LegacyTypeTracker sends legacy broadcasts
9929 for (final NetworkReassignment.RequestReassignment event :
9930 changes.getRequestReassignments()) {
9931 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009932 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009933 } else {
James Mattisa076c532020-12-02 14:12:41 -08009934 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009935 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009936 }
9937 }
9938
junyulai0ac374f2020-12-14 18:41:52 +08009939 // Update the inactivity state before processing listen callbacks, because the background
9940 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009941 // just yet though, because they have to be sent after the listens are processed to keep
9942 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08009943 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09009944 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08009945 // Rematching may have altered the inactivity state of some networks, so update all
9946 // inactivity timers. updateInactivityState reads the state from the network agent
9947 // and does nothing if the state has not changed : the source of truth is controlled
9948 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
9949 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08009950 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08009951 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009952 }
9953 }
9954
Chalard Jeanb10ab412019-12-11 14:12:30 +09009955 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009956 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009957 // Process listen requests and update capabilities if the background state has
9958 // changed for this network. For consistency with previous behavior, send onLost
9959 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09009960 processNewlyLostListenRequests(nai);
9961 if (oldBackground != nai.isBackgroundNetwork()) {
9962 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009963 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09009964 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009965 }
9966
junyulai0ac374f2020-12-14 18:41:52 +08009967 for (final NetworkAgentInfo nai : inactiveNetworks) {
9968 // For nascent networks, if connecting with no foreground request, skip broadcasting
9969 // LOSING for backward compatibility. This is typical when mobile data connected while
9970 // wifi connected with mobile data always-on enabled.
9971 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009972 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009973 }
9974
James Mattise3ef1912020-12-20 11:09:58 -08009975 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09009976
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009977 // Tear down all unneeded networks.
Jean Chalard01a7d322023-06-27 08:54:23 +00009978 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009979 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08009980 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009981 // This network has active linger timers and no requests, but is not
9982 // lingering. Linger it.
9983 //
9984 // One way (the only way?) this can happen if this network is unvalidated
9985 // and became unneeded due to another network improving its score to the
9986 // point where this network will no longer be able to satisfy any requests
9987 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08009988 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009989 notifyNetworkLosing(nai, now);
9990 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09009991 } else {
Chalard Jean49707572019-12-10 21:07:02 +09009992 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09009993 teardownUnneededNetwork(nai);
9994 }
9995 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04009996 }
9997 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009998
Chalard Jean62edfd82019-12-02 18:39:29 +09009999 /**
10000 * Apply a change in background state resulting from rematching networks with requests.
10001 *
10002 * During rematch, a network may change background states by starting to satisfy or stopping
10003 * to satisfy a foreground request. Listens don't count for this. When a network changes
10004 * background states, its capabilities need to be updated and callbacks fired for the
10005 * capability change.
10006 *
10007 * @param nai The network that changed background states
10008 */
10009 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
10010 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
10011 if (Objects.equals(nai.networkCapabilities, newNc)) return;
10012 updateNetworkPermissions(nai, newNc);
10013 nai.getAndSetNetworkCapabilities(newNc);
10014 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
10015 }
10016
Chalard Jeanf0344532019-11-19 19:23:38 +090010017 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -080010018 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010019 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +090010020 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
10021 changes.getReassignment(mDefaultRequest);
10022 final NetworkAgentInfo oldDefaultNetwork =
10023 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
10024 final NetworkAgentInfo newDefaultNetwork =
10025 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -080010026
Chalard Jean5b409c72021-02-04 13:12:59 +090010027 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010028 // Maintain the illusion : since the legacy API only understands one network at a time,
10029 // if the default network changed, apps should see a disconnected broadcast for the
10030 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +090010031 if (oldDefaultNetwork != null) {
10032 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
10033 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010034 }
Chalard Jean5b409c72021-02-04 13:12:59 +090010035 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010036 // The new default network can be newly null if and only if the old default
10037 // network doesn't satisfy the default request any more because it lost a
10038 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +090010039 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -080010040 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +090010041 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010042 }
10043 }
10044
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010045 // Now that all the callbacks have been sent, send the legacy network broadcasts
10046 // as needed. This is necessary so that legacy requests correctly bind dns
10047 // requests to this network. The legacy users are listening for this broadcast
10048 // and will generally do a dns request so they can ensureRouteToHost and if
10049 // they do that before the callbacks happen they'll use the default network.
10050 //
10051 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
10052 // callbacks, but if apps can receive the broadcast before the callback, they still might
10053 // have an inconsistent view of networking.
10054 //
10055 // This *does* introduce a race where if the user uses the new api
10056 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
10057 // they may get old info. Reverse this after the old startUsing api is removed.
10058 // This is on top of the multiple intent sequencing referenced in the todo above.
10059 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +090010060 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010061 addNetworkToLegacyTypeTracker(nai);
10062 }
The Android Open Source Project28527d22009-03-03 19:31:44 -080010063 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010064 }
10065
Chalard Jean0354d8c2021-01-12 10:58:56 +090010066 private void issueNetworkNeeds() {
10067 ensureRunningOnConnectivityServiceThread();
10068 for (final NetworkOfferInfo noi : mNetworkOffers) {
10069 issueNetworkNeeds(noi);
10070 }
10071 }
10072
10073 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
10074 ensureRunningOnConnectivityServiceThread();
10075 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10076 informOffer(nri, noi.offer, mNetworkRanker);
10077 }
10078 }
10079
10080 /**
10081 * Inform a NetworkOffer about any new situation of a request.
10082 *
10083 * This function handles updates to offers. A number of events may happen that require
10084 * updating the registrant for this offer about the situation :
10085 * • The offer itself was updated. This may lead the offer to no longer being able
10086 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
10087 * or conversely being strengthened enough to beat the satisfier (and therefore
10088 * start being needed)
10089 * • The network satisfying a request changed (including cases where the request
10090 * starts or stops being satisfied). The new network may be a stronger or weaker
10091 * match than the old one, possibly affecting whether the offer is needed.
10092 * • The network satisfying a request updated their score. This may lead the offer
10093 * to no longer be able to beat it if the current satisfier got better, or
10094 * conversely start being a good choice if the current satisfier got weaker.
10095 *
10096 * @param nri The request
10097 * @param offer The offer. This may be an updated offer.
10098 */
10099 private static void informOffer(@NonNull NetworkRequestInfo nri,
10100 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
10101 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
10102 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +090010103
10104 // Multi-layer requests have a currently active request, the one being satisfied.
10105 // Since the system will try to bring up a better network than is currently satisfying
10106 // the request, NetworkProviders need to be told the offers matching the requests *above*
10107 // the currently satisfied one are needed, that the ones *below* the satisfied one are
10108 // not needed, and the offer is needed for the active request iff the offer can beat
10109 // the satisfier.
10110 // For non-multilayer requests, the logic above gracefully degenerates to only the
10111 // last case.
10112 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
10113 // providers that the offer is needed for this request, until the active request is found.
10114 // In a second phase, deal with the currently active request. In a third phase, inform
10115 // the providers that offer is unneeded for the remaining requests.
10116
10117 // First phase : inform providers of all requests above the active request.
10118 int i;
10119 for (i = 0; nri.mRequests.size() > i; ++i) {
10120 final NetworkRequest request = nri.mRequests.get(i);
10121 if (activeRequest == request) break; // Found the active request : go to phase 2
10122 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10123 // Since this request is higher-priority than the one currently satisfied, if the
10124 // offer can satisfy it, the provider should try and bring up the network for sure ;
10125 // no need to even ask the ranker – an offer that can satisfy is always better than
10126 // no network. Hence tell the provider so unless it already knew.
10127 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
10128 offer.onNetworkNeeded(request);
10129 }
10130 }
10131
10132 // Second phase : deal with the active request (if any)
10133 if (null != activeRequest && activeRequest.isRequest()) {
10134 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000010135 // If an offer can satisfy the request, it is considered needed if it is currently
10136 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090010137 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000010138 && satisfier.factorySerialNumber == offer.providerId
10139 && activeRequest.canBeSatisfiedBy(offer.caps);
10140 final boolean newNeeded = currentlyServing
10141 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010142 if (newNeeded != oldNeeded) {
10143 if (newNeeded) {
10144 offer.onNetworkNeeded(activeRequest);
10145 } else {
10146 // The offer used to be able to beat the satisfier. Now it can't.
10147 offer.onNetworkUnneeded(activeRequest);
10148 }
10149 }
10150 }
10151
10152 // Third phase : inform the providers that the offer isn't needed for any request
10153 // below the active one.
10154 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10155 final NetworkRequest request = nri.mRequests.get(i);
10156 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10157 // Since this request is lower-priority than the one currently satisfied, if the
10158 // offer can satisfy it, the provider should not try and bring up the network.
10159 // Hence tell the provider so unless it already knew.
10160 if (offer.neededFor(request)) {
10161 offer.onNetworkUnneeded(request);
10162 }
10163 }
10164 }
10165
Chalard Jean61c79252019-11-07 23:07:32 +090010166 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10167 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10168 NetworkRequest nr = nai.requestAt(i);
10169 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10170 // legacy type tracker filters out repeat adds
10171 mLegacyTypeTracker.add(nr.legacyType, nai);
10172 }
10173 }
10174
10175 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010176 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010177 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10178 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10179 if (nai.isVPN()) {
10180 mLegacyTypeTracker.add(TYPE_VPN, nai);
10181 }
10182 }
10183
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010184 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010185 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010186 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010187 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010188 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010189 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010190
Chalard Jean254bd162022-08-25 13:04:51 +090010191 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010192 // Don't repeat publish.
10193 if (newInetCondition == mDefaultInetConditionPublished) return;
10194
10195 mDefaultInetConditionPublished = newInetCondition;
10196 sendInetConditionBroadcast(nai.networkInfo);
10197 }
10198
Chalard Jeand61375d2020-01-14 22:46:36 +090010199 @NonNull
10200 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10201 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010202 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010203 final boolean suspended =
10204 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10205 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10206 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10207 // state. This is because the network could have been suspended before connecting,
10208 // or it could be disconnecting while being suspended, and in both these cases
10209 // the state should not be overridden. Note that the only detailed state that
10210 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10211 // worry about multiple different substates of CONNECTED.
10212 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10213 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010214 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10215 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10216 // network agent is created, then goes to suspended, then goes out of suspended without
10217 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010218 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010219 ? NetworkInfo.DetailedState.CONNECTED
10220 : NetworkInfo.DetailedState.CONNECTING,
10221 info.getReason(),
10222 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010223 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010224 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010225 return newInfo;
10226 }
10227
10228 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10229 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10230
Erik Kline99f301b2017-02-15 19:59:17 +090010231 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010232 NetworkInfo oldInfo = null;
10233 synchronized (networkAgent) {
10234 oldInfo = networkAgent.networkInfo;
10235 networkAgent.networkInfo = newInfo;
10236 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010237
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010238 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010239 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10240 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010241 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010242
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +090010243 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010244 // A network that has just connected has zero requests and is thus a foreground network.
10245 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10246
Luke Huangfdd11f82019-04-09 18:41:49 +080010247 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +090010248
10249 networkAgent.setCreated();
10250
10251 // If the network is created immediately on register, then apply the LinkProperties now.
10252 // Otherwise, this is done further down when the network goes into connected state.
10253 // Applying the LinkProperties means that the network is ready to carry traffic -
10254 // interfaces and routing rules have been added, DNS servers programmed, etc.
10255 // For VPNs, this must be done before the capabilities are updated, because as soon as
10256 // that happens, UIDs are routed to the network.
10257 if (shouldCreateNetworksImmediately()) {
10258 applyInitialLinkProperties(networkAgent);
10259 }
10260
10261 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10262 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010263 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010264 // Initialize the network's capabilities to their starting values according to the
10265 // underlying networks. This ensures that the capabilities are correct before
10266 // anything happens to the network.
10267 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010268 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010269 networkAgent.onNetworkCreated();
Tommy Webb34f81dc2023-02-20 14:10:55 -050010270 updateDisallowedUidsForNetwork(networkAgent);
Chalard Jeande665262022-02-25 16:12:12 +090010271 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010272 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010273 }
10274
Chalard Jean254bd162022-08-25 13:04:51 +090010275 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10276 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010277
lucaslin45e639b2019-04-03 17:09:28 +080010278 // NetworkCapabilities need to be set before sending the private DNS config to
10279 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010280 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10281
Erik Kline9a62f012018-03-21 07:18:33 -070010282 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti8c21c3b2022-07-25 13:20:37 +090010283 if (!shouldCreateNetworksImmediately()) {
10284 applyInitialLinkProperties(networkAgent);
10285 } else {
10286 // The network was created when the agent registered, and the LinkProperties are
10287 // already up-to-date. However, updateLinkProperties also makes some changes only
10288 // when the network connects. Apply those changes here. On T and below these are
10289 // handled by the applyInitialLinkProperties call just above.
10290 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10291 // If something depends on both LinkProperties and connected state, it should be in
10292 // this method as well.
10293 networkAgent.clatd.update();
10294 updateProxy(networkAgent.linkProperties, null);
10295 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010296
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010297 // If a rate limit has been configured and is applicable to this network (network
10298 // provides internet connectivity), apply it. The tc police filter cannot be attached
10299 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
10300 // updateInterfaces -> INetd#networkAddInterface.
10301 // Note: in case of a system server crash, the NetworkController constructor in netd
10302 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10303 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10304 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10305 mIngressRateLimit);
10306 }
10307
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010308 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10309 // command must be sent after updating LinkProperties to maximize chances of
10310 // NetworkMonitor seeing the correct LinkProperties when starting.
10311 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010312 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010313 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010314 }
Chalard Jeand4900722022-02-06 12:25:38 +090010315 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10316 params.networkAgentConfig = networkAgent.networkAgentConfig;
10317 params.networkCapabilities = networkAgent.networkCapabilities;
10318 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10319 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010320 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10321 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10322 // call that would cause a Log.wtf to be emitted from the system_server process, and
10323 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10324 // process to check the interface version, just use an SDK check. NetworkStack will
10325 // always be new enough when running on T+.
Chalard Jean03552c42023-05-29 17:02:43 +090010326 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010327 networkAgent.networkMonitor().notifyNetworkConnected(params);
10328 } else {
10329 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10330 params.networkCapabilities);
10331 }
Chalard Jean3f0ff5b2023-06-05 19:26:17 +090010332 final long evaluationDelay;
10333 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10334 // If the network is anything other than pure wifi, use the default timeout.
10335 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10336 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10337 // If the network is explicitly selected, use the default timeout because it's
10338 // shorter and the user is likely staring at the screen expecting it to validate
10339 // right away.
10340 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10341 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10342 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10343 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10344 } else {
10345 // It's wifi, automatically connected, and bad wifi is preferred : use the
10346 // longer timeout to avoid the device switching to captive portals with bad
10347 // signal or very slow response.
10348 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10349 }
10350 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010351
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010352 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10353 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10354 // capabilities, so it only needs to be done once on initial connect, not every time the
10355 // network's capabilities change. Note that we do this before rematching the network,
10356 // so we could decide to tear it down immediately afterwards. That's fine though - on
10357 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10358 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010359 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010360
junyulai0ac374f2020-12-14 18:41:52 +080010361 // Before first rematching networks, put an inactivity timer without any request, this
10362 // allows {@code updateInactivityState} to update the state accordingly and prevent
10363 // tearing down for any {@code unneeded} evaluation in this period.
10364 // Note that the timer will not be rescheduled since the expiry time is
10365 // fixed after connection regardless of the network satisfying other requests or not.
10366 // But it will be removed as soon as the network satisfies a request for the first time.
10367 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10368 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010369 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010370
Paul Jensen05e85ee2014-09-11 11:00:39 -040010371 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010372 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010373
10374 // This has to happen after matching the requests, because callbacks are just requests.
10375 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010376 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard01a7d322023-06-27 08:54:23 +000010377 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010378 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010379 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010380 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010381 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010382 if (networkAgent.isVPN()) {
10383 // As the active or bound network changes for apps, broadcast the default proxy, as
10384 // apps may need to update their proxy data. This is called after disconnecting from
10385 // VPN to make sure we do not broadcast the old proxy data.
10386 // TODO(b/122649188): send the broadcast only to VPN users.
10387 mProxyTracker.sendProxyBroadcast();
10388 }
Chalard Jean254bd162022-08-25 13:04:51 +090010389 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10390 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010391 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010392 }
10393 }
10394
Chalard Jean28018572020-12-21 18:36:52 +090010395 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010396 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10397 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010398 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010399 }
10400
Erik Kline99f301b2017-02-15 19:59:17 +090010401 // Notify only this one new request of the current state. Transfer all the
10402 // current state by calling NetworkCapabilities and LinkProperties callbacks
10403 // so that callers can be guaranteed to have as close to atomicity in state
10404 // transfer as can be supported by this current API.
10405 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010406 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010407 if (nri.mPendingIntent != null) {
10408 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10409 // Attempt no subsequent state pushes where intents are involved.
10410 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010411 }
Erik Kline99f301b2017-02-15 19:59:17 +090010412
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010413 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010414 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010415 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10416 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10417 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010418 }
10419
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010420 // Notify the requests on this NAI that the network is now lingered.
10421 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010422 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010423 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10424 }
10425
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010426 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10427 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10428 return vpnBlocked
10429 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10430 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10431 }
10432
10433 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10434 if (blockedReasons == BLOCKED_REASON_NONE) {
10435 mUidBlockedReasons.delete(uid);
10436 } else {
10437 mUidBlockedReasons.put(uid, blockedReasons);
10438 }
10439 }
10440
junyulaif2c67e42018-08-07 19:50:45 +080010441 /**
10442 * Notify of the blocked state apps with a registered callback matching a given NAI.
10443 *
10444 * Unlike other callbacks, blocked status is different between each individual uid. So for
10445 * any given nai, all requests need to be considered according to the uid who filed it.
10446 *
10447 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010448 * @param oldMetered True if the previous network capabilities were metered.
10449 * @param newMetered True if the current network capabilities are metered.
10450 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10451 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010452 */
10453 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010454 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10455 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010456
10457 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10458 NetworkRequest nr = nai.requestAt(i);
10459 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010460
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010461 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10462 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10463 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010464 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010465 : oldVpnBlocked;
10466
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010467 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10468 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10469 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010470 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010471 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010472 }
10473 }
10474 }
10475
10476 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010477 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010478 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010479 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010480 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010481 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010482 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010483 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010484 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010485
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010486 final int oldBlockedState = getBlockedState(
10487 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
10488 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
10489 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080010490 continue;
junyulaif2c67e42018-08-07 19:50:45 +080010491 }
junyulaif2c67e42018-08-07 19:50:45 +080010492 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10493 NetworkRequest nr = nai.requestAt(i);
10494 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010495 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010496 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
10497 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010498 }
10499 }
10500 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010501 }
10502
Chalard Jean3a3f5f22019-04-10 23:07:55 +090010503 @VisibleForTesting
10504 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090010505 // The NetworkInfo we actually send out has no bearing on the real
10506 // state of affairs. For example, if the default connection is mobile,
10507 // and a request for HIPRI has just gone away, we need to pretend that
10508 // HIPRI has just disconnected. So we need to set the type to HIPRI and
10509 // the state to DISCONNECTED, even though the network is of type MOBILE
10510 // and is still connected.
10511 NetworkInfo info = new NetworkInfo(nai.networkInfo);
10512 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090010513 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010514 if (state != DetailedState.DISCONNECTED) {
10515 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090010516 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010517 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010518 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070010519 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
10520 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
10521 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
10522 if (info.isFailover()) {
10523 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
10524 nai.networkInfo.setFailover(false);
10525 }
10526 if (info.getReason() != null) {
10527 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
10528 }
10529 if (info.getExtraInfo() != null) {
10530 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
10531 }
10532 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090010533 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080010534 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070010535 if (newDefaultAgent != null) {
10536 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
10537 newDefaultAgent.networkInfo);
10538 } else {
10539 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
10540 }
10541 }
10542 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
10543 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090010544 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010545 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090010546 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070010547 }
10548 }
10549 }
10550
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010551 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090010552 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090010553 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090010554 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090010555 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090010556 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
10557 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070010558 NetworkRequestInfo nri = mNetworkRequests.get(nr);
10559 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010560 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010561 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010562 } else {
10563 sendPendingIntentForRequest(nri, networkAgent, notifyType);
10564 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010565 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010566 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010567
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090010568 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
10569 notifyNetworkCallbacks(networkAgent, notifyType, 0);
10570 }
10571
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010572 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090010573 * Returns the list of all interfaces that could be used by network traffic that does not
10574 * explicitly specify a network. This includes the default network, but also all VPNs that are
10575 * currently connected.
10576 *
10577 * Must be called on the handler thread.
10578 */
junyulaie7c7d2a2021-01-26 15:29:15 +080010579 @NonNull
10580 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010581 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080010582 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080010583 final Set<Integer> activeNetIds = new ArraySet<>();
10584 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
10585 if (nri.isBeingSatisfied()) {
10586 activeNetIds.add(nri.getSatisfier().network().netId);
10587 }
10588 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010589 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090010590 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090010591 defaultNetworks.add(nai.network);
10592 }
10593 }
junyulaie7c7d2a2021-01-26 15:29:15 +080010594 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090010595 }
10596
10597 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090010598 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
10599 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010600 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080010601 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080010602 ensureRunningOnConnectivityServiceThread();
10603 String activeIface = null;
10604 LinkProperties activeLinkProperties = getActiveLinkProperties();
10605 if (activeLinkProperties != null) {
10606 activeIface = activeLinkProperties.getInterfaceName();
10607 }
Benedict Wong9308cd32019-06-12 17:46:31 +000010608
junyulai2050bed2021-01-23 09:46:34 +080010609 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010610 try {
junyulaide41fc22021-01-22 22:46:01 +080010611 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090010612 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080010613 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
10614 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080010615 } catch (Exception ignored) {
10616 }
10617 }
10618
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070010619 @Override
Udam Sainicd645462016-01-04 12:16:14 -080010620 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080010621 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090010622 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090010623 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010624
10625 if (!TextUtils.isEmpty(settingUrl)) {
10626 return settingUrl;
10627 }
10628
10629 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010630 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010010631 if (!TextUtils.isEmpty(settingUrl)) {
10632 return settingUrl;
10633 }
10634
10635 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080010636 }
10637
10638 @Override
junyulai070f9ff2019-01-16 20:23:34 +080010639 public void startNattKeepalive(Network network, int intervalSeconds,
10640 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010641 enforceKeepalivePermission();
10642 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080010643 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000010644 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
10645 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000010646 // false and set the underpinned network to null because there is no way and no
10647 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10648 // deprecated method.
10649 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010650 }
10651
10652 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010653 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010654 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010655 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010656 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010657 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010658 mKeepaliveTracker.startNattKeepalive(
10659 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010660 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10661 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010662 } finally {
10663 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10664 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010665 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10666 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010667 }
10668 }
junyulaid05a1922019-01-15 11:32:44 +080010669 }
10670
10671 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010672 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010673 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010674 try {
10675 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010676 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010677 mKeepaliveTracker.startTcpKeepalive(
10678 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10679 } finally {
10680 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10681 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010682 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10683 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010684 }
10685 }
junyulai0835a1e2019-01-08 20:04:33 +080010686 }
10687
10688 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010689 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010690 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010691 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10692 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010693 }
10694
10695 @Override
Remi NGUYEN VAN6ca02962023-02-20 20:10:09 +090010696 public int[] getSupportedKeepalives() {
10697 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
10698 // Backwards compatibility with CTS 13
10699 android.Manifest.permission.QUERY_ALL_PACKAGES);
10700
10701 return BinderUtils.withCleanCallingIdentity(() ->
10702 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
10703 }
10704
10705 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010706 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010707 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010708
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010709 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010710 final long token = Binder.clearCallingIdentity();
10711 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010712 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10713 UserHandle.getUserHandleForUid(uid))) {
10714 return;
10715 }
10716
Heemin Seogdb8489d2019-06-12 09:21:44 -070010717 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10718 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010719
10720 // Turn airplane mode off
10721 setAirplaneMode(false);
10722
10723 // restore private DNS settings to default mode (opportunistic)
10724 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10725 UserHandle.getUserHandleForUid(uid))) {
10726 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10727 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10728 }
10729
10730 Settings.Global.putString(mContext.getContentResolver(),
10731 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010732 } finally {
10733 Binder.restoreCallingIdentity(token);
10734 }
Stuart Scottd5463642015-04-02 18:00:02 -070010735 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010736
Ricky Wai7097cc92018-01-23 04:09:45 +000010737 @Override
10738 public byte[] getNetworkWatchlistConfigHash() {
10739 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10740 if (nwm == null) {
10741 loge("Unable to get NetworkWatchlistManager");
10742 return null;
10743 }
10744 // Redirect it to network watchlist service to access watchlist file and calculate hash.
10745 return nwm.getWatchlistConfigHash();
10746 }
10747
Hugo Benichibe0c7652016-05-31 16:28:06 +090010748 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090010749 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080010750 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090010751 }
Hugo Benichif4210292017-04-21 15:07:12 +090010752
10753 private static boolean toBool(int encodedBoolean) {
10754 return encodedBoolean != 0; // Only 0 means false.
10755 }
10756
10757 private static int encodeBool(boolean b) {
10758 return b ? 1 : 0;
10759 }
mswest4632928412018-03-12 10:34:34 -070010760
10761 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010762 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
10763 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
10764 @NonNull String[] args) {
10765 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
10766 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070010767 }
10768
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010769 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070010770 @Override
10771 public int onCommand(String cmd) {
10772 if (cmd == null) {
10773 return handleDefaultCommands(cmd);
10774 }
10775 final PrintWriter pw = getOutPrintWriter();
10776 try {
10777 switch (cmd) {
10778 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010779 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
10780 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070010781 final String action = getNextArg();
10782 if ("enable".equals(action)) {
10783 setAirplaneMode(true);
10784 return 0;
10785 } else if ("disable".equals(action)) {
10786 setAirplaneMode(false);
10787 return 0;
10788 } else if (action == null) {
10789 final ContentResolver cr = mContext.getContentResolver();
10790 final int enabled = Settings.Global.getInt(cr,
10791 Settings.Global.AIRPLANE_MODE_ON);
10792 pw.println(enabled == 0 ? "disabled" : "enabled");
10793 return 0;
10794 } else {
10795 onHelp();
10796 return -1;
10797 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010798 case "reevaluate":
10799 // Usage : adb shell cmd connectivity reevaluate <netId>
10800 // If netId is omitted, then reevaluate the default network
10801 final String netId = getNextArg();
10802 final NetworkAgentInfo nai;
10803 if (null == netId) {
10804 // Note that the command is running on the wrong thread to call this,
10805 // so this could in principle return stale data. But it can't crash.
10806 nai = getDefaultNetwork();
10807 } else {
10808 // If netId can't be parsed, this throws NumberFormatException, which
10809 // is passed back to adb who prints it.
10810 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
10811 }
10812 if (null == nai) {
10813 pw.println("Unknown network (net ID not found or no default network)");
10814 return 0;
10815 }
10816 Log.d(TAG, "Reevaluating network " + nai.network);
10817 reportNetworkConnectivity(nai.network, !nai.isValidated());
10818 return 0;
mswest4632928412018-03-12 10:34:34 -070010819 default:
10820 return handleDefaultCommands(cmd);
10821 }
10822 } catch (Exception e) {
10823 pw.println(e);
10824 }
10825 return -1;
10826 }
10827
10828 @Override
10829 public void onHelp() {
10830 PrintWriter pw = getOutPrintWriter();
10831 pw.println("Connectivity service commands:");
10832 pw.println(" help");
10833 pw.println(" Print this help text.");
10834 pw.println(" airplane-mode [enable|disable]");
10835 pw.println(" Turn airplane mode on or off.");
10836 pw.println(" airplane-mode");
10837 pw.println(" Get airplane mode.");
10838 }
10839 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010840
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090010841 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010842 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
10843 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
10844 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080010845 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010846 }
10847
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090010848 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
10849 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090010850 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
10851 final TransportInfo newInfo = nc.getTransportInfo();
10852 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
10853 return;
10854 }
10855 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090010856 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090010857 }
10858 }
10859
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010860 /**
10861 * @param connectionInfo the connection to resolve.
10862 * @return {@code uid} if the connection is found and the app has permission to observe it
10863 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
10864 * connection is not found.
10865 */
10866 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010867 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
10868 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
10869 }
10870
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090010871 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010872 connectionInfo.local, connectionInfo.remote);
10873
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010874 if (uid == INVALID_UID) return uid; // Not found.
10875
10876 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
10877 // VPN, if any, that applies to the UID that owns the connection.
10878 if (checkNetworkStackPermission()) return uid;
10879
10880 final NetworkAgentInfo vpn = getVpnForUid(uid);
10881 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090010882 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010883 return INVALID_UID;
10884 }
10885
10886 return uid;
10887 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000010888
Benedict Wong493e04b2018-11-09 14:45:34 -080010889 /**
10890 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
10891 *
10892 * <p>The TestNetworkService must be run in the system server due to TUN creation.
10893 */
10894 @Override
10895 public IBinder startOrGetTestNetworkService() {
10896 synchronized (mTNSLock) {
10897 TestNetworkService.enforceTestNetworkPermissions(mContext);
10898
10899 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080010900 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080010901 }
10902
10903 return mTNS;
10904 }
10905 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080010906
Cody Kesting73708bf2019-12-18 10:57:50 -080010907 /**
10908 * Handler used for managing all Connectivity Diagnostics related functions.
10909 *
10910 * @see android.net.ConnectivityDiagnosticsManager
10911 *
10912 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
10913 */
10914 @VisibleForTesting
10915 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010916 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
10917
Cody Kesting73708bf2019-12-18 10:57:50 -080010918 /**
10919 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
10920 * android.net.ConnectivityDiagnosticsManager}.
10921 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
10922 * NetworkRequestInfo to be registered
10923 */
10924 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
10925
10926 /**
10927 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
10928 * android.net.ConnectivityDiagnosticsManager}.
10929 * obj = the IConnectivityDiagnosticsCallback to be unregistered
10930 * arg1 = the uid of the caller
10931 */
10932 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
10933
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010934 /**
10935 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010936 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010937 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
10938 * NetworkMonitor.
10939 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010940 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010941 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010942
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010943 /**
10944 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
10945 * been detected on the network.
10946 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
10947 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
10948 * arg2 = NetID.
10949 * data = PersistableBundle of extras passed from NetworkMonitor.
10950 */
10951 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
10952
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010953 /**
10954 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
10955 * the platform. This event will invoke {@link
10956 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
10957 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070010958 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010959 */
10960 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
10961
Cody Kesting73708bf2019-12-18 10:57:50 -080010962 private ConnectivityDiagnosticsHandler(Looper looper) {
10963 super(looper);
10964 }
10965
10966 @Override
10967 public void handleMessage(Message msg) {
10968 switch (msg.what) {
10969 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10970 handleRegisterConnectivityDiagnosticsCallback(
10971 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
10972 break;
10973 }
10974 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10975 handleUnregisterConnectivityDiagnosticsCallback(
10976 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
10977 break;
10978 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010979 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010980 final ConnectivityReportEvent reportEvent =
10981 (ConnectivityReportEvent) msg.obj;
10982
Aaron Huang959d3642021-01-21 15:47:41 +080010983 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010984 break;
10985 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010986 case EVENT_DATA_STALL_SUSPECTED: {
10987 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080010988 final Pair<Long, PersistableBundle> arg =
10989 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010990 if (nai == null) break;
10991
Aaron Huang959d3642021-01-21 15:47:41 +080010992 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010993 break;
10994 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010995 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070010996 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010997 break;
10998 }
10999 default: {
11000 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
11001 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011002 }
11003 }
11004 }
11005
11006 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
11007 @VisibleForTesting
11008 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
11009 @NonNull private final IConnectivityDiagnosticsCallback mCb;
11010 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011011 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011012
11013 @VisibleForTesting
11014 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011015 @NonNull IConnectivityDiagnosticsCallback cb,
11016 @NonNull NetworkRequestInfo nri,
11017 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011018 mCb = cb;
11019 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011020 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011021 }
11022
11023 @Override
11024 public void binderDied() {
11025 log("ConnectivityDiagnosticsCallback IBinder died.");
11026 unregisterConnectivityDiagnosticsCallback(mCb);
11027 }
11028 }
11029
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011030 /**
11031 * Class used for sending information from {@link
11032 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
11033 */
11034 private static class NetworkTestedResults {
11035 private final int mNetId;
11036 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011037 @Nullable private final String mRedirectUrl;
11038
11039 private NetworkTestedResults(
11040 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
11041 mNetId = netId;
11042 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011043 mRedirectUrl = redirectUrl;
11044 }
11045 }
11046
11047 /**
11048 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
11049 * ConnectivityDiagnosticsHandler}.
11050 */
11051 private static class ConnectivityReportEvent {
11052 private final long mTimestampMillis;
11053 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080011054 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011055
Aaron Huang959d3642021-01-21 15:47:41 +080011056 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
11057 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011058 mTimestampMillis = timestampMillis;
11059 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080011060 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011061 }
11062 }
11063
Cody Kestingf1120be2020-08-03 18:01:40 -070011064 /**
11065 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
11066 * ConnectivityDiagnosticsHandler}.
11067 */
11068 private static class ReportedNetworkConnectivityInfo {
11069 public final boolean hasConnectivity;
11070 public final boolean isNetworkRevalidating;
11071 public final int reporterUid;
11072 @NonNull public final NetworkAgentInfo nai;
11073
11074 private ReportedNetworkConnectivityInfo(
11075 boolean hasConnectivity,
11076 boolean isNetworkRevalidating,
11077 int reporterUid,
11078 @NonNull NetworkAgentInfo nai) {
11079 this.hasConnectivity = hasConnectivity;
11080 this.isNetworkRevalidating = isNetworkRevalidating;
11081 this.reporterUid = reporterUid;
11082 this.nai = nai;
11083 }
11084 }
11085
Cody Kesting73708bf2019-12-18 10:57:50 -080011086 private void handleRegisterConnectivityDiagnosticsCallback(
11087 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11088 ensureRunningOnConnectivityServiceThread();
11089
11090 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011091 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011092 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11093
James Mattis64b8b0f2020-11-24 17:40:49 -080011094 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11095 // confusing for these networks to change when an NRI is satisfied in another layer.
11096 if (nri.isMultilayerRequest()) {
11097 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11098 + "network requests.");
11099 }
11100
Cody Kesting73708bf2019-12-18 10:57:50 -080011101 // This means that the client registered the same callback multiple times. Do
11102 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011103 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011104 if (VDBG) log("Diagnostics callback is already registered");
11105
11106 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11107 // incremented when the NetworkRequestInfo is created as part of
11108 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011109 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011110 return;
11111 }
11112
Cody Kesting31f1ff62020-03-05 10:46:02 -080011113 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011114
11115 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011116 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011117 } catch (RemoteException e) {
11118 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011119 return;
11120 }
11121
11122 // Once registered, provide ConnectivityReports for matching Networks
11123 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11124 synchronized (mNetworkForNetId) {
11125 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11126 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011127 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11128 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011129 matchingNetworks.add(nai);
11130 }
11131 }
11132 }
11133 for (final NetworkAgentInfo nai : matchingNetworks) {
11134 final ConnectivityReport report = nai.getConnectivityReport();
11135 if (report == null) {
11136 continue;
11137 }
11138 if (!checkConnectivityDiagnosticsPermissions(
11139 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11140 continue;
11141 }
11142
11143 try {
11144 cb.onConnectivityReportAvailable(report);
11145 } catch (RemoteException e) {
11146 // Exception while sending the ConnectivityReport. Move on to the next network.
11147 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011148 }
11149 }
11150
11151 private void handleUnregisterConnectivityDiagnosticsCallback(
11152 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11153 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011154 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011155
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011156 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11157 mConnectivityDiagnosticsCallbacks.remove(iCb);
11158 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011159 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11160 return;
11161 }
11162
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011163 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011164
Cody Kesting70fa2b22020-12-02 12:16:56 -080011165 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11166 // (if the Binder died)
11167 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11168 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011169 return;
11170 }
11171
Cody Kesting46cb1672020-03-04 13:35:20 -080011172 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11173 // incremented when the NetworkRequestInfo is created as part of
11174 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011175 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011176
Cody Kesting31f1ff62020-03-05 10:46:02 -080011177 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011178 }
11179
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011180 private void handleNetworkTestedWithExtras(
11181 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11182 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011183 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011184 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011185 final ConnectivityReport report =
11186 new ConnectivityReport(
11187 reportEvent.mNai.network,
11188 reportEvent.mTimestampMillis,
11189 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011190 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011191 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011192 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011193
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011194 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011195 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011196 for (final IConnectivityDiagnosticsCallback cb : results) {
11197 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011198 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011199 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011200 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011201 }
11202 }
11203 }
11204
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011205 private void handleDataStallSuspected(
11206 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11207 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011208 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011209 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011210 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011211 new DataStallReport(
11212 nai.network,
11213 timestampMillis,
11214 detectionMethod,
11215 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011216 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011217 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011218 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011219 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011220 for (final IConnectivityDiagnosticsCallback cb : results) {
11221 try {
11222 cb.onDataStallSuspected(report);
11223 } catch (RemoteException ex) {
11224 loge("Error invoking onDataStallSuspected", ex);
11225 }
11226 }
11227 }
11228
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011229 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011230 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11231 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11232 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11233
11234 // If the Network is being re-validated as a result of this call to
11235 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11236 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011237 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011238 getMatchingPermissionedCallbacks(
11239 nai,
11240 reportedNetworkConnectivityInfo.isNetworkRevalidating
11241 ? Process.INVALID_UID
11242 : reportedNetworkConnectivityInfo.reporterUid);
11243
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011244 for (final IConnectivityDiagnosticsCallback cb : results) {
11245 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011246 cb.onNetworkConnectivityReported(
11247 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011248 } catch (RemoteException ex) {
11249 loge("Error invoking onNetworkConnectivityReported", ex);
11250 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011251
11252 // If the Network isn't re-validating, also provide the cached report. If there is no
11253 // cached report, the Network is still being validated and a report will be sent once
11254 // validation is complete. Note that networks which never undergo validation will still
11255 // have a cached ConnectivityReport with RESULT_SKIPPED.
11256 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11257 try {
11258 cb.onConnectivityReportAvailable(cachedReport);
11259 } catch (RemoteException ex) {
11260 loge("Error invoking onConnectivityReportAvailable", ex);
11261 }
11262 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011263 }
11264 }
11265
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011266 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011267 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11268 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011269 sanitized.setUids(null);
11270 sanitized.setAdministratorUids(new int[0]);
11271 sanitized.setOwnerUid(Process.INVALID_UID);
11272 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011273 }
11274
Cody Kestingf1120be2020-08-03 18:01:40 -070011275 /**
11276 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11277 *
11278 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11279 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011280 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011281 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011282 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011283 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011284 mConnectivityDiagnosticsCallbacks.entrySet()) {
11285 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11286 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011287
James Mattis64b8b0f2020-11-24 17:40:49 -080011288 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011289 if (!nai.satisfies(nri.mRequests.get(0))) {
11290 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011291 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011292
11293 // UID for this callback must either be:
11294 // - INVALID_UID (which sends callbacks to all UIDs), or
11295 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11296 // notified as a result)
11297 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11298 continue;
11299 }
11300
11301 if (!checkConnectivityDiagnosticsPermissions(
11302 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11303 continue;
11304 }
11305
11306 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011307 }
11308 return results;
11309 }
11310
Cody Kesting7474f672021-05-11 14:22:40 -070011311 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11312 @NonNull NetworkAgentInfo nai) {
11313 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11314 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11315 }
11316
Cody Kesting160ef392021-05-05 13:17:22 -070011317 private boolean hasLocationPermission(String packageName, int uid) {
11318 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11319 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11320 // call in a try-catch.
11321 try {
11322 if (!mLocationPermissionChecker.checkLocationPermission(
11323 packageName, null /* featureId */, uid, null /* message */)) {
11324 return false;
11325 }
11326 } catch (SecurityException e) {
11327 return false;
11328 }
11329
11330 return true;
11331 }
11332
11333 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11334 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011335 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011336 && virtual.networkCapabilities.getOwnerUid() == uid
11337 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11338 return true;
11339 }
11340 }
11341
11342 return false;
11343 }
11344
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011345 @VisibleForTesting
11346 boolean checkConnectivityDiagnosticsPermissions(
11347 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
11348 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
11349 return true;
11350 }
11351
Cody Kesting160ef392021-05-05 13:17:22 -070011352 // Administrator UIDs also contains the Owner UID
11353 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11354 if (!CollectionUtils.contains(administratorUids, callbackUid)
11355 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011356 return false;
11357 }
11358
Cody Kesting7474f672021-05-11 14:22:40 -070011359 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
11360 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011361 }
11362
Cody Kestingd199a9d2019-12-17 12:55:28 -080011363 @Override
11364 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011365 @NonNull IConnectivityDiagnosticsCallback callback,
11366 @NonNull NetworkRequest request,
11367 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011368 Objects.requireNonNull(callback, "callback must not be null");
11369 Objects.requireNonNull(request, "request must not be null");
11370 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
11371
Cody Kesting73708bf2019-12-18 10:57:50 -080011372 if (request.legacyType != TYPE_NONE) {
11373 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
11374 + " Please use NetworkCapabilities instead.");
11375 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011376 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080011377 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011378
11379 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
11380 // and administrator uids to be safe.
11381 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080011382 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011383
11384 final NetworkRequest requestWithId =
11385 new NetworkRequest(
11386 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
11387
11388 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
11389 //
11390 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
11391 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
11392 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011393 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080011394 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011395 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011396
11397 mConnectivityDiagnosticsHandler.sendMessage(
11398 mConnectivityDiagnosticsHandler.obtainMessage(
11399 ConnectivityDiagnosticsHandler
11400 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
11401 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011402 }
11403
11404 @Override
11405 public void unregisterConnectivityDiagnosticsCallback(
11406 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011407 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080011408 mConnectivityDiagnosticsHandler.sendMessage(
11409 mConnectivityDiagnosticsHandler.obtainMessage(
11410 ConnectivityDiagnosticsHandler
11411 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011412 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080011413 0,
11414 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011415 }
Cody Kestingf53a0752020-04-15 12:33:28 -070011416
Yan Yanfe96dde2022-12-05 23:00:01 +000011417 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
11418 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
11419 if (underlyingNetworks == null) return false;
11420
11421 for (Network network : underlyingNetworks) {
11422 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
11423 return true;
11424 }
11425 }
11426 return false;
11427 }
11428
Cody Kestingf53a0752020-04-15 12:33:28 -070011429 @Override
11430 public void simulateDataStall(int detectionMethod, long timestampMillis,
11431 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011432 Objects.requireNonNull(network, "network must not be null");
11433 Objects.requireNonNull(extras, "extras must not be null");
11434
paulhu3ffffe72021-09-16 10:15:22 +080011435 enforceAnyPermissionOf(mContext,
11436 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070011437 android.Manifest.permission.NETWORK_STACK);
11438 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011439 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
11440 throw new SecurityException(
11441 "Data Stall simulation is only possible for test networks or networks built on"
11442 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070011443 }
11444
11445 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000011446 if (nai == null
11447 || (nai.creatorUid != mDeps.getCallingUid()
11448 && nai.creatorUid != Process.SYSTEM_UID)) {
11449 throw new SecurityException(
11450 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070011451 }
11452
Cody Kesting652e3ec2020-05-21 12:08:21 -070011453 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
11454 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
11455 // Data Stall information as a DataStallReportParcelable and passing to
11456 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
11457 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070011458 final DataStallReportParcelable p = new DataStallReportParcelable();
11459 p.timestampMillis = timestampMillis;
11460 p.detectionMethod = detectionMethod;
11461
11462 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
11463 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
11464 }
11465 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
11466 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
11467 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
11468 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
11469 }
11470
Serik Beketayevec8ad212020-12-07 22:43:07 -080011471 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070011472 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011473
lucaslin66f44212021-02-23 01:12:55 +080011474 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
11475 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080011476 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080011477 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080011478 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080011479 }
lucaslin37a16d92021-01-21 19:48:09 +080011480
11481 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011482 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080011483 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080011484 nai.clatd.interfaceLinkStateChanged(iface, up);
11485 }
11486 }
11487
11488 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090011489 public void onInterfaceRemoved(@NonNull String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080011490 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080011491 nai.clatd.interfaceRemoved(iface);
11492 }
lucaslin66f44212021-02-23 01:12:55 +080011493 }
11494 }
11495
lucaslin1a8b4c62021-01-21 02:02:55 +080011496 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
11497
11498 /**
11499 * Class used for updating network activity tracking with netd and notify network activity
11500 * changes.
11501 */
11502 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080011503 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080011504 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080011505 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080011506 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
11507 new RemoteCallbackList<>();
11508 // Indicate the current system default network activity is active or not.
11509 @GuardedBy("mActiveIdleTimers")
11510 private boolean mNetworkActive;
11511 @GuardedBy("mActiveIdleTimers")
Chalard Jean46bfbf02022-02-02 00:56:25 +090011512 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1193a5d2021-01-21 02:04:15 +080011513 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080011514
Chalard Jean46bfbf02022-02-02 00:56:25 +090011515 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080011516 public final int timeout;
11517 public final int transportType;
11518
11519 IdleTimerParams(int timeout, int transport) {
11520 this.timeout = timeout;
11521 this.transportType = transport;
11522 }
11523 }
11524
11525 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080011526 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080011527 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080011528 mNetd = netd;
11529 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080011530 }
11531
lucaslin66f44212021-02-23 01:12:55 +080011532 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
11533 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
11534 synchronized (mActiveIdleTimers) {
11535 mNetworkActive = active;
11536 // If there are no idle timers, it means that system is not monitoring
11537 // activity, so the system default network for those default network
11538 // unspecified apps is always considered active.
11539 //
11540 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
11541 // any network activity change event. Whenever this event is received,
11542 // the mActiveIdleTimers should be always not empty. The legacy behavior
11543 // is no-op. Remove to refer to mNetworkActive only.
11544 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
11545 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
11546 }
11547 }
11548 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011549
lucaslin1193a5d2021-01-21 02:04:15 +080011550 // The network activity should only be updated from ConnectivityService handler thread
11551 // when mActiveIdleTimers lock is held.
11552 @GuardedBy("mActiveIdleTimers")
11553 private void reportNetworkActive() {
11554 final int length = mNetworkActivityListeners.beginBroadcast();
11555 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
11556 try {
11557 for (int i = 0; i < length; i++) {
11558 try {
11559 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
11560 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011561 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080011562 }
11563 }
11564 } finally {
11565 mNetworkActivityListeners.finishBroadcast();
11566 }
11567 }
11568
11569 @GuardedBy("mActiveIdleTimers")
11570 public void handleReportNetworkActivity() {
11571 synchronized (mActiveIdleTimers) {
11572 reportNetworkActive();
11573 }
11574 }
11575
lucaslin1a8b4c62021-01-21 02:02:55 +080011576 // This is deprecated and only to support legacy use cases.
11577 private int transportTypeToLegacyType(int type) {
11578 switch (type) {
11579 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011580 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080011581 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011582 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080011583 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011584 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080011585 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090011586 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080011587 default:
11588 loge("Unexpected transport in transportTypeToLegacyType: " + type);
11589 }
11590 return ConnectivityManager.TYPE_NONE;
11591 }
11592
11593 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
11594 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
11595 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
11596 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
11597 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
11598 final long ident = Binder.clearCallingIdentity();
11599 try {
11600 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
11601 RECEIVE_DATA_ACTIVITY_CHANGE,
11602 null /* resultReceiver */,
11603 null /* scheduler */,
11604 0 /* initialCode */,
11605 null /* initialData */,
11606 null /* initialExtra */);
11607 } finally {
11608 Binder.restoreCallingIdentity(ident);
11609 }
11610 }
11611
11612 /**
11613 * Setup data activity tracking for the given network.
11614 *
11615 * Every {@code setupDataActivityTracking} should be paired with a
11616 * {@link #removeDataActivityTracking} for cleanup.
11617 */
11618 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
11619 final String iface = networkAgent.linkProperties.getInterfaceName();
11620
11621 final int timeout;
11622 final int type;
11623
11624 if (networkAgent.networkCapabilities.hasTransport(
11625 NetworkCapabilities.TRANSPORT_CELLULAR)) {
11626 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011627 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080011628 10);
11629 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11630 } else if (networkAgent.networkCapabilities.hasTransport(
11631 NetworkCapabilities.TRANSPORT_WIFI)) {
11632 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011633 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080011634 15);
11635 type = NetworkCapabilities.TRANSPORT_WIFI;
11636 } else {
11637 return; // do not track any other networks
11638 }
11639
lucaslinb961efc2021-01-21 02:03:17 +080011640 updateRadioPowerState(true /* isActive */, type);
11641
lucaslin1a8b4c62021-01-21 02:02:55 +080011642 if (timeout > 0 && iface != null) {
11643 try {
lucaslin1193a5d2021-01-21 02:04:15 +080011644 synchronized (mActiveIdleTimers) {
11645 // Networks start up.
11646 mNetworkActive = true;
11647 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
11648 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
11649 reportNetworkActive();
11650 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011651 } catch (Exception e) {
11652 // You shall not crash!
11653 loge("Exception in setupDataActivityTracking " + e);
11654 }
11655 }
11656 }
11657
11658 /**
11659 * Remove data activity tracking when network disconnects.
11660 */
11661 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
11662 final String iface = networkAgent.linkProperties.getInterfaceName();
11663 final NetworkCapabilities caps = networkAgent.networkCapabilities;
11664
lucaslinb961efc2021-01-21 02:03:17 +080011665 if (iface == null) return;
11666
11667 final int type;
11668 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
11669 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11670 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
11671 type = NetworkCapabilities.TRANSPORT_WIFI;
11672 } else {
11673 return; // do not track any other networks
11674 }
11675
11676 try {
11677 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080011678 synchronized (mActiveIdleTimers) {
11679 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
11680 // The call fails silently if no idle timer setup for this interface
11681 mNetd.idletimerRemoveInterface(iface, params.timeout,
11682 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080011683 }
lucaslinb961efc2021-01-21 02:03:17 +080011684 } catch (Exception e) {
11685 // You shall not crash!
11686 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080011687 }
11688 }
11689
11690 /**
11691 * Update data activity tracking when network state is updated.
11692 */
11693 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
11694 NetworkAgentInfo oldNetwork) {
11695 if (newNetwork != null) {
11696 setupDataActivityTracking(newNetwork);
11697 }
11698 if (oldNetwork != null) {
11699 removeDataActivityTracking(oldNetwork);
11700 }
11701 }
lucaslinb961efc2021-01-21 02:03:17 +080011702
11703 private void updateRadioPowerState(boolean isActive, int transportType) {
11704 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
11705 switch (transportType) {
11706 case NetworkCapabilities.TRANSPORT_CELLULAR:
11707 bs.reportMobileRadioPowerState(isActive, NO_UID);
11708 break;
11709 case NetworkCapabilities.TRANSPORT_WIFI:
11710 bs.reportWifiRadioPowerState(isActive, NO_UID);
11711 break;
11712 default:
11713 logw("Untracked transport type:" + transportType);
11714 }
11715 }
lucaslin1193a5d2021-01-21 02:04:15 +080011716
11717 public boolean isDefaultNetworkActive() {
11718 synchronized (mActiveIdleTimers) {
11719 // If there are no idle timers, it means that system is not monitoring activity,
11720 // so the default network is always considered active.
11721 //
11722 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
11723 // tracking is disabled (negative idle timer value configured), or no active default
11724 // network. In the latter case, this reports active but it should report inactive.
11725 return mNetworkActive || mActiveIdleTimers.isEmpty();
11726 }
11727 }
11728
11729 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
11730 mNetworkActivityListeners.register(l);
11731 }
11732
11733 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
11734 mNetworkActivityListeners.unregister(l);
11735 }
lucaslin012f7a12021-01-21 02:04:35 +080011736
11737 public void dump(IndentingPrintWriter pw) {
11738 synchronized (mActiveIdleTimers) {
11739 pw.print("mNetworkActive="); pw.println(mNetworkActive);
11740 pw.println("Idle timers:");
11741 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
11742 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
11743 final IdleTimerParams params = ent.getValue();
11744 pw.print(" timeout="); pw.print(params.timeout);
11745 pw.print(" type="); pw.println(params.transportType);
11746 }
11747 }
11748 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011749 }
James Mattis47db0582021-01-01 14:13:35 -080011750
Daniel Brightf9e945b2020-06-15 16:10:01 -070011751 /**
11752 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
11753 *
11754 * @param socketInfo the socket information
11755 * @param callback the callback to register
11756 */
11757 @Override
11758 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
11759 @NonNull final IQosCallback callback) {
11760 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
11761 if (nai == null || nai.networkCapabilities == null) {
11762 try {
11763 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
11764 } catch (final RemoteException ex) {
11765 loge("registerQosCallbackInternal: RemoteException", ex);
11766 }
11767 return;
11768 }
11769 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
11770 }
11771
11772 /**
11773 * Register a {@link IQosCallback} with base {@link QosFilter}.
11774 *
11775 * @param filter the filter to register
11776 * @param callback the callback to register
11777 * @param nai the agent information related to the filter's network
11778 */
11779 @VisibleForTesting
11780 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
11781 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011782 Objects.requireNonNull(filter, "filter must be non-null");
11783 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011784
11785 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080011786 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
11787 // on this network is unregistered when the app loses permission or b) no QoS
11788 // callbacks are sent for restricted networks unless the app currently has permission
11789 // to access restricted networks.
11790 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070011791 }
11792 mQosCallbackTracker.registerCallback(callback, filter, nai);
11793 }
11794
11795 /**
11796 * Unregisters the given callback.
11797 *
11798 * @param callback the callback to unregister
11799 */
11800 @Override
11801 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011802 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011803 mQosCallbackTracker.unregisterCallback(callback);
11804 }
James Mattis47db0582021-01-01 14:13:35 -080011805
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011806 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
11807 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
11808 // Enterprise device can be fully managed like device owner and such use case
11809 // also should be supported. Calling app check for work profile and fully managed device
11810 // is already done in DevicePolicyManager.
11811 // This check is an extra caution to be sure device is fully managed or not.
11812 final UserManager um = mContext.getSystemService(UserManager.class);
11813 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
11814 if (um.isManagedProfile(profile.getIdentifier())) {
11815 return true;
11816 }
Chalard Jean03552c42023-05-29 17:02:43 +090011817 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011818 return false;
11819 }
11820
James Mattis45d81842021-01-10 14:24:24 -080011821 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011822 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011823 *
11824 * See the documentation for the individual preferences for a description of the supported
11825 * behaviors.
11826 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011827 * @param profile If the device owner is set, any profile is allowed.
11828 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011829 * @param preferences the list of profile network preferences for the
11830 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011831 * @param listener an optional listener to listen for completion of the operation.
11832 */
11833 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011834 public void setProfileNetworkPreferences(
11835 @NonNull final UserHandle profile,
11836 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090011837 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011838 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011839 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011840
11841 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011842 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
11843 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
11844 .build();
11845 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011846 }
11847
paulhu3ffffe72021-09-16 10:15:22 +080011848 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011849 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011850 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011851 }
11852 if (profile.getIdentifier() < 0) {
11853 throw new IllegalArgumentException("Must explicitly specify a user handle ("
11854 + "UserHandle.CURRENT not supported)");
11855 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011856 if (!isNetworkPreferenceAllowedForProfile(profile)) {
11857 throw new IllegalArgumentException("Profile must be a managed profile "
11858 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011859 }
paulhuaa0743d2021-05-26 21:56:03 +080011860
Chalard Jean0606fc82022-12-14 20:34:43 +090011861 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011862 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011863 for (final ProfileNetworkPreference preference : preferences) {
11864 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011865 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080011866 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011867 switch (preference.getPreference()) {
11868 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
11869 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011870 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011871 if (preference.getPreferenceEnterpriseId() != 0) {
11872 throw new IllegalArgumentException(
11873 "Invalid enterprise identifier in setProfileNetworkPreferences");
11874 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011875 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080011876 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
11877 blockingNonEnterprise = true;
11878 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011879 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
11880 allowFallback = false;
11881 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011882 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011883 // This code is needed even though there is a check later on,
11884 // because isRangeAlreadyInPreferenceList assumes that every preference
11885 // has a UID list.
11886 if (hasDefaultPreference) {
11887 throw new IllegalArgumentException(
11888 "Default profile preference should not be set along with other "
11889 + "preference");
11890 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011891 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
11892 throw new IllegalArgumentException(
11893 "Invalid enterprise identifier in setProfileNetworkPreferences");
11894 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011895 final Set<UidRange> uidRangeSet =
11896 getUidListToBeAppliedForNetworkPreference(profile, preference);
11897 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
11898 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
11899 } else {
11900 throw new IllegalArgumentException(
11901 "Overlapping uid range in setProfileNetworkPreferences");
11902 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011903 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011904 nc.addEnterpriseId(
11905 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011906 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11907 break;
11908 default:
11909 throw new IllegalArgumentException(
11910 "Invalid preference in setProfileNetworkPreferences");
11911 }
Junyu Lai35665cc2022-12-19 17:37:48 +080011912 preferenceList.add(new ProfileNetworkPreferenceInfo(
11913 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011914 if (hasDefaultPreference && preferenceList.size() > 1) {
11915 throw new IllegalArgumentException(
11916 "Default profile preference should not be set along with other preference");
11917 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011918 }
11919 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011920 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011921 }
11922
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011923 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
11924 @NonNull final UserHandle profile,
11925 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
11926 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080011927 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
11928 profileNetworkPreference.getIncludedUids());
11929
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011930 if (uidRangeSet.size() > 0) {
11931 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
11932 throw new IllegalArgumentException(
11933 "Allow uid range is outside the uid range of profile.");
11934 }
11935 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080011936 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011937 profileNetworkPreference.getExcludedUids());
11938 if (disallowUidRangeSet.size() > 0) {
11939 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
11940 throw new IllegalArgumentException(
11941 "disallow uid range is outside the uid range of profile.");
11942 }
11943 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
11944 disallowUidRangeSet);
11945 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011946 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011947 uidRangeSet.add(profileUids);
11948 }
11949 }
11950 return uidRangeSet;
11951 }
11952
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011953 private boolean isEnterpriseIdentifierValid(
11954 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011955 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011956 return true;
11957 }
11958 return false;
11959 }
11960
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011961 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090011962 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011963 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090011964 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011965 // The NRI for a user should contain the request for capabilities.
11966 // If fallback to default network is needed then NRI should include
11967 // the request for the default network. Create an image of it to
11968 // have the correct UIDs in it (also a request can only be part of one NRI, because
11969 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011970 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
11971 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011972 if (pref.allowFallback) {
11973 nrs.add(createDefaultInternetRequestForTransport(
11974 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11975 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011976 if (VDBG) {
11977 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
11978 pref.capabilities.getUids()));
11979 }
11980
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011981 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080011982 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080011983 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011984 result.add(nri);
11985 }
11986 return result;
11987 }
11988
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011989 /**
11990 * Compare if the given UID range sets have the same UIDs.
11991 *
11992 */
11993 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090011994 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011995 @NonNull Set<UidRange> uidRangeSet) {
11996 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
11997 return false;
11998 }
Chalard Jean0606fc82022-12-14 20:34:43 +090011999 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012000 if (UidRangeUtils.doesRangeSetOverlap(
12001 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
12002 return true;
12003 }
12004 }
12005 return false;
12006 }
12007
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012008 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090012009 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012010 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012011 /*
12012 * handleSetProfileNetworkPreference is always called for single user.
12013 * preferenceList only contains preferences for different uids within the same user
12014 * (enforced by getUidListToBeAppliedForNetworkPreference).
12015 * Clear all the existing preferences for the user before applying new preferences.
12016 *
12017 */
Chalard Jean0606fc82022-12-14 20:34:43 +090012018 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
12019 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012020 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
12021 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012022
paulhu74128522021-09-28 02:29:03 +000012023 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
12024 addPerAppDefaultNetworkRequests(
12025 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080012026 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080012027
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012028 // Finally, rematch.
12029 rematchAllNetworksAndRequests();
12030
12031 if (null != listener) {
12032 try {
12033 listener.onComplete();
12034 } catch (RemoteException e) {
12035 loge("Listener for setProfileNetworkPreference has died");
12036 }
12037 }
12038 }
12039
paulhu51f77dc2021-06-07 02:34:20 +000012040 @VisibleForTesting
12041 @NonNull
12042 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12043 @NonNull final Set<Integer> uids) {
12044 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12045 if (uids.size() == 0) {
12046 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12047 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
12048 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
12049 return nris;
12050 }
12051
12052 final List<NetworkRequest> requests = new ArrayList<>();
12053 // The NRI should be comprised of two layers:
12054 // - The request for the mobile network preferred.
12055 // - The request for the default network, for fallback.
12056 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012057 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012058 requests.add(createDefaultInternetRequestForTransport(
12059 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12060 final Set<UidRange> ranges = new ArraySet<>();
12061 for (final int uid : uids) {
12062 ranges.add(new UidRange(uid, uid));
12063 }
12064 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080012065 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080012066 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000012067 return nris;
12068 }
12069
12070 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000012071 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000012072 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
12073 addPerAppDefaultNetworkRequests(
12074 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000012075 // Finally, rematch.
12076 rematchAllNetworksAndRequests();
12077 }
12078
Patrick Rohr2857ac42022-01-21 14:58:16 +010012079 private void handleIngressRateLimitChanged() {
12080 final long oldIngressRateLimit = mIngressRateLimit;
12081 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
12082 mContext);
12083 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
12084 if (canNetworkBeRateLimited(networkAgent)) {
12085 // If rate limit has previously been enabled, remove the old limit first.
12086 if (oldIngressRateLimit >= 0) {
12087 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
12088 }
12089 if (mIngressRateLimit >= 0) {
12090 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12091 mIngressRateLimit);
12092 }
12093 }
12094 }
12095 }
12096
12097 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012098 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jean03552c42023-05-29 17:02:43 +090012099 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012100
Patrick Rohrff3b3f82022-02-09 15:15:52 +010012101 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
12102 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
12103 // internet connectivity can be rate limited.
12104 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
12105 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010012106 return false;
12107 }
12108
12109 final String iface = networkAgent.linkProperties.getInterfaceName();
12110 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012111 // This may happen in tests, but if there is no interface then there is nothing that
12112 // can be rate limited.
12113 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012114 return false;
12115 }
12116 return true;
12117 }
12118
James Mattis45d81842021-01-10 14:24:24 -080012119 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012120 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12121 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012122 }
12123
12124 /**
12125 * Used by automotive devices to set the network preferences used to direct traffic at an
12126 * application level as per the given OemNetworkPreferences. An example use-case would be an
12127 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12128 * vehicle via a particular network.
12129 *
12130 * Calling this will overwrite the existing preference.
12131 *
James Mattisda32cfe2021-01-26 16:23:52 -080012132 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012133 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012134 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012135 */
James Mattis47db0582021-01-01 14:13:35 -080012136 @Override
James Mattis45d81842021-01-10 14:24:24 -080012137 public void setOemNetworkPreference(
12138 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012139 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012140
James Mattisfa270db2021-05-31 17:11:10 -070012141 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12142 // Only bypass the permission/device checks if this is a valid test request.
12143 if (isValidTestOemNetworkPreference(preference)) {
12144 enforceManageTestNetworksPermission();
12145 } else {
12146 enforceAutomotiveDevice();
12147 enforceOemNetworkPreferencesPermission();
12148 validateOemNetworkPreferences(preference);
12149 }
James Mattis45d81842021-01-10 14:24:24 -080012150
James Mattis45d81842021-01-10 14:24:24 -080012151 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
12152 new Pair<>(preference, listener)));
12153 }
12154
James Mattisfa270db2021-05-31 17:11:10 -070012155 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000012156 * Sets the specified UIDs to get/receive the VPN as the only default network.
12157 *
12158 * Calling this will overwrite the existing network preference for this session, and the
12159 * specified UIDs won't get any default network when no VPN is connected.
12160 *
12161 * @param session The VPN session which manages the passed UIDs.
12162 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
12163 * setting for this session if the array is empty. Null is not allowed, the
12164 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
12165 * @hide
12166 */
12167 @Override
12168 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
12169 Objects.requireNonNull(ranges);
12170 enforceNetworkStackOrSettingsPermission();
12171 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
12172 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
12173 throw new IllegalArgumentException(
12174 "setVpnNetworkPreference: Passed UID ranges overlap");
12175 }
12176
12177 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
12178 new VpnNetworkPreferenceInfo(session,
12179 new ArraySet<UidRange>(Arrays.asList(ranges)))));
12180 }
12181
12182 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
12183 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
12184
12185 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
12186 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
12187
12188 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
12189 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
12190 // Finally, rematch.
12191 rematchAllNetworksAndRequests();
12192 }
12193
12194 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
12195 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
12196 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12197 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
12198 final List<NetworkRequest> requests = new ArrayList<>();
12199 // Request VPN only, so other networks won't be the fallback options when VPN is not
12200 // connected temporarily.
12201 requests.add(createVpnRequest());
12202 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
12203 setNetworkRequestUids(requests, uidRanges);
12204 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
12205 }
12206 return nris;
12207 }
12208
12209 /**
James Mattisfa270db2021-05-31 17:11:10 -070012210 * Check the validity of an OEM network preference to be used for testing purposes.
12211 * @param preference the preference to validate
12212 * @return true if this is a valid OEM network preference test request.
12213 */
12214 private boolean isValidTestOemNetworkPreference(
12215 @NonNull final OemNetworkPreferences preference) {
12216 // Allow for clearing of an existing OemNetworkPreference used for testing.
12217 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
12218 // changes after this check is complete. This is an unlikely scenario as calling of this API
12219 // is controlled by the OEM therefore the added complexity is not worth adding given those
12220 // circumstances. That said, it is an edge case to be aware of hence this comment.
12221 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
12222 && isTestOemNetworkPreference(mOemNetworkPreferences);
12223 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
12224 }
12225
12226 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
12227 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
12228 return prefMap.size() == 1
12229 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
12230 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
12231 }
12232
James Mattis45d81842021-01-10 14:24:24 -080012233 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
12234 for (@OemNetworkPreferences.OemNetworkPreference final int pref
12235 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070012236 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
12237 throw new IllegalArgumentException(
12238 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
12239 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080012240 }
12241 }
12242 }
12243
12244 private void handleSetOemNetworkPreference(
12245 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012246 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080012247 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12248 if (DBG) {
12249 log("set OEM network preferences :" + preference.toString());
12250 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012251
James Mattiscb1e0362021-04-06 17:07:42 -070012252 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000012253 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
12254 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
12255 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080012256 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080012257
12258 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012259 try {
12260 listener.onComplete();
12261 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080012262 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090012263 }
James Mattis45d81842021-01-10 14:24:24 -080012264 }
12265 }
12266
paulhu74128522021-09-28 02:29:03 +000012267 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080012268 // Skip the requests which are set by other network preference. Because the uid range rules
12269 // should stay in netd.
12270 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080012271 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080012272 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080012273 }
12274
James Mattis3ce3d3c2021-02-09 18:18:28 -080012275 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
12276 ensureRunningOnConnectivityServiceThread();
12277 mDefaultNetworkRequests.addAll(nris);
12278 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
12279 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080012280 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000012281 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
12282 nrisToRegister.addAll(
12283 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
12284 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012285 }
12286
12287 /**
12288 * All current requests that are tracking the default network need to be assessed as to whether
12289 * or not the current set of per-application default requests will be changing their default
12290 * network. If so, those requests will need to be updated so that they will send callbacks for
12291 * default network changes at the appropriate time. Additionally, those requests tracking the
12292 * default that were previously updated by this flow will need to be reassessed.
12293 * @return the nris which will need to be updated.
12294 */
12295 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
12296 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
12297 // Get the distinct nris to check since for multilayer requests, it is possible to have the
12298 // same nri in the map's values for each of its NetworkRequest objects.
12299 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080012300 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012301 // Include this nri if it is currently being tracked.
12302 if (isPerAppTrackedNri(nri)) {
12303 defaultCallbackRequests.add(nri);
12304 continue;
12305 }
12306 // We only track callbacks for requests tracking the default.
12307 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
12308 continue;
12309 }
12310 // Include this nri if it will be tracked by the new per-app default requests.
12311 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012312 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080012313 if (isNriGoingToBeTracked) {
12314 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080012315 }
12316 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080012317 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080012318 }
12319
James Mattis3ce3d3c2021-02-09 18:18:28 -080012320 /**
12321 * Create nris for those network requests that are currently tracking the default network that
12322 * are being controlled by a per-application default.
12323 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
12324 * foundation when creating the nri. Important items include the calling uid's original
12325 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
12326 * requests are assumed to have already been validated as needing to be updated.
12327 * @return the Set of nris to use when registering network requests.
12328 */
12329 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
12330 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
12331 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
12332 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
12333 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012334 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012335
Chalard Jean9473c982021-07-29 20:03:04 +090012336 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080012337 if (trackingNri == mDefaultRequest) {
12338 callbackRequestsToRegister.add(new NetworkRequestInfo(
12339 callbackRequest,
12340 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
12341 continue;
12342 }
12343
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012344 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080012345 callbackRequestsToRegister.add(new NetworkRequestInfo(
12346 callbackRequest,
12347 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012348 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090012349 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080012350 }
12351 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080012352 }
12353
Chalard Jean17215832021-03-01 14:06:28 +090012354 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
12355 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090012356 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012357 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090012358 }
12359 }
12360
James Mattis45d81842021-01-10 14:24:24 -080012361 /**
12362 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
12363 */
12364 @VisibleForTesting
12365 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012366 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080012367 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080012368 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080012369 final SparseArray<Set<Integer>> uids =
12370 createUidsFromOemNetworkPreferences(preference);
12371 for (int i = 0; i < uids.size(); i++) {
12372 final int key = uids.keyAt(i);
12373 final Set<Integer> value = uids.valueAt(i);
12374 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
12375 // No need to add an nri without any requests.
12376 if (0 == nri.mRequests.size()) {
12377 continue;
12378 }
12379 nris.add(nri);
12380 }
12381
12382 return nris;
12383 }
12384
12385 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
12386 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070012387 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080012388 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080012389 final List<UserHandle> users =
12390 mContext.getSystemService(UserManager.class).getUserHandles(true);
12391 if (null == users || users.size() == 0) {
12392 if (VDBG || DDBG) {
12393 log("No users currently available for setting the OEM network preference.");
12394 }
James Mattisb6b6a432021-06-01 22:30:36 -070012395 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080012396 }
James Mattis45d81842021-01-10 14:24:24 -080012397 for (final Map.Entry<String, Integer> entry :
12398 preference.getNetworkPreferences().entrySet()) {
12399 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070012400 // Add the rules for all users as this policy is device wide.
12401 for (final UserHandle user : users) {
12402 try {
12403 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
12404 if (!prefToUids.contains(pref)) {
12405 prefToUids.put(pref, new ArraySet<>());
12406 }
12407 prefToUids.get(pref).add(uid);
12408 } catch (PackageManager.NameNotFoundException e) {
12409 // Although this may seem like an error scenario, it is ok that uninstalled
12410 // packages are sent on a network preference as the system will watch for
12411 // package installations associated with this network preference and update
12412 // accordingly. This is done to minimize race conditions on app install.
12413 continue;
James Mattis45d81842021-01-10 14:24:24 -080012414 }
James Mattis45d81842021-01-10 14:24:24 -080012415 }
12416 }
James Mattisb6b6a432021-06-01 22:30:36 -070012417 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080012418 }
12419
12420 private NetworkRequestInfo createNriFromOemNetworkPreferences(
12421 @OemNetworkPreferences.OemNetworkPreference final int preference,
12422 @NonNull final Set<Integer> uids) {
12423 final List<NetworkRequest> requests = new ArrayList<>();
12424 // Requests will ultimately be evaluated by order of insertion therefore it matters.
12425 switch (preference) {
12426 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
12427 requests.add(createUnmeteredNetworkRequest());
12428 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070012429 requests.add(createDefaultInternetRequestForTransport(
12430 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080012431 break;
12432 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
12433 requests.add(createUnmeteredNetworkRequest());
12434 requests.add(createOemPaidNetworkRequest());
12435 break;
12436 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
12437 requests.add(createOemPaidNetworkRequest());
12438 break;
12439 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
12440 requests.add(createOemPrivateNetworkRequest());
12441 break;
James Mattisfa270db2021-05-31 17:11:10 -070012442 case OEM_NETWORK_PREFERENCE_TEST:
12443 requests.add(createUnmeteredNetworkRequest());
12444 requests.add(createTestNetworkRequest());
12445 requests.add(createDefaultRequest());
12446 break;
12447 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
12448 requests.add(createTestNetworkRequest());
12449 break;
James Mattis45d81842021-01-10 14:24:24 -080012450 default:
12451 // This should never happen.
12452 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
12453 + " called with invalid preference of " + preference);
12454 }
12455
James Mattisfa270db2021-05-31 17:11:10 -070012456 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090012457 for (final int uid : uids) {
12458 ranges.add(new UidRange(uid, uid));
12459 }
12460 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080012461 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080012462 }
12463
12464 private NetworkRequest createUnmeteredNetworkRequest() {
12465 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12466 .addCapability(NET_CAPABILITY_NOT_METERED)
12467 .addCapability(NET_CAPABILITY_VALIDATED);
12468 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
12469 }
12470
12471 private NetworkRequest createOemPaidNetworkRequest() {
12472 // NET_CAPABILITY_OEM_PAID is a restricted capability.
12473 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12474 .addCapability(NET_CAPABILITY_OEM_PAID)
12475 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12476 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12477 }
12478
12479 private NetworkRequest createOemPrivateNetworkRequest() {
12480 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
12481 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
12482 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
12483 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12484 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
12485 }
12486
12487 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070012488 final NetworkCapabilities netcap = new NetworkCapabilities();
12489 netcap.addCapability(NET_CAPABILITY_INTERNET);
12490 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
12491 return netcap;
12492 }
12493
12494 private NetworkRequest createTestNetworkRequest() {
12495 final NetworkCapabilities netcap = new NetworkCapabilities();
12496 netcap.clearAll();
12497 netcap.addTransportType(TRANSPORT_TEST);
12498 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080012499 }
James Mattis47db0582021-01-01 14:13:35 -080012500 }
markchien738ad912021-12-09 18:15:45 +080012501
12502 @Override
12503 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
12504 enforceNetworkStackOrSettingsPermission();
12505
12506 try {
12507 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012508 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012509 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012510 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080012511 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012512 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012513 throw new IllegalStateException(e);
12514 }
12515 }
12516
12517 @Override
12518 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
12519 enforceNetworkStackOrSettingsPermission();
12520
12521 try {
12522 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012523 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012524 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012525 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080012526 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012527 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080012528 throw new IllegalStateException(e);
12529 }
12530 }
markchiene1561fa2021-12-09 22:00:56 +080012531
12532 @Override
markchien3c04e662022-03-22 16:29:56 +080012533 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080012534 enforceNetworkStackOrSettingsPermission();
12535
markchien3c04e662022-03-22 16:29:56 +080012536 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
12537 int firewallRule = getFirewallRuleType(chain, rule);
12538
12539 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
12540 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
12541 }
12542
markchiene1561fa2021-12-09 22:00:56 +080012543 try {
markchien3c04e662022-03-22 16:29:56 +080012544 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012545 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080012546 throw new IllegalStateException(e);
12547 }
12548 }
markchien98a6f952022-01-13 23:43:53 +080012549
Motomu Utsumi900b8062023-01-19 16:16:49 +090012550 @Override
12551 public int getUidFirewallRule(final int chain, final int uid) {
12552 enforceNetworkStackOrSettingsPermission();
12553 return mBpfNetMaps.getUidRule(chain, uid);
12554 }
12555
markchien3c04e662022-03-22 16:29:56 +080012556 private int getFirewallRuleType(int chain, int rule) {
12557 final int defaultRule;
12558 switch (chain) {
12559 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000012560 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
12561 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000012562 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080012563 defaultRule = FIREWALL_RULE_ALLOW;
12564 break;
12565 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
12566 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
12567 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
12568 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
12569 defaultRule = FIREWALL_RULE_DENY;
12570 break;
12571 default:
12572 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
12573 }
12574 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
12575
12576 return rule;
12577 }
12578
Motomu Utsumied1848c2023-03-28 18:08:12 +090012579 private void closeSocketsForFirewallChainLocked(final int chain)
12580 throws ErrnoException, SocketException, InterruptedIOException {
12581 if (mBpfNetMaps.isFirewallAllowList(chain)) {
12582 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
12583 // So, close all non-system socket owned by uids that are not explicitly allowed
12584 Set<Range<Integer>> ranges = new ArraySet<>();
12585 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
12586 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
12587 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
12588 } else {
12589 // Denylist means the firewall allows all by default, uids must be explicitly denied
12590 // So, close socket owned by uids that are explicitly denied
12591 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
12592 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
12593 }
12594 }
12595
markchien98a6f952022-01-13 23:43:53 +080012596 @Override
12597 public void setFirewallChainEnabled(final int chain, final boolean enable) {
12598 enforceNetworkStackOrSettingsPermission();
12599
12600 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080012601 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090012602 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080012603 throw new IllegalStateException(e);
12604 }
Motomu Utsumied1848c2023-03-28 18:08:12 +090012605
Chalard Jean03552c42023-05-29 17:02:43 +090012606 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumied1848c2023-03-28 18:08:12 +090012607 try {
12608 closeSocketsForFirewallChainLocked(chain);
12609 } catch (ErrnoException | SocketException | InterruptedIOException e) {
12610 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
12611 }
12612 }
markchien98a6f952022-01-13 23:43:53 +080012613 }
12614
markchien00a0bed2022-01-13 23:46:13 +080012615 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012616 public boolean getFirewallChainEnabled(final int chain) {
12617 enforceNetworkStackOrSettingsPermission();
12618
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000012619 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000012620 }
12621
12622 @Override
markchien00a0bed2022-01-13 23:46:13 +080012623 public void replaceFirewallChain(final int chain, final int[] uids) {
12624 enforceNetworkStackOrSettingsPermission();
12625
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000012626 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080012627 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080012628
12629 @Override
12630 public IBinder getCompanionDeviceManagerProxyService() {
12631 enforceNetworkStackPermission(mContext);
12632 return mCdmps;
12633 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070012634}